Ignore
This commit is contained in:
@@ -4,8 +4,10 @@ import com.ilummc.tlib.TLib;
|
||||
import me.skymc.taboolib.anvil.AnvilContainerAPI;
|
||||
import me.skymc.taboolib.bstats.Metrics;
|
||||
import me.skymc.taboolib.commands.MainCommands;
|
||||
import me.skymc.taboolib.commands.internal.InternalCommandExecutor;
|
||||
import me.skymc.taboolib.commands.language.Language2Command;
|
||||
import me.skymc.taboolib.commands.locale.TabooLibLocaleCommand;
|
||||
import me.skymc.taboolib.commands.plugin.TabooLibPluginCommand;
|
||||
import me.skymc.taboolib.commands.sub.itemlist.listener.ItemLibraryPatch;
|
||||
import me.skymc.taboolib.commands.sub.sounds.listener.SoundsLibraryPatch;
|
||||
import me.skymc.taboolib.database.GlobalDataManager;
|
||||
@@ -114,7 +116,7 @@ public class Main extends JavaPlugin implements Listener {
|
||||
}
|
||||
|
||||
public static Random getRandom() {
|
||||
return NumberUtils.getRand();
|
||||
return NumberUtils.getRandom();
|
||||
}
|
||||
|
||||
public static String getTablePrefix() {
|
||||
@@ -203,6 +205,7 @@ public class Main extends JavaPlugin implements Listener {
|
||||
getCommand("language2").setExecutor(new Language2Command());
|
||||
getCommand("taboolibrarymodule").setExecutor(new TLMCommands());
|
||||
getCommand("tabooliblocale").setExecutor(new TabooLibLocaleCommand());
|
||||
InternalCommandExecutor.createCommandExecutor("taboolibplugin", new TabooLibPluginCommand());
|
||||
|
||||
// 注册监听
|
||||
registerListener();
|
||||
|
||||
@@ -88,7 +88,7 @@ public class AnvilContainerAPI implements Listener {
|
||||
|
||||
@EventHandler
|
||||
public void example(PlayerCommandPreprocessEvent e) {
|
||||
if (e.getMessage().equals("/anvilexample")) {
|
||||
if ("/anvilexample".equals(e.getMessage())) {
|
||||
if (e.getPlayer().hasPermission("taboolib.admin")) {
|
||||
e.setCancelled(true);
|
||||
AnvilContainerAPI.send(e.getPlayer(), "EXAMPLE", "在这里输入文本", null);
|
||||
@@ -98,7 +98,7 @@ public class AnvilContainerAPI implements Listener {
|
||||
|
||||
@EventHandler
|
||||
public void example2(AnvilContainerAPIEvent e) {
|
||||
if (e.type.equals("EXAMPLE")) {
|
||||
if ("EXAMPLE".equals(e.type)) {
|
||||
e.event.getWhoClicked().sendMessage(e.string);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import java.util.regex.Pattern;
|
||||
/**
|
||||
* The NMS helper for all the Book-API
|
||||
*/
|
||||
@SuppressWarnings({"ALL", "AliControlFlowStatementWithoutBraces"})
|
||||
public final class BookReflection {
|
||||
|
||||
private static final String version;
|
||||
@@ -66,8 +67,10 @@ public final class BookReflection {
|
||||
craftMetaBookField = craftMetaBookClass.getDeclaredField("pages");
|
||||
craftMetaBookField.setAccessible(true);
|
||||
Class<?> chatSerializer = getNmsClass("IChatBaseComponent$ChatSerializer", false);
|
||||
if (chatSerializer == null)
|
||||
//noinspection AliControlFlowStatementWithoutBraces
|
||||
if (chatSerializer == null) {
|
||||
chatSerializer = getNmsClass("ChatSerializer");
|
||||
}
|
||||
|
||||
chatSerializerA = chatSerializer.getDeclaredMethod("a", String.class);
|
||||
|
||||
@@ -257,12 +260,15 @@ public final class BookReflection {
|
||||
return craftItemStackAsNMSCopy.invoke(null, item);
|
||||
}
|
||||
|
||||
@SuppressWarnings("AliControlFlowStatementWithoutBraces")
|
||||
public static Class<?> getNmsClass(String className, boolean log) {
|
||||
try {
|
||||
return Class.forName("net.minecraft.server." + version + "." + className);
|
||||
} catch (ClassNotFoundException e) {
|
||||
if (log)
|
||||
//noinspection AliControlFlowStatementWithoutBraces
|
||||
if (log) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,10 +35,11 @@ public interface ClickAction {
|
||||
* @return a new ClickAction
|
||||
*/
|
||||
static ClickAction openUrl(String url) {
|
||||
if (url.startsWith("http://") || url.startsWith("https://"))
|
||||
if (url.startsWith("http://") || url.startsWith("https://")) {
|
||||
return new SimpleClickAction(ClickEvent.Action.OPEN_URL, url);
|
||||
else
|
||||
} else {
|
||||
throw new IllegalArgumentException("Invalid url: \"" + url + "\", it should start with http:// or https://");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -107,8 +107,9 @@ public class PageBuilder {
|
||||
*/
|
||||
public static PageBuilder of(BaseComponent... text) {
|
||||
PageBuilder res = new PageBuilder();
|
||||
for(BaseComponent b : text)
|
||||
for(BaseComponent b : text) {
|
||||
res.add(b);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,6 @@
|
||||
package me.skymc.taboolib.bstats;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.logging.Level;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
|
||||
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
@@ -29,16 +10,29 @@ import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.json.simple.JSONArray;
|
||||
import org.json.simple.JSONObject;
|
||||
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.URL;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.logging.Level;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
/**
|
||||
* bStats collects some data for plugin authors.
|
||||
*
|
||||
* <p>
|
||||
* Check out https://bStats.org/ to learn more about bStats!
|
||||
*/
|
||||
public class Metrics {
|
||||
|
||||
static {
|
||||
// You can use the property to disable the check in your test environment
|
||||
if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) {
|
||||
if (System.getProperty("bstats.relocatecheck") == null || !"false".equals(System.getProperty("bstats.relocatecheck"))) {
|
||||
// Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D
|
||||
final String defaultPackage = new String(
|
||||
new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'});
|
||||
@@ -50,22 +44,34 @@ public class Metrics {
|
||||
}
|
||||
}
|
||||
|
||||
// The version of this bStats class
|
||||
/**
|
||||
* The version of this bStats class
|
||||
*/
|
||||
public static final int B_STATS_VERSION = 1;
|
||||
|
||||
// The url to which the data is sent
|
||||
/**
|
||||
* The url to which the data is sent
|
||||
*/
|
||||
private static final String URL = "https://bStats.org/submitData/bukkit";
|
||||
|
||||
// Should failed requests be logged?
|
||||
/**
|
||||
* Should failed requests be logged?
|
||||
*/
|
||||
private static boolean logFailedRequests;
|
||||
|
||||
// The uuid of the server
|
||||
/**
|
||||
* The uuid of the server
|
||||
*/
|
||||
private static String serverUUID;
|
||||
|
||||
// The plugin
|
||||
/**
|
||||
* The plugin
|
||||
*/
|
||||
private final JavaPlugin plugin;
|
||||
|
||||
// A list with all custom charts
|
||||
/**
|
||||
* A list with all custom charts
|
||||
*/
|
||||
private final List<CustomChart> charts = new ArrayList<>();
|
||||
|
||||
/**
|
||||
@@ -103,7 +109,8 @@ public class Metrics {
|
||||
).copyDefaults(true);
|
||||
try {
|
||||
config.save(configFile);
|
||||
} catch (IOException ignored) { }
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
// Load the data
|
||||
@@ -114,10 +121,13 @@ public class Metrics {
|
||||
// Search for all other bStats Metrics classes to see if we are the first one
|
||||
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
|
||||
try {
|
||||
service.getField("B_STATS_VERSION"); // Our identifier :)
|
||||
found = true; // We aren't the first
|
||||
// Our identifier :)
|
||||
service.getField("B_STATS_VERSION");
|
||||
// We aren't the first
|
||||
found = true;
|
||||
break;
|
||||
} catch (NoSuchFieldException ignored) { }
|
||||
} catch (NoSuchFieldException ignored) {
|
||||
}
|
||||
}
|
||||
// Register our service
|
||||
Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal);
|
||||
@@ -144,22 +154,23 @@ public class Metrics {
|
||||
* Starts the Scheduler which submits our data every 30 minutes.
|
||||
*/
|
||||
private void startSubmitting() {
|
||||
final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
|
||||
timer.scheduleAtFixedRate(new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (!plugin.isEnabled()) { // Plugin was disabled
|
||||
timer.cancel();
|
||||
return;
|
||||
}
|
||||
// Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
|
||||
// Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
|
||||
Bukkit.getScheduler().runTask(plugin, () -> submitData());
|
||||
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1, new BasicThreadFactory.Builder().namingPattern("metrics-schedule-pool-%d").daemon(true).build());
|
||||
executorService.scheduleAtFixedRate(() -> {
|
||||
if (!plugin.isEnabled()) {
|
||||
executorService.shutdown();
|
||||
return;
|
||||
}
|
||||
}, 1000*60*5, 1000*60*30);
|
||||
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
|
||||
// WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
|
||||
// WARNING: Just don't do it!
|
||||
/*
|
||||
* Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
|
||||
* Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
|
||||
*/
|
||||
Bukkit.getScheduler().runTask(plugin, this::submitData);
|
||||
/*
|
||||
* Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
|
||||
* WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
|
||||
* WARNING: Just don't do it!
|
||||
*/
|
||||
}, 5, 30, TimeUnit.MINUTES);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -174,13 +185,16 @@ public class Metrics {
|
||||
String pluginName = plugin.getDescription().getName();
|
||||
String pluginVersion = plugin.getDescription().getVersion();
|
||||
|
||||
data.put("pluginName", pluginName); // Append the name of the plugin
|
||||
data.put("pluginVersion", pluginVersion); // Append the version of the plugin
|
||||
// Append the name of the plugin
|
||||
data.put("pluginName", pluginName);
|
||||
// Append the version of the plugin
|
||||
data.put("pluginVersion", pluginVersion);
|
||||
JSONArray customCharts = new JSONArray();
|
||||
for (CustomChart customChart : charts) {
|
||||
// Add the data of the custom charts
|
||||
JSONObject chart = customChart.getRequestJsonObject();
|
||||
if (chart == null) { // If the chart is null, we skip it
|
||||
// If the chart is null, we skip it
|
||||
if (chart == null) {
|
||||
continue;
|
||||
}
|
||||
customCharts.add(chart);
|
||||
@@ -206,7 +220,8 @@ public class Metrics {
|
||||
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
|
||||
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
|
||||
} catch (Exception e) {
|
||||
playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
|
||||
// Just use the new method if the Reflection failed
|
||||
playerAmount = Bukkit.getOnlinePlayers().size();
|
||||
}
|
||||
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
|
||||
String bukkitVersion = org.bukkit.Bukkit.getVersion();
|
||||
@@ -246,20 +261,23 @@ public class Metrics {
|
||||
// Search for all other bStats Metrics classes to get their plugin data
|
||||
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
|
||||
try {
|
||||
service.getField("B_STATS_VERSION"); // Our identifier :)
|
||||
// Our identifier :)
|
||||
service.getField("B_STATS_VERSION");
|
||||
|
||||
for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) {
|
||||
try {
|
||||
pluginData.add(provider.getService().getMethod("getPluginData").invoke(provider.getProvider()));
|
||||
} catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { }
|
||||
} catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
|
||||
}
|
||||
}
|
||||
} catch (NoSuchFieldException ignored) { }
|
||||
} catch (NoSuchFieldException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
data.put("plugins", pluginData);
|
||||
|
||||
// Create a new thread for the connection to the bStats server
|
||||
new Thread(() -> {
|
||||
Executors.newSingleThreadExecutor().execute(() -> {
|
||||
try {
|
||||
// Send the data
|
||||
sendData(data);
|
||||
@@ -269,7 +287,7 @@ public class Metrics {
|
||||
plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -294,9 +312,11 @@ public class Metrics {
|
||||
connection.setRequestMethod("POST");
|
||||
connection.addRequestProperty("Accept", "application/json");
|
||||
connection.addRequestProperty("Connection", "close");
|
||||
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
|
||||
// We gzip our request
|
||||
connection.addRequestProperty("Content-Encoding", "gzip");
|
||||
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
|
||||
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
|
||||
// We send our data in JSON format
|
||||
connection.setRequestProperty("Content-Type", "application/json");
|
||||
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
|
||||
|
||||
// Send data
|
||||
@@ -306,7 +326,8 @@ public class Metrics {
|
||||
outputStream.flush();
|
||||
outputStream.close();
|
||||
|
||||
connection.getInputStream().close(); // We don't care about the response - Just send our data :)
|
||||
// We don't care about the response - Just send our data :)
|
||||
connection.getInputStream().close();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -332,7 +353,9 @@ public class Metrics {
|
||||
*/
|
||||
public static abstract class CustomChart {
|
||||
|
||||
// The id of the chart
|
||||
/**
|
||||
* The id of the chart
|
||||
*/
|
||||
final String chartId;
|
||||
|
||||
/**
|
||||
@@ -380,7 +403,7 @@ public class Metrics {
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public SimplePie(String chartId, Callable<String> callable) {
|
||||
@@ -411,7 +434,7 @@ public class Metrics {
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) {
|
||||
@@ -455,7 +478,7 @@ public class Metrics {
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) {
|
||||
@@ -504,7 +527,7 @@ public class Metrics {
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public SingleLineChart(String chartId, Callable<Integer> callable) {
|
||||
@@ -536,7 +559,7 @@ public class Metrics {
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) {
|
||||
@@ -581,7 +604,7 @@ public class Metrics {
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) {
|
||||
@@ -619,7 +642,7 @@ public class Metrics {
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) {
|
||||
|
||||
@@ -15,45 +15,45 @@ public class MainCommands implements CommandExecutor {
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
|
||||
if (args.length == 0 || args[0].equalsIgnoreCase("help")) {
|
||||
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.HELP");
|
||||
} else if (args[0].equalsIgnoreCase("save")) {
|
||||
if (args.length == 0 || "help".equalsIgnoreCase(args[0])) {
|
||||
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.HELP", label);
|
||||
} else if ("save".equalsIgnoreCase(args[0])) {
|
||||
new SaveCommand(sender, args);
|
||||
} else if (args[0].equalsIgnoreCase("enchants")) {
|
||||
} else if ("enchants".equalsIgnoreCase(args[0])) {
|
||||
new EnchantCommand(sender, args);
|
||||
} else if (args[0].equalsIgnoreCase("potions")) {
|
||||
} else if ("potions".equalsIgnoreCase(args[0])) {
|
||||
new PotionCommand(sender, args);
|
||||
} else if (args[0].equalsIgnoreCase("flags")) {
|
||||
} else if ("flags".equalsIgnoreCase(args[0])) {
|
||||
new FlagCommand(sender, args);
|
||||
} else if (args[0].equalsIgnoreCase("attributes")) {
|
||||
} else if ("attributes".equalsIgnoreCase(args[0])) {
|
||||
new AttributesCommand(sender, args);
|
||||
} else if (args[0].equalsIgnoreCase("slots")) {
|
||||
} else if ("slots".equalsIgnoreCase(args[0])) {
|
||||
new SlotCommand(sender, args);
|
||||
} else if (args[0].equalsIgnoreCase("importdata")) {
|
||||
} else if ("importdata".equalsIgnoreCase(args[0])) {
|
||||
new ImportCommand(sender, args);
|
||||
} else if (args[0].equalsIgnoreCase("iteminfo")) {
|
||||
} else if ("iteminfo".equalsIgnoreCase(args[0])) {
|
||||
new InfoCommand(sender, args);
|
||||
} else if (args[0].equalsIgnoreCase("itemlist")) {
|
||||
} else if ("itemlist".equalsIgnoreCase(args[0])) {
|
||||
new ItemListCommand(sender, args);
|
||||
} else if (args[0].equalsIgnoreCase("item") || args[0].equalsIgnoreCase("i")) {
|
||||
} else if ("item".equalsIgnoreCase(args[0]) || "i".equalsIgnoreCase(args[0])) {
|
||||
new ItemCommand(sender, args);
|
||||
} else if (args[0].equalsIgnoreCase("setvariable")) {
|
||||
} else if ("setvariable".equalsIgnoreCase(args[0])) {
|
||||
new VariableSetCommand(sender, args);
|
||||
} else if (args[0].equalsIgnoreCase("getvariable")) {
|
||||
} else if ("getvariable".equalsIgnoreCase(args[0])) {
|
||||
new VariableGetCommand(sender, args);
|
||||
} else if (args[0].equalsIgnoreCase("shell") || args[0].equalsIgnoreCase("s")) {
|
||||
} else if ("shell".equalsIgnoreCase(args[0]) || "s".equalsIgnoreCase(args[0])) {
|
||||
new ShellCommand(sender, args);
|
||||
} else if (args[0].equalsIgnoreCase("cycle") || args[0].equalsIgnoreCase("c")) {
|
||||
} else if ("cycle".equalsIgnoreCase(args[0]) || "c".equalsIgnoreCase(args[0])) {
|
||||
new CycleCommand(sender, args);
|
||||
} else if (args[0].equalsIgnoreCase("sounds")) {
|
||||
} else if ("sounds".equalsIgnoreCase(args[0])) {
|
||||
new SoundsCommand(sender, args);
|
||||
} else if (args[0].equalsIgnoreCase("tagprefix")) {
|
||||
} else if ("tagprefix".equalsIgnoreCase(args[0])) {
|
||||
new TagPrefixCommand(sender, args);
|
||||
} else if (args[0].equalsIgnoreCase("tagsuffix")) {
|
||||
} else if ("tagsuffix".equalsIgnoreCase(args[0])) {
|
||||
new TagSuffixCommand(sender, args);
|
||||
} else if (args[0].equalsIgnoreCase("tagdelete")) {
|
||||
} else if ("tagdelete".equalsIgnoreCase(args[0])) {
|
||||
new TagDeleteCommand(sender, args);
|
||||
} else if (args[0].equalsIgnoreCase("itemreload") || args[0].equalsIgnoreCase("ireload")) {
|
||||
} else if ("itemreload".equalsIgnoreCase(args[0]) || "ireload".equalsIgnoreCase(args[0])) {
|
||||
ItemUtils.reloadItemCache();
|
||||
ItemUtils.reloadItemName();
|
||||
TLocale.sendTo(sender, "COMMANDS.RELOAD.SUCCESS-NORMAL");
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package me.skymc.taboolib.commands.internal;
|
||||
|
||||
/**
|
||||
* @author Bkm016
|
||||
* @since 2018-04-17
|
||||
*/
|
||||
public class InternalArgument {
|
||||
|
||||
private String name;
|
||||
private boolean required;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public boolean isRequired() {
|
||||
return required;
|
||||
}
|
||||
|
||||
public InternalArgument(String name, boolean required) {
|
||||
this.name = name;
|
||||
this.required = required;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return required ? "§7[§8" + name + "§7]" : "§7<§8" + name + "§7>";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package me.skymc.taboolib.commands.internal;
|
||||
|
||||
/**
|
||||
* @Author sky
|
||||
* @Since 2018-05-07 21:36
|
||||
*/
|
||||
public interface InternalCommand {
|
||||
|
||||
String getCommandTitle();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package me.skymc.taboolib.commands.internal;
|
||||
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import me.skymc.taboolib.Main;
|
||||
import me.skymc.taboolib.TabooLib;
|
||||
import me.skymc.taboolib.string.ArrayUtils;
|
||||
import me.skymc.taboolib.string.StringUtils;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.*;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* @Author sky
|
||||
* @Since 2018-05-07 21:38
|
||||
*/
|
||||
public abstract class InternalCommandExecutor implements InternalCommand, CommandExecutor, TabExecutor {
|
||||
|
||||
private InternalCommandExecutor subExecutor;
|
||||
private List<InternalSubCommandExecutor> subCommandExecutors = new ArrayList<>();
|
||||
|
||||
public static InternalCommandExecutor createCommandExecutor(String command, InternalCommandExecutor internalCommandExecutor) {
|
||||
assert Bukkit.getPluginCommand(command) == null : "PluginCommand \"" + command + "\"not found";
|
||||
assert internalCommandExecutor != null : "Executor can not be null";
|
||||
assert internalCommandExecutor.getCommandTitle() != null : "Executor title can not be null";
|
||||
assert internalCommandExecutor.getClass() != InternalCommandExecutor.class : "SubExecutor can not be \"InternalCommandExecutor.class\"";
|
||||
internalCommandExecutor.setSubExecutor(internalCommandExecutor);
|
||||
Bukkit.getPluginCommand(command).setExecutor(internalCommandExecutor);
|
||||
Bukkit.getPluginCommand(command).setTabCompleter(internalCommandExecutor);
|
||||
return internalCommandExecutor;
|
||||
}
|
||||
|
||||
public void setSubExecutor(InternalCommandExecutor subExecutor) {
|
||||
this.subExecutor = subExecutor;
|
||||
}
|
||||
|
||||
public InternalCommandExecutor getSubExecutor() {
|
||||
return subExecutor;
|
||||
}
|
||||
|
||||
public List<InternalSubCommandExecutor> getSubCommandExecutors() {
|
||||
return subCommandExecutors;
|
||||
}
|
||||
|
||||
public void registerSubCommandExecutor(InternalSubCommandExecutor subCommandExecutor) {
|
||||
assert subCommandExecutor.getLabel() != null : "Command label can not be null";
|
||||
assert subCommandExecutor.getDescription() != null : "Command description can not be null";
|
||||
assert subCommandExecutor.getArguments() != null : "Command arguments can not be null";
|
||||
subCommandExecutors.add(subCommandExecutor);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (args.length == 0) {
|
||||
helpCommand(sender, label);
|
||||
} else {
|
||||
for (InternalSubCommandExecutor subCommand : subCommandExecutors) {
|
||||
if (subCommand == null || !args[0].equalsIgnoreCase(subCommand.getLabel())) {
|
||||
continue;
|
||||
}
|
||||
if (!isConfirmType(sender, subCommand.getType())) {
|
||||
TLocale.sendTo(sender, "COMMANDS.INTERNAL.ONLY-PLAYER", args[0], TLocale.asString("COMMANDS.INTERNAL.TYPE-" + subCommand.getType()));
|
||||
return true;
|
||||
}
|
||||
String[] subCommandArgs = ArrayUtils.removeFirst(args);
|
||||
if (subCommand.isParameterConform(subCommandArgs)) {
|
||||
subCommand.onCommand(sender, command, label, subCommandArgs);
|
||||
} else {
|
||||
TLocale.sendTo(sender, "COMMANDS.INTERNAL.ERROR-USAGE", args[0], subCommand.getCommandString(label));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
new BukkitRunnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
List<InternalSubCommandExecutor> commandCompute = subCommandExecutors.stream().filter(Objects::nonNull).sorted((b, a) -> Double.compare(StringUtils.similarDegree(args[0], a.getLabel()), StringUtils.similarDegree(args[0], b.getLabel()))).collect(Collectors.toList());
|
||||
if (commandCompute.size() > 0) {
|
||||
TLocale.sendTo(sender, "COMMANDS.INTERNAL.ERROR-COMMAND", args[0], commandCompute.get(0).getCommandString(label).trim());
|
||||
}
|
||||
}
|
||||
}.runTaskAsynchronously(Main.getInst());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] args) {
|
||||
return args.length == 1 ? subCommandExecutors.stream().filter(internalCommandExecutor -> internalCommandExecutor != null && (args[0].isEmpty() || internalCommandExecutor.getLabel().startsWith(args[0]))).map(InternalSubCommand::getLabel).collect(Collectors.toList()) : null;
|
||||
}
|
||||
|
||||
private String getEmptyLine() {
|
||||
return TabooLib.getVerint() < 10800 ? "~" : "";
|
||||
}
|
||||
|
||||
private void helpCommand(CommandSender sender, String label) {
|
||||
sender.sendMessage(getEmptyLine());
|
||||
sender.sendMessage(subExecutor.getCommandTitle());
|
||||
sender.sendMessage(getEmptyLine());
|
||||
subCommandExecutors.stream().map(subCommand -> subCommand == null ? getEmptyLine() : subCommand.getCommandString(label)).forEach(sender::sendMessage);
|
||||
sender.sendMessage(getEmptyLine());
|
||||
}
|
||||
|
||||
private boolean isConfirmType(CommandSender sender, InternalSubCommandType commandType) {
|
||||
return commandType == InternalSubCommandType.ALL || sender instanceof ConsoleCommandSender && commandType == InternalSubCommandType.CONSOLE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package me.skymc.taboolib.commands.internal;
|
||||
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
/**
|
||||
* @author Bkm016
|
||||
* @since 2018-04-17
|
||||
*/
|
||||
public interface InternalSubCommand {
|
||||
|
||||
String getLabel();
|
||||
|
||||
String getDescription();
|
||||
|
||||
InternalArgument[] getArguments();
|
||||
|
||||
void onCommand(CommandSender sender, Command command, String label, String[] args);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package me.skymc.taboolib.commands.internal;
|
||||
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
/**
|
||||
* @author Bkm016
|
||||
* @since 2018-04-17
|
||||
*/
|
||||
public abstract class InternalSubCommandExecutor implements InternalSubCommand {
|
||||
|
||||
public InternalSubCommandType getType() {
|
||||
return InternalSubCommandType.ALL;
|
||||
}
|
||||
|
||||
public boolean requiredPlayer() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isParameterConform(String[] args) {
|
||||
return IntStream.range(0, getArguments().length).noneMatch(i -> getArguments()[i].isRequired() && (args == null || args.length <= i));
|
||||
}
|
||||
|
||||
public String getCommandString(String label) {
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
stringBuilder.append(" §f/");
|
||||
stringBuilder.append(label);
|
||||
stringBuilder.append(" ");
|
||||
stringBuilder.append(getLabel());
|
||||
stringBuilder.append(" ");
|
||||
for (InternalArgument parameter : getArguments()) {
|
||||
stringBuilder.append(parameter.toString());
|
||||
stringBuilder.append(" ");
|
||||
}
|
||||
stringBuilder.append("§6- §e");
|
||||
stringBuilder.append(getDescription());
|
||||
return stringBuilder.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package me.skymc.taboolib.commands.internal;
|
||||
|
||||
/**
|
||||
* @author Bkm016
|
||||
* @since 2018-04-17
|
||||
*/
|
||||
public enum InternalSubCommandType {
|
||||
|
||||
CONSOLE, PLAYER, ALL
|
||||
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package me.skymc.taboolib.commands.language;
|
||||
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import me.skymc.taboolib.Main;
|
||||
import me.skymc.taboolib.message.MsgUtils;
|
||||
import me.skymc.taboolib.string.language2.Language2Value;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
@@ -16,64 +16,57 @@ import org.bukkit.entity.Player;
|
||||
*/
|
||||
public class Language2Command implements CommandExecutor {
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
|
||||
if (args.length == 0) {
|
||||
sender.sendMessage("§f");
|
||||
sender.sendMessage("§b§l----- §3§lLanguage2 Commands §b§l-----");
|
||||
sender.sendMessage("§f");
|
||||
sender.sendMessage("§f /language2 send §8[§7玩家/ALL§8] §8[§7语言§8] §8<§7变量§8> §6- §e发送语言提示");
|
||||
sender.sendMessage("§f /language2 reload §6- §e重载语言库");
|
||||
sender.sendMessage("§f");
|
||||
}
|
||||
else if (args[0].equalsIgnoreCase("reload")) {
|
||||
MsgUtils.send(sender, "§7重载中..");
|
||||
long time = System.currentTimeMillis();
|
||||
Main.getExampleLanguage2().reload();
|
||||
MsgUtils.send(sender, "§7重载完成! 耗时: &f" + (System.currentTimeMillis() - time) + "ms");
|
||||
}
|
||||
else if (args[0].equalsIgnoreCase("send")) {
|
||||
if (args.length < 3) {
|
||||
MsgUtils.send(sender, "§4参数错误");
|
||||
}
|
||||
else {
|
||||
// 时间
|
||||
long time = System.currentTimeMillis();
|
||||
|
||||
// 获取语言文件
|
||||
Language2Value value = Main.getExampleLanguage2().get(args[2]);
|
||||
// 如果有变量参数
|
||||
if (args.length > 3) {
|
||||
int i = 0;
|
||||
for (String variable : args[3].split("\\|")) {
|
||||
value.addPlaceholder("$" + i, variable);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
// 如果是公告
|
||||
if (args[1].equals("ALL")) {
|
||||
// 发送信息
|
||||
value.broadcast();
|
||||
}
|
||||
else {
|
||||
// 获取玩家
|
||||
Player player = Bukkit.getPlayerExact(args[1]);
|
||||
if (player == null) {
|
||||
MsgUtils.send(sender, "§4玩家不在线");
|
||||
}
|
||||
else {
|
||||
// 发送信息
|
||||
value.send(player);
|
||||
}
|
||||
}
|
||||
|
||||
// 如果发送者是玩家
|
||||
if (sender instanceof Player && ((Player) sender).getItemInHand().getType().equals(Material.COMMAND)) {
|
||||
MsgUtils.send(sender, "§7信息已发送, 本次计算耗时: &f" + (System.currentTimeMillis() - time) + "ms");
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
|
||||
if (args.length == 0) {
|
||||
TLocale.sendTo(sender, "COMMANDS.LANGUAGE2.HELP", label);
|
||||
} else if ("reload".equalsIgnoreCase(args[0])) {
|
||||
reload(sender);
|
||||
} else if ("send".equalsIgnoreCase(args[0])) {
|
||||
send(sender, args);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void send(CommandSender sender, String[] args) {
|
||||
if (args.length < 3) {
|
||||
TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN");
|
||||
} else {
|
||||
long time = System.currentTimeMillis();
|
||||
Language2Value value = getLanguage2Value(args);
|
||||
|
||||
if ("ALL".equalsIgnoreCase(args[1])) {
|
||||
value.broadcast();
|
||||
} else {
|
||||
Player player = Bukkit.getPlayerExact(args[1]);
|
||||
if (player == null) {
|
||||
TLocale.sendTo(sender, "COMMANDS.LANGUAGE2.INVALID-PLAYER", args[1]);
|
||||
} else {
|
||||
value.send(player);
|
||||
}
|
||||
}
|
||||
|
||||
if (sender instanceof Player && ((Player) sender).getItemInHand().getType().equals(Material.COMMAND)) {
|
||||
TLocale.sendTo(sender, "COMMANDS.LANGUAGE2.SUCCESS-SEND", String.valueOf(System.currentTimeMillis() - time));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Language2Value getLanguage2Value(String[] args) {
|
||||
Language2Value value = Main.getExampleLanguage2().get(args[2]);
|
||||
if (args.length > 3) {
|
||||
int i = 0;
|
||||
for (String variable : args[3].split("\\|")) {
|
||||
value.addPlaceholder("$" + i++, variable);
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private void reload(CommandSender sender) {
|
||||
TLocale.sendTo(sender, "COMMANDS.RELOAD.LOADING");
|
||||
long time = System.currentTimeMillis();
|
||||
Main.getExampleLanguage2().reload();
|
||||
TLocale.sendTo(sender, "COMMANDS.RELOAD.SUCCESS-ELAPSED-TIME", String.valueOf(System.currentTimeMillis() - time));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package me.skymc.taboolib.commands.locale;
|
||||
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import me.skymc.taboolib.message.MsgUtils;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandExecutor;
|
||||
@@ -21,35 +20,31 @@ public class TabooLibLocaleCommand implements CommandExecutor {
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, Command arg1, String label, String[] args) {
|
||||
if (args.length == 0) {
|
||||
sender.sendMessage("§f");
|
||||
sender.sendMessage("§b§l----- §3§lTabooLibLoacle Commands §b§l-----");
|
||||
sender.sendMessage("§f");
|
||||
sender.sendMessage("§f /tloacle send §8[§7玩家/ALL§8] §8[§7语言§8] §8<§7变量§8> §6- §e发送语言提示");
|
||||
sender.sendMessage("§f /tloacle reload §6- §e重载语言库");
|
||||
sender.sendMessage("§f");
|
||||
} else if (args[0].equalsIgnoreCase("send")) {
|
||||
TLocale.sendTo(sender, "COMMANDS.TLOCALE.HELP", label);
|
||||
} else if ("send".equalsIgnoreCase(args[0])) {
|
||||
send(sender, args);
|
||||
} else if (args[0].equalsIgnoreCase("reload")) {
|
||||
} else if ("reload".equalsIgnoreCase(args[0])) {
|
||||
reload(sender);
|
||||
} else {
|
||||
MsgUtils.send(sender, "§4参数错误");
|
||||
TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void send(CommandSender sender, String[] args) {
|
||||
if (args.length < 3) {
|
||||
MsgUtils.send(sender, "§4参数错误");
|
||||
TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN");
|
||||
return;
|
||||
}
|
||||
|
||||
long time = System.currentTimeMillis();
|
||||
List<Player> target = new ArrayList<>();
|
||||
if (args[1].equalsIgnoreCase("all")) {
|
||||
if ("all".equalsIgnoreCase(args[1])) {
|
||||
target.addAll(Bukkit.getOnlinePlayers());
|
||||
} else {
|
||||
Player player = Bukkit.getPlayerExact(args[1]);
|
||||
if (player == null) {
|
||||
MsgUtils.send(sender, "§4玩家不在线");
|
||||
TLocale.sendTo(sender, "COMMANDS.TLOCALE.INVALID-PLAYER", args[1]);
|
||||
return;
|
||||
}
|
||||
target.add(player);
|
||||
@@ -64,13 +59,13 @@ public class TabooLibLocaleCommand implements CommandExecutor {
|
||||
}
|
||||
|
||||
if (sender instanceof Player) {
|
||||
MsgUtils.send(sender, "§7信息已发送");
|
||||
TLocale.sendTo(sender, "COMMANDS.TLOCALE.SUCCESS-SEND", String.valueOf(System.currentTimeMillis() - time));
|
||||
}
|
||||
}
|
||||
|
||||
void reload(CommandSender sender) {
|
||||
TLocale.reload();
|
||||
MsgUtils.send(sender, "§7重载完成");
|
||||
TLocale.sendTo(sender, "COMMANDS.TLOCALE.SUCCESS-RELOAD");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
package me.skymc.taboolib.commands.plugin;
|
||||
|
||||
import com.google.common.base.Joiner;
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import me.skymc.taboolib.commands.internal.InternalArgument;
|
||||
import me.skymc.taboolib.commands.internal.InternalCommandExecutor;
|
||||
import me.skymc.taboolib.commands.internal.InternalSubCommandExecutor;
|
||||
import me.skymc.taboolib.plugin.PluginUtils;
|
||||
import me.skymc.taboolib.string.ArrayUtils;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* @Author sky
|
||||
* @Since 2018-05-07 20:14
|
||||
*/
|
||||
public class TabooLibPluginCommand extends InternalCommandExecutor {
|
||||
|
||||
public TabooLibPluginCommand() {
|
||||
listCommand();
|
||||
infoCommand();
|
||||
loadCommand();
|
||||
unloadCommand();
|
||||
reloadCommand();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getCommandTitle() {
|
||||
return TLocale.asString("COMMANDS.TPLUGIN.COMMAND-TITLE");
|
||||
}
|
||||
|
||||
void loadCommand() {
|
||||
registerSubCommandExecutor(new InternalSubCommandExecutor() {
|
||||
|
||||
@Override
|
||||
public String getLabel() {
|
||||
return "load";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return TLocale.asString("COMMANDS.TPLUGIN.LOAD.DESCRIPTION");
|
||||
}
|
||||
|
||||
@Override
|
||||
public InternalArgument[] getArguments() {
|
||||
return new InternalArgument[]{new InternalArgument(TLocale.asString("COMMANDS.TPLUGIN.LOAD.ARGUMENTS.0"), true)};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
String name = ArrayUtils.arrayJoin(args, 0);
|
||||
if (PluginUtils.getPluginByName(name) != null) {
|
||||
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.INVALID-PLUGIN", name);
|
||||
} else {
|
||||
switch (PluginUtils.load(name)) {
|
||||
case "loaded": {
|
||||
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.LOAD-SUCCESS", name);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.LOAD-FALL", name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void unloadCommand() {
|
||||
registerSubCommandExecutor(new InternalSubCommandExecutor() {
|
||||
|
||||
@Override
|
||||
public String getLabel() {
|
||||
return "unload";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return TLocale.asString("COMMANDS.TPLUGIN.UNLOAD.DESCRIPTION");
|
||||
}
|
||||
|
||||
@Override
|
||||
public InternalArgument[] getArguments() {
|
||||
return new InternalArgument[]{new InternalArgument(TLocale.asString("COMMANDS.TPLUGIN.UNLOAD.ARGUMENTS.0"), true)};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
String name = ArrayUtils.arrayJoin(args, 0);
|
||||
Plugin plugin = PluginUtils.getPluginByName(name);
|
||||
if (plugin == null) {
|
||||
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.INVALID-PLUGIN", name);
|
||||
} else if (PluginUtils.isIgnored(plugin)) {
|
||||
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.INVALID-PLUGIN-IGNORED", name);
|
||||
} else {
|
||||
switch (PluginUtils.unload(plugin)) {
|
||||
case "unloaded": {
|
||||
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.UNLOAD-SUCCESS", name);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.UNLOAD-FALL", name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void reloadCommand() {
|
||||
registerSubCommandExecutor(new InternalSubCommandExecutor() {
|
||||
|
||||
@Override
|
||||
public String getLabel() {
|
||||
return "reload";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return TLocale.asString("COMMANDS.TPLUGIN.RELOAD.DESCRIPTION");
|
||||
}
|
||||
|
||||
@Override
|
||||
public InternalArgument[] getArguments() {
|
||||
return new InternalArgument[]{new InternalArgument(TLocale.asString("COMMANDS.TPLUGIN.RELOAD.ARGUMENTS.0"), true)};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
String name = ArrayUtils.arrayJoin(args, 0);
|
||||
Plugin plugin = PluginUtils.getPluginByName(name);
|
||||
if (plugin == null) {
|
||||
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.RELOAD.INVALID-PLUGIN", name);
|
||||
} else if (PluginUtils.isIgnored(plugin)) {
|
||||
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.RELOAD.INVALID-PLUGIN-IGNORED", name);
|
||||
} else {
|
||||
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.RELOAD.TRY-RELOAD");
|
||||
PluginUtils.reload(plugin);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void infoCommand() {
|
||||
registerSubCommandExecutor(new InternalSubCommandExecutor() {
|
||||
|
||||
@Override
|
||||
public String getLabel() {
|
||||
return "info";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return TLocale.asString("COMMANDS.TPLUGIN.INFO.DESCRIPTION");
|
||||
}
|
||||
|
||||
@Override
|
||||
public InternalArgument[] getArguments() {
|
||||
return new InternalArgument[]{new InternalArgument(TLocale.asString("COMMANDS.TPLUGIN.INFO.ARGUMENTS.0"), true)};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
String name = ArrayUtils.arrayJoin(args, 0);
|
||||
Plugin plugin = PluginUtils.getPluginByName(name);
|
||||
if (plugin == null) {
|
||||
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.INFO.INVALID-PLUGIN", name);
|
||||
} else {
|
||||
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.INFO.INFO-PLUGIN",
|
||||
plugin.getName(),
|
||||
String.valueOf(plugin.getDescription().getDescription()),
|
||||
String.valueOf(plugin.getDescription().getAuthors()),
|
||||
String.valueOf(plugin.getDescription().getDepend()),
|
||||
String.valueOf(plugin.getDescription().getSoftDepend()),
|
||||
String.valueOf(plugin.getDescription().getMain()),
|
||||
String.valueOf(plugin.getDescription().getVersion()),
|
||||
String.valueOf(plugin.getDescription().getWebsite()),
|
||||
String.valueOf(plugin.getDescription().getCommands().keySet()));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void listCommand() {
|
||||
registerSubCommandExecutor(new InternalSubCommandExecutor() {
|
||||
|
||||
@Override
|
||||
public String getLabel() {
|
||||
return "list";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return TLocale.asString("COMMANDS.TPLUGIN.LIST.DESCRIPTION");
|
||||
}
|
||||
|
||||
@Override
|
||||
public InternalArgument[] getArguments() {
|
||||
return new InternalArgument[0];
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
List<String> pluginList = Arrays.stream(Bukkit.getPluginManager().getPlugins()).map(Plugin::getName).sorted(String.CASE_INSENSITIVE_ORDER).collect(Collectors.toList());
|
||||
TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LIST.LIST-PLUGIN", String.valueOf(Bukkit.getPluginManager().getPlugins().length), Joiner.on(", ").join(pluginList));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -62,7 +62,7 @@ public class SaveCommand extends SubCommand {
|
||||
@SuppressWarnings("deprecation")
|
||||
@Override
|
||||
public boolean after(String message) {
|
||||
if (message.equalsIgnoreCase("yes")) {
|
||||
if ("yes".equalsIgnoreCase(message)) {
|
||||
saveItem(args[1], ((Player) sender).getItemInHand());
|
||||
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SAVE.SUCCESS", args[1]);
|
||||
} else {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
package me.skymc.taboolib.commands.sub;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import me.skymc.taboolib.commands.SubCommand;
|
||||
import me.skymc.taboolib.message.MsgUtils;
|
||||
import me.skymc.taboolib.team.TagManager;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/**
|
||||
* @author sky
|
||||
@@ -14,27 +14,23 @@ import me.skymc.taboolib.team.TagManager;
|
||||
*/
|
||||
public class TagDeleteCommand extends SubCommand {
|
||||
|
||||
/**
|
||||
* @param sender
|
||||
* @param args
|
||||
*/
|
||||
public TagDeleteCommand(CommandSender sender, String[] args) {
|
||||
super(sender, args);
|
||||
if (args.length < 2) {
|
||||
MsgUtils.send(sender, "参数错误");
|
||||
return;
|
||||
}
|
||||
|
||||
Player player = Bukkit.getPlayerExact(args[1]);
|
||||
if (player == null) {
|
||||
MsgUtils.send(sender, "玩家 &f" + args[1] + " &7不在线");
|
||||
return;
|
||||
}
|
||||
|
||||
TagManager.getInst().removeData(player);
|
||||
if (sender instanceof Player) {
|
||||
MsgUtils.send(sender, "删除玩家 &f" + args[1] + " &7的称号数据");
|
||||
}
|
||||
}
|
||||
public TagDeleteCommand(CommandSender sender, String[] args) {
|
||||
super(sender, args);
|
||||
if (args.length < 2) {
|
||||
TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN");
|
||||
return;
|
||||
}
|
||||
|
||||
Player player = Bukkit.getPlayerExact(args[1]);
|
||||
if (player == null) {
|
||||
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.PLAYERTAG.INVALID-PLAYER", args[1]);
|
||||
return;
|
||||
}
|
||||
|
||||
TagManager.getInst().removeData(player);
|
||||
if (sender instanceof Player) {
|
||||
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.PLAYERTAG.SUCCESS-DELETE", args[1]);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package me.skymc.taboolib.commands.sub;
|
||||
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
@@ -15,20 +16,16 @@ import me.skymc.taboolib.team.TagManager;
|
||||
*/
|
||||
public class TagPrefixCommand extends SubCommand {
|
||||
|
||||
/**
|
||||
* @param sender
|
||||
* @param args
|
||||
*/
|
||||
public TagPrefixCommand(CommandSender sender, String[] args) {
|
||||
super(sender, args);
|
||||
if (args.length < 3) {
|
||||
MsgUtils.send(sender, "参数错误");
|
||||
TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN");
|
||||
return;
|
||||
}
|
||||
|
||||
Player player = Bukkit.getPlayerExact(args[1]);
|
||||
if (player == null) {
|
||||
MsgUtils.send(sender, "玩家 &f" + args[1] + " &7不在线");
|
||||
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.PLAYERTAG.INVALID-PLAYER", args[1]);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -39,7 +36,7 @@ public class TagPrefixCommand extends SubCommand {
|
||||
|
||||
TagManager.getInst().setPrefix(player, value);
|
||||
if (sender instanceof Player) {
|
||||
MsgUtils.send(sender, "设置玩家 &f" + args[1] + " &7的前缀为 &f" + value);
|
||||
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.PLAYERTAG.SUCCESS-PREFIX-SET", args[1], value);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
package me.skymc.taboolib.commands.sub;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import me.clip.placeholderapi.PlaceholderAPI;
|
||||
import me.skymc.taboolib.commands.SubCommand;
|
||||
import me.skymc.taboolib.message.MsgUtils;
|
||||
import me.skymc.taboolib.team.TagManager;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/**
|
||||
* @author sky
|
||||
@@ -15,32 +15,28 @@ import me.skymc.taboolib.team.TagManager;
|
||||
*/
|
||||
public class TagSuffixCommand extends SubCommand {
|
||||
|
||||
/**
|
||||
* @param sender
|
||||
* @param args
|
||||
*/
|
||||
public TagSuffixCommand(CommandSender sender, String[] args) {
|
||||
super(sender, args);
|
||||
if (args.length < 3) {
|
||||
MsgUtils.send(sender, "参数错误");
|
||||
return;
|
||||
}
|
||||
|
||||
Player player = Bukkit.getPlayerExact(args[1]);
|
||||
if (player == null) {
|
||||
MsgUtils.send(sender, "玩家 &f" + args[1] + " &7不在线");
|
||||
return;
|
||||
}
|
||||
|
||||
String value = getArgs(2).replace("&", "§");
|
||||
if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
|
||||
value = PlaceholderAPI.setPlaceholders(player, value);
|
||||
}
|
||||
|
||||
TagManager.getInst().setSuffix(player, value);
|
||||
if (sender instanceof Player) {
|
||||
MsgUtils.send(sender, "设置玩家 &f" + args[1] + " &7的后缀为 &f" + value);
|
||||
}
|
||||
}
|
||||
public TagSuffixCommand(CommandSender sender, String[] args) {
|
||||
super(sender, args);
|
||||
if (args.length < 3) {
|
||||
TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN");
|
||||
return;
|
||||
}
|
||||
|
||||
Player player = Bukkit.getPlayerExact(args[1]);
|
||||
if (player == null) {
|
||||
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.PLAYERTAG.INVALID-PLAYER", args[1]);
|
||||
return;
|
||||
}
|
||||
|
||||
String value = getArgs(2).replace("&", "§");
|
||||
if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
|
||||
value = PlaceholderAPI.setPlaceholders(player, value);
|
||||
}
|
||||
|
||||
TagManager.getInst().setSuffix(player, value);
|
||||
if (sender instanceof Player) {
|
||||
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.PLAYERTAG.SUCCESS-SUFFIX-SET", args[1], value);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -5,32 +5,34 @@ import me.skymc.taboolib.commands.SubCommand;
|
||||
import me.skymc.taboolib.database.GlobalDataManager;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
/**
|
||||
* @author sky
|
||||
*/
|
||||
public class VariableGetCommand extends SubCommand {
|
||||
|
||||
public VariableGetCommand(CommandSender sender, String[] args) {
|
||||
super(sender, args);
|
||||
|
||||
if (args.length < 3) {
|
||||
public VariableGetCommand(CommandSender sender, String[] args) {
|
||||
super(sender, args);
|
||||
|
||||
if (args.length < 3) {
|
||||
TLocale.sendTo(sender, "COAMMNDS.PARAMETER.INSUFFICIENT");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!(args[1].equals("-a") || args[1].equals("-s"))) {
|
||||
if (!("-a".equals(args[1]) || "-s".equals(args[1]))) {
|
||||
TLocale.sendTo(sender, "COAMMNDS.TABOOLIB.VARIABLE.READ-ERROR-TYPE");
|
||||
return;
|
||||
}
|
||||
|
||||
Long time = System.currentTimeMillis();
|
||||
String value = null;
|
||||
|
||||
if (args[1].equals("-s")) {
|
||||
value = GlobalDataManager.getVariable(args[2], null);
|
||||
}
|
||||
else if (args[1].equals("-a")) {
|
||||
value = GlobalDataManager.getVariableAsynchronous(args[2], null);
|
||||
}
|
||||
}
|
||||
|
||||
Long time = System.currentTimeMillis();
|
||||
String value = null;
|
||||
|
||||
if ("-s".equals(args[1])) {
|
||||
value = GlobalDataManager.getVariable(args[2], null);
|
||||
} else if ("-a".equals(args[1])) {
|
||||
value = GlobalDataManager.getVariableAsynchronous(args[2], null);
|
||||
}
|
||||
|
||||
TLocale.sendTo(sender, "COAMMNDS.TABOOLIB.VARIABLE.READ-SUCCESS", String.valueOf(System.currentTimeMillis() - time));
|
||||
TLocale.sendTo(sender, "COAMMNDS.TABOOLIB.VARIABLE.READ-RESULT", value == null ? "null" : value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,30 +7,29 @@ import org.bukkit.command.CommandSender;
|
||||
|
||||
public class VariableSetCommand extends SubCommand {
|
||||
|
||||
public VariableSetCommand(CommandSender sender, String[] args) {
|
||||
super(sender, args);
|
||||
|
||||
if (args.length < 4) {
|
||||
public VariableSetCommand(CommandSender sender, String[] args) {
|
||||
super(sender, args);
|
||||
|
||||
if (args.length < 4) {
|
||||
TLocale.sendTo(sender, "COAMMNDS.PARAMETER.INSUFFICIENT");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!(args[1].equals("-a") || args[1].equals("-s"))) {
|
||||
if (!("-a".equals(args[1]) || "-s".equals(args[1]))) {
|
||||
TLocale.sendTo(sender, "COAMMNDS.TABOOLIB.VARIABLE.WRITE-ERROR-TYPE");
|
||||
return;
|
||||
}
|
||||
|
||||
Long time = System.currentTimeMillis();
|
||||
String value = getArgs(3);
|
||||
|
||||
if (args[1].equals("-s")) {
|
||||
GlobalDataManager.setVariable(args[2], value);
|
||||
}
|
||||
else if (args[1].equals("-a")) {
|
||||
GlobalDataManager.setVariableAsynchronous(args[2], value);
|
||||
}
|
||||
}
|
||||
|
||||
Long time = System.currentTimeMillis();
|
||||
String value = getArgs(3);
|
||||
|
||||
if ("-s".equals(args[1])) {
|
||||
GlobalDataManager.setVariable(args[2], value);
|
||||
} else if ("-a".equals(args[1])) {
|
||||
GlobalDataManager.setVariableAsynchronous(args[2], value);
|
||||
}
|
||||
|
||||
TLocale.sendTo(sender, "COAMMNDS.TABOOLIB.VARIABLE.WRITE-SUCCESS", String.valueOf(System.currentTimeMillis() - time));
|
||||
setReturn(true);
|
||||
}
|
||||
setReturn(true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,13 +9,13 @@ public class CycleCommand extends SubCommand {
|
||||
public CycleCommand(CommandSender sender, String[] args) {
|
||||
super(sender, args);
|
||||
if (args.length > 1) {
|
||||
if (args[1].equalsIgnoreCase("list")) {
|
||||
if ("list".equalsIgnoreCase(args[1])) {
|
||||
new CycleListCommand(sender, args);
|
||||
} else if (args[1].equalsIgnoreCase("info")) {
|
||||
} else if ("info".equalsIgnoreCase(args[1])) {
|
||||
new CycleInfoCommand(sender, args);
|
||||
} else if (args[1].equalsIgnoreCase("reset")) {
|
||||
} else if ("reset".equalsIgnoreCase(args[1])) {
|
||||
new CycleResetCommand(sender, args);
|
||||
} else if (args[1].equalsIgnoreCase("update")) {
|
||||
} else if ("update".equalsIgnoreCase(args[1])) {
|
||||
new CycleUpdateCommand(sender, args);
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -2,6 +2,7 @@ package me.skymc.taboolib.commands.sub.cycle;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
import me.skymc.taboolib.commands.SubCommand;
|
||||
@@ -15,25 +16,21 @@ public class CycleInfoCommand extends SubCommand {
|
||||
public CycleInfoCommand(CommandSender sender, String[] args) {
|
||||
super(sender, args);
|
||||
if (args.length < 3) {
|
||||
MsgUtils.send(sender, "&c请输入正确的检查器名称");
|
||||
TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN");
|
||||
return;
|
||||
}
|
||||
|
||||
TimeCycle cycle = TimeCycleManager.getTimeCycle(args[2]);
|
||||
if (cycle == null) {
|
||||
MsgUtils.send(sender, "&c检查器 &4" + args[2] + " &c不存在");
|
||||
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.TIMECYCLE.INVALID-CYCLE", args[2]);
|
||||
return;
|
||||
}
|
||||
|
||||
sender.sendMessage("§f");
|
||||
sender.sendMessage("§b§l----- §3§lTimeCycle Info §b§l-----");
|
||||
sender.sendMessage("§f");
|
||||
sender.sendMessage(" §f- §7注册周期: §f" + asString(cycle.getCycle() / 1000L));
|
||||
sender.sendMessage(" §f- §7注册插件: §f" + cycle.getPlugin().getName());
|
||||
sender.sendMessage("§f");
|
||||
sender.sendMessage(" §f- §7上次刷新时间: §f" + DateUtils.CH_ALL.format(TimeCycleManager.getBeforeTimeline(cycle.getName())));
|
||||
sender.sendMessage(" §f- §7下次刷新时间: §f" + DateUtils.CH_ALL.format(TimeCycleManager.getAfterTimeline(cycle.getName())));
|
||||
sender.sendMessage("§f");
|
||||
|
||||
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.TIMECYCLE.CYCLE-INFO",
|
||||
asString(cycle.getCycle() / 1000L),
|
||||
cycle.getPlugin().getName(),
|
||||
DateUtils.CH_ALL.format(TimeCycleManager.getBeforeTimeline(cycle.getName())),
|
||||
DateUtils.CH_ALL.format(TimeCycleManager.getAfterTimeline(cycle.getName())));
|
||||
}
|
||||
|
||||
public String asString(long seconds) {
|
||||
@@ -48,5 +45,4 @@ public class CycleInfoCommand extends SubCommand {
|
||||
public boolean command() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package me.skymc.taboolib.commands.sub.cycle;
|
||||
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
@@ -9,29 +10,20 @@ import me.skymc.taboolib.jsonformatter.click.SuggestCommandEvent;
|
||||
import me.skymc.taboolib.jsonformatter.hover.ShowTextEvent;
|
||||
import me.skymc.taboolib.timecycle.TimeCycle;
|
||||
import me.skymc.taboolib.timecycle.TimeCycleManager;
|
||||
import org.bukkit.inventory.ItemFlag;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class CycleListCommand extends SubCommand {
|
||||
|
||||
public CycleListCommand(CommandSender sender, String[] args) {
|
||||
super(sender, args);
|
||||
|
||||
sender.sendMessage("§f");
|
||||
sender.sendMessage("§b§l----- §3§lTimeCycle List §b§l-----");
|
||||
sender.sendMessage("§f");
|
||||
|
||||
for (TimeCycle cycle : TimeCycleManager.getTimeCycles()) {
|
||||
if (isPlayer()) {
|
||||
JSONFormatter json = new JSONFormatter();
|
||||
json.append(" §7- §f" + cycle.getName());
|
||||
json.appendHoverClick(" §8(点击复制)", new ShowTextEvent("§f点击复制"), new SuggestCommandEvent(cycle.getName()));
|
||||
json.send((Player) sender);
|
||||
}
|
||||
else {
|
||||
sender.sendMessage(" §7- §f" + cycle.getName());
|
||||
}
|
||||
}
|
||||
|
||||
sender.sendMessage("§f");
|
||||
|
||||
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.TIMECYCLE.LIST.HEAD");
|
||||
|
||||
TimeCycleManager.getTimeCycles().forEach(cycle -> TLocale.sendTo(sender, "COMMANDS.TABOOLIB.TIMECYCLE.LIST.BODY", cycle.getName()));
|
||||
|
||||
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.TIMECYCLE.LIST.FOOT");
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package me.skymc.taboolib.commands.sub.cycle;
|
||||
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
@@ -18,13 +19,13 @@ public class CycleResetCommand extends SubCommand {
|
||||
public CycleResetCommand(CommandSender sender, String[] args) {
|
||||
super(sender, args);
|
||||
if (args.length < 3) {
|
||||
MsgUtils.send(sender, "&c请输入正确的检查器名称");
|
||||
TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN");
|
||||
return;
|
||||
}
|
||||
|
||||
TimeCycle cycle = TimeCycleManager.getTimeCycle(args[2]);
|
||||
if (cycle == null) {
|
||||
MsgUtils.send(sender, "&c检查器 &4" + args[2] + " &c不存在");
|
||||
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.TIMECYCLE.INVALID-CYCLE", args[2]);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -38,7 +39,7 @@ public class CycleResetCommand extends SubCommand {
|
||||
// 触发器
|
||||
Bukkit.getPluginManager().callEvent(new TimeCycleEvent(cycle));
|
||||
// 提示
|
||||
MsgUtils.send(sender, "检查器 &f" + args[2] + " &7初始化完成");
|
||||
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.TIMECYCLE.CYCLE-RESET", args[2]);
|
||||
}
|
||||
}.runTaskAsynchronously(Main.getInst());
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package me.skymc.taboolib.commands.sub.cycle;
|
||||
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
@@ -17,13 +18,13 @@ public class CycleUpdateCommand extends SubCommand {
|
||||
public CycleUpdateCommand(CommandSender sender, String[] args) {
|
||||
super(sender, args);
|
||||
if (args.length < 3) {
|
||||
MsgUtils.send(sender, "&c请输入正确的检查器名称");
|
||||
TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN");
|
||||
return;
|
||||
}
|
||||
|
||||
TimeCycle cycle = TimeCycleManager.getTimeCycle(args[2]);
|
||||
if (cycle == null) {
|
||||
MsgUtils.send(sender, "&c检查器 &4" + args[2] + " &c不存在");
|
||||
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.TIMECYCLE.INVALID-CYCLE", args[2]);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -36,7 +37,7 @@ public class CycleUpdateCommand extends SubCommand {
|
||||
// 触发器
|
||||
Bukkit.getPluginManager().callEvent(new TimeCycleEvent(cycle));
|
||||
// 提示
|
||||
MsgUtils.send(sender, "检查器 &f" + args[2] + " &7已更新");
|
||||
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.TIMECYCLE.CYCLE-UPDATE", args[2]);
|
||||
}
|
||||
}.runTaskAsynchronously(Main.getInst());
|
||||
}
|
||||
|
||||
@@ -9,9 +9,9 @@ public class ShellCommand extends SubCommand {
|
||||
public ShellCommand(CommandSender sender, String[] args) {
|
||||
super(sender, args);
|
||||
if (args.length > 1) {
|
||||
if (args[1].equalsIgnoreCase("load")) {
|
||||
if ("load".equalsIgnoreCase(args[1])) {
|
||||
new ShellLoadCommand(sender, args);
|
||||
} else if (args[1].equalsIgnoreCase("unload")) {
|
||||
} else if ("unload".equalsIgnoreCase(args[1])) {
|
||||
new ShellUnloadCommand(sender, args);
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -1,55 +1,47 @@
|
||||
package me.skymc.taboolib.cooldown;
|
||||
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.event.server.PluginDisableEvent;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import me.skymc.taboolib.message.MsgUtils;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Deprecated
|
||||
public class CooldownUtils implements Listener {
|
||||
|
||||
private static ConcurrentHashMap<String, CooldownPack> packlist = new ConcurrentHashMap<>();
|
||||
|
||||
public static void register(CooldownPack pack) {
|
||||
packlist.put(pack.getPackName(), pack);
|
||||
MsgUtils.send("注册冷却包: " + pack.getPackName() + ", 时间: " + pack.getPackSeconds() + " 秒 (匿名注册)");
|
||||
}
|
||||
|
||||
public static void register(CooldownPack pack, Plugin plugin) {
|
||||
pack.setPlugin(plugin.getName());
|
||||
|
||||
packlist.put(pack.getPackName(), pack);
|
||||
MsgUtils.send("注册冷却包: " + pack.getPackName() + ", 时间: " + pack.getPackSeconds() + " 秒 (" + plugin.getName() + ")");
|
||||
}
|
||||
|
||||
public static void unregister(String name) {
|
||||
packlist.remove(name);
|
||||
|
||||
MsgUtils.send("注销冷却包: " + name + " (主动注销)");
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void quit(PlayerQuitEvent e) {
|
||||
for (CooldownPack pack : packlist.values()) {
|
||||
if (!pack.isCooldown(e.getPlayer().getName(), 0)) {
|
||||
pack.unRegister(e.getPlayer().getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void disable(PluginDisableEvent e) {
|
||||
for (CooldownPack pack : packlist.values()) {
|
||||
if (pack.getPlugin().equals(e.getPlugin().getName())) {
|
||||
packlist.remove(pack.getPackName());
|
||||
|
||||
MsgUtils.send("注销冷却包: " + pack.getPackName() + " (自动注销)");
|
||||
}
|
||||
}
|
||||
}
|
||||
private static ConcurrentHashMap<String, CooldownPack> packlist = new ConcurrentHashMap<>();
|
||||
|
||||
public static void register(CooldownPack pack) {
|
||||
packlist.put(pack.getPackName(), pack);
|
||||
TLocale.Logger.info("COOLDOWNPACK.PACK-REGISTER-ANONYMOUS", pack.getPackName(), String.valueOf(pack.getPackSeconds()));
|
||||
}
|
||||
|
||||
public static void register(CooldownPack pack, Plugin plugin) {
|
||||
pack.setPlugin(plugin.getName());
|
||||
packlist.put(pack.getPackName(), pack);
|
||||
TLocale.Logger.info("COOLDOWNPACK.PACK-REGISTER", pack.getPackName(), String.valueOf(pack.getPackSeconds()), plugin.getName());
|
||||
}
|
||||
|
||||
public static void unregister(String name) {
|
||||
packlist.remove(name);
|
||||
TLocale.Logger.info("COOLDOWNPACK.PACK-UNREGISTER", name);
|
||||
}
|
||||
|
||||
private static void unregister(CooldownPack pack) {
|
||||
packlist.remove(pack.getPackName());
|
||||
TLocale.Logger.info("COOLDOWNPACK.PACK-UNREGISTER-AUTO", pack.getPackName());
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void quit(PlayerQuitEvent e) {
|
||||
packlist.values().stream().filter(pack -> !pack.isCooldown(e.getPlayer().getName(), 0)).forEach(pack -> pack.unRegister(e.getPlayer().getName()));
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void disable(PluginDisableEvent e) {
|
||||
packlist.values().stream().filter(pack -> pack.getPlugin().equals(e.getPlugin().getName())).forEach(CooldownUtils::unregister);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package me.skymc.taboolib.cooldown.seconds;
|
||||
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
@@ -18,39 +19,32 @@ public class CooldownUtils2 implements Listener {
|
||||
|
||||
public static void register(CooldownPack2 pack) {
|
||||
packlist.put(pack.getPackName(), pack);
|
||||
// MsgUtils.send("注册冷却包: " + pack.getPackName() + ", 时间: " + pack.getPackSeconds() + " 秒 (匿名注册)");
|
||||
TLocale.Logger.info("COOLDOWNPACK.PACK-REGISTER-ANONYMOUS", pack.getPackName(), String.valueOf(pack.getPackSeconds()));
|
||||
}
|
||||
|
||||
public static void register(CooldownPack2 pack, Plugin plugin) {
|
||||
pack.setPlugin(plugin.getName());
|
||||
|
||||
packlist.put(pack.getPackName(), pack);
|
||||
// MsgUtils.send("注册冷却包: " + pack.getPackName() + ", 时间: " + pack.getPackSeconds() + " 秒 (" + plugin.getName() + ")");
|
||||
TLocale.Logger.info("COOLDOWNPACK.PACK-REGISTER", pack.getPackName(), String.valueOf(pack.getPackSeconds()), plugin.getName());
|
||||
}
|
||||
|
||||
public static void unregister(String name) {
|
||||
packlist.remove(name);
|
||||
|
||||
// MsgUtils.send("注销冷却包: " + name + " (主动注销)");
|
||||
TLocale.Logger.info("COOLDOWNPACK.PACK-UNREGISTER", name);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
|
||||
private static void unregister(CooldownPack2 pack) {
|
||||
packlist.remove(pack.getPackName());
|
||||
TLocale.Logger.info("COOLDOWNPACK.PACK-UNREGISTER-AUTO", pack.getPackName());
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void quit(PlayerQuitEvent e) {
|
||||
for (CooldownPack2 pack : packlist.values()) {
|
||||
if (!pack.isCooldown(e.getPlayer().getName(), 0)) {
|
||||
pack.unRegister(e.getPlayer().getName());
|
||||
}
|
||||
}
|
||||
packlist.values().stream().filter(pack -> !pack.isCooldown(e.getPlayer().getName(), 0)).forEach(pack -> pack.unRegister(e.getPlayer().getName()));
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void disable(PluginDisableEvent e) {
|
||||
for (CooldownPack2 pack : packlist.values()) {
|
||||
if (pack.getPlugin().equals(e.getPlugin().getName())) {
|
||||
packlist.remove(pack.getPackName());
|
||||
|
||||
// MsgUtils.send("注销冷却包: " + pack.getPackName() + " (自动注销)");
|
||||
}
|
||||
}
|
||||
}
|
||||
packlist.values().stream().filter(pack -> pack.getPlugin().equals(e.getPlugin().getName())).forEach(CooldownUtils2::unregister);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
|
||||
@@ -28,7 +29,7 @@ public class GlobalDataManager {
|
||||
public static String getVariable(String name, String defaultVariable) {
|
||||
if (Main.getStorageType() == StorageType.SQL) {
|
||||
Object obj = Main.getConnection().getValueLast(Main.getTablePrefix() + "_plugindata", "name", name, "variable");
|
||||
return obj != null ? obj.toString().equals("null") ? defaultVariable : obj.toString() : defaultVariable;
|
||||
return obj != null ? "null".equals(obj.toString()) ? defaultVariable : obj.toString() : defaultVariable;
|
||||
}
|
||||
else {
|
||||
return data.contains(name) ? data.getString(name) : defaultVariable;
|
||||
@@ -45,7 +46,7 @@ public class GlobalDataManager {
|
||||
public static String getVariableAsynchronous(String name, String defaultVariable) {
|
||||
if (Main.getStorageType() == StorageType.SQL) {
|
||||
SQLVariable variable = SQLMethod.getSQLVariable(name);
|
||||
return variable == null ? defaultVariable : variable.getVariable().equals("null") ? defaultVariable : variable.getVariable();
|
||||
return variable == null ? defaultVariable : "null".equals(variable.getVariable()) ? defaultVariable : variable.getVariable();
|
||||
}
|
||||
else {
|
||||
return getVariable(name, defaultVariable);
|
||||
@@ -137,7 +138,7 @@ public class GlobalDataManager {
|
||||
if (Main.getStorageType() == StorageType.SQL) {
|
||||
LinkedList<HashMap<String, Object>> list = Main.getConnection().getValues(Main.getTablePrefix() + "_plugindata", "id", -1, false, "name", "variable");
|
||||
for (HashMap<String, Object> _map : list) {
|
||||
if (!_map.get("variable").toString().equals("null")) {
|
||||
if (!"null".equals(_map.get("variable").toString())) {
|
||||
map.put(_map.get("name").toString(), _map.get("variable").toString());
|
||||
}
|
||||
}
|
||||
@@ -159,7 +160,7 @@ public class GlobalDataManager {
|
||||
if (Main.getStorageType() == StorageType.SQL) {
|
||||
HashMap<String, String> map = new HashMap<>();
|
||||
for (SQLVariable variable : SQLMethod.getSQLVariables()) {
|
||||
if (!variable.getVariable().equals("null")) {
|
||||
if (!"null".equals(variable.getVariable())) {
|
||||
map.put(variable.getName(), variable.getVariable());
|
||||
}
|
||||
}
|
||||
@@ -286,7 +287,7 @@ public class GlobalDataManager {
|
||||
public void run() {
|
||||
LinkedList<HashMap<String, Object>> list = Main.getConnection().getValues(Main.getTablePrefix() + "_plugindata", "id", -1, false, "name", "variable", "upgrade");
|
||||
for (HashMap<String, Object> _map : list) {
|
||||
if (!_map.get("variable").toString().equals("null")) {
|
||||
if (!"null".equals(_map.get("variable").toString())) {
|
||||
variables.put(_map.get("name").toString(), new SQLVariable(_map.get("name").toString(), _map.get("variable").toString(), _map.get("upgrade").toString()));
|
||||
}
|
||||
}
|
||||
@@ -325,7 +326,7 @@ public class GlobalDataManager {
|
||||
// 如果变量不是由本服更新
|
||||
if (!value.get("upgrade").equals(variables.get(name).getUpgradeUID())) {
|
||||
// 如果变量是空
|
||||
if (value.get("variable").equals("null")) {
|
||||
if ("null".equals(value.get("variable"))) {
|
||||
// 删除变量
|
||||
variables.remove(name);
|
||||
}
|
||||
@@ -336,7 +337,7 @@ public class GlobalDataManager {
|
||||
}
|
||||
}
|
||||
// 如果变量存在则下载到本地
|
||||
else if (!value.get("variable").equals("null")) {
|
||||
else if (!"null".equals(value.get("variable"))) {
|
||||
variables.put(value.get("name").toString(), new SQLVariable(value.get("name").toString(), value.get("variable").toString(), value.get("upgrade").toString()));
|
||||
}
|
||||
}
|
||||
@@ -344,8 +345,7 @@ public class GlobalDataManager {
|
||||
// 移除
|
||||
variables.remove(name);
|
||||
// 提示
|
||||
MsgUtils.warn("变量出现异常: &4" + name);
|
||||
MsgUtils.warn("原因: &4" + e.getMessage());
|
||||
TLocale.Logger.error("GLOBAL-DATAMANAGER.ERROR-CHECK-VARIABLE", String.valueOf(name), e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -410,8 +410,8 @@ public class GlobalDataManager {
|
||||
// 载入数据
|
||||
loadVariables(false);
|
||||
// 提示信息
|
||||
MsgUtils.send("从数据库中获取 &f" + variables.size() + " &7个变量, 耗时: &f" + (System.currentTimeMillis() - time) + " &7(ms)");
|
||||
|
||||
TLocale.Logger.info("GLOBAL-DATAMANAGER.SUCCESS-LOADED-VARIABLE", String.valueOf(variables.size()), String.valueOf(System.currentTimeMillis() - time));
|
||||
|
||||
// 检查更新
|
||||
new BukkitRunnable() {
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package me.skymc.taboolib.database;
|
||||
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import me.skymc.taboolib.Main;
|
||||
import me.skymc.taboolib.Main.StorageType;
|
||||
import me.skymc.taboolib.events.PlayerLoadedEvent;
|
||||
@@ -79,7 +80,7 @@ public class PlayerDataManager implements Listener {
|
||||
return PLAYER_DATA.get(username);
|
||||
} else if (offline) {
|
||||
if (Main.getStorageType() == StorageType.SQL) {
|
||||
throw new PlayerOfflineException("不允许在储存模式为数据库的情况下获取离线玩家数据");
|
||||
throw new PlayerOfflineException(TLocale.asString("PLAYER-DATAMANAGER.ERROR-STORAGE-SQL"));
|
||||
}
|
||||
return loadPlayerData(username);
|
||||
}
|
||||
@@ -111,7 +112,7 @@ public class PlayerDataManager implements Listener {
|
||||
// 创建空数据
|
||||
PLAYER_DATA.put(username, new YamlConfiguration());
|
||||
// 反馈信息
|
||||
MsgUtils.warn("玩家 &4" + username + " &c的数据载入出现异常: &4" + e.getMessage());
|
||||
TLocale.Logger.error("PLAYER-DATAMANAGER.ERROR-PLAYER-DATA", username, e.toString());
|
||||
}
|
||||
} else {
|
||||
// 创建空数据
|
||||
@@ -185,7 +186,7 @@ public class PlayerDataManager implements Listener {
|
||||
}
|
||||
// 提示
|
||||
if (!Main.getInst().getConfig().getBoolean("HIDE-NOTIFY")) {
|
||||
MsgUtils.send("保存 &f" + PLAYER_DATA.size() + " &7条玩家数据, 耗时: &f" + (System.currentTimeMillis() - time) + " &7(ms)");
|
||||
TLocale.Logger.info("PLAYER-DATAMANAGER.SUCCESS-SAVE-DATA", String.valueOf(PLAYER_DATA.size()), String.valueOf(System.currentTimeMillis() - time));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -10,8 +10,9 @@ import org.bukkit.entity.Player;
|
||||
public class ActionUtils {
|
||||
|
||||
public static void send(Player player, String action) {
|
||||
if (player == null)
|
||||
if (player == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
ActionBar.sendActionBar(player, action);
|
||||
} catch (Throwable ignored) {
|
||||
|
||||
@@ -68,7 +68,9 @@ public class EntityTag {
|
||||
* @param value 值
|
||||
*/
|
||||
public void set(String key, Object value, Entity... entities) {
|
||||
for (Entity entity : entities) set(key, value, entity);
|
||||
for (Entity entity : entities) {
|
||||
set(key, value, entity);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -78,7 +80,9 @@ public class EntityTag {
|
||||
* @param value 值
|
||||
*/
|
||||
public void set(String key, Object value, List<Entity> entities) {
|
||||
for (Entity entity : entities) set(key, value, entity);
|
||||
for (Entity entity : entities) {
|
||||
set(key, value, entity);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -104,7 +108,9 @@ public class EntityTag {
|
||||
* @param entities 实体
|
||||
*/
|
||||
public void remove(String key, Entity... entities) {
|
||||
for (Entity entity : entities) remove(key, entity);
|
||||
for (Entity entity : entities) {
|
||||
remove(key, entity);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -114,7 +120,9 @@ public class EntityTag {
|
||||
* @param entities 实体
|
||||
*/
|
||||
public void remove(String key, List<Entity> entities) {
|
||||
for (Entity entity : entities) remove(key, entity);
|
||||
for (Entity entity : entities) {
|
||||
remove(key, entity);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.comphenix.protocol.PacketType;
|
||||
import com.comphenix.protocol.ProtocolLibrary;
|
||||
import com.comphenix.protocol.events.PacketContainer;
|
||||
import com.comphenix.protocol.wrappers.WrappedDataWatcher;
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import me.skymc.taboolib.exception.PluginNotFoundException;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.World;
|
||||
@@ -66,7 +67,7 @@ public class EntityUtils implements Listener {
|
||||
public static void addGlow(Player player, Entity entity) {
|
||||
if (Bukkit.getPluginManager().getPlugin("ProtocolLib") == null) {
|
||||
try {
|
||||
throw new PluginNotFoundException("缺少前置插件 ProtocolLib");
|
||||
throw new PluginNotFoundException(TLocale.asString("ENTITY-UTILS.NOTFOUND-PROTOCOLLIB"));
|
||||
} catch (Exception e) {
|
||||
//
|
||||
}
|
||||
@@ -94,7 +95,7 @@ public class EntityUtils implements Listener {
|
||||
public static void delGlow(Player player, Entity entity) {
|
||||
if (Bukkit.getPluginManager().getPlugin("ProtocolLib") == null) {
|
||||
try {
|
||||
throw new PluginNotFoundException("缺少前置插件 ProtocolLib");
|
||||
throw new PluginNotFoundException(TLocale.asString("ENTITY-UTILS.NOTFOUND-PROTOCOLLIB"));
|
||||
} catch (Exception e) {
|
||||
//
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.google.common.collect.Maps;
|
||||
import com.google.common.io.Files;
|
||||
import com.ilummc.tlib.TLib;
|
||||
import com.ilummc.tlib.bean.Property;
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import com.ilummc.tlib.util.Ref;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.MemoryConfiguration;
|
||||
@@ -60,7 +61,7 @@ public class ConfigUtils {
|
||||
|
||||
public static String mapToYaml(Map<String, Object> map) {
|
||||
String dump = YAML.dump(map);
|
||||
if (dump.equals("{}\n")) {
|
||||
if ("{}\n".equals(dump)) {
|
||||
dump = "";
|
||||
}
|
||||
return dump;
|
||||
@@ -91,13 +92,17 @@ public class ConfigUtils {
|
||||
public static <T> T mapToObj(Map<String, Object> map, T obj) {
|
||||
Class<?> clazz = obj.getClass();
|
||||
map.forEach((string, value) -> Ref.getFieldBySerializedName(clazz, string).ifPresent(field -> {
|
||||
if (!field.isAccessible())
|
||||
if (!field.isAccessible()) {
|
||||
field.setAccessible(true);
|
||||
}
|
||||
try {
|
||||
if (Property.class.isAssignableFrom(field.getType())) {
|
||||
Property<Object> property = (Property) field.get(obj);
|
||||
if (property != null) property.set(value);
|
||||
else field.set(obj, Property.of(value));
|
||||
if (property != null) {
|
||||
property.set(value);
|
||||
} else {
|
||||
field.set(obj, Property.of(value));
|
||||
}
|
||||
} else {
|
||||
field.set(obj, value);
|
||||
}
|
||||
@@ -124,11 +129,16 @@ public class ConfigUtils {
|
||||
}
|
||||
for (Field field : Ref.getDeclaredFields(object.getClass(), excludedModifiers, false)) {
|
||||
try {
|
||||
if (!field.isAccessible()) field.setAccessible(true);
|
||||
if (!field.isAccessible()) {
|
||||
field.setAccessible(true);
|
||||
}
|
||||
Object obj = field.get(object);
|
||||
if (obj instanceof Property) obj = ((Property) obj).get();
|
||||
if (obj instanceof ConfigurationSection)
|
||||
if (obj instanceof Property) {
|
||||
obj = ((Property) obj).get();
|
||||
}
|
||||
if (obj instanceof ConfigurationSection) {
|
||||
obj = objToMap(((ConfigurationSection) obj).getValues(false), excludedModifiers);
|
||||
}
|
||||
map.put(Ref.getSerializedName(field), obj);
|
||||
} catch (IllegalAccessException ignored) {
|
||||
}
|
||||
@@ -190,9 +200,7 @@ public class ConfigUtils {
|
||||
configuration.loadFromString(yaml);
|
||||
return configuration;
|
||||
} catch (Exception e) {
|
||||
TLib.getTLib().getLogger().error("配置文件载入失败!");
|
||||
TLib.getTLib().getLogger().error("插件: &4" + plugin.getName());
|
||||
TLib.getTLib().getLogger().error("文件: &4" + file);
|
||||
TLocale.Logger.error("FILE-UTILS.FALL-LOAD-CONFIGURATION", plugin.getName(), file.getName());
|
||||
}
|
||||
return configuration;
|
||||
}
|
||||
|
||||
@@ -2,51 +2,58 @@ package me.skymc.taboolib.fileutils;
|
||||
|
||||
import ch.njol.util.Closeable;
|
||||
import me.skymc.taboolib.message.MsgUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.util.Objects;
|
||||
|
||||
public class FileUtils {
|
||||
|
||||
public static String ip() {
|
||||
URL url;
|
||||
URLConnection con;
|
||||
try {
|
||||
url = new URL("http://1212.ip138.com/ic.asp");
|
||||
con = url.openConnection();
|
||||
} catch (Exception ignored) {
|
||||
return "[IP ERROR]";
|
||||
}
|
||||
InputStream ins = null;
|
||||
InputStreamReader inputStreamReader = null;
|
||||
BufferedReader bufferedReader = null;
|
||||
try {
|
||||
InputStream ins = null;
|
||||
URL url = new URL("http://1212.ip138.com/ic.asp");
|
||||
URLConnection con = url.openConnection();
|
||||
ins = con.getInputStream();
|
||||
InputStreamReader isReader = new InputStreamReader(ins, "GB2312");
|
||||
BufferedReader bReader = new BufferedReader(isReader);
|
||||
inputStreamReader = new InputStreamReader(ins, "GB2312");
|
||||
bufferedReader = new BufferedReader(inputStreamReader);
|
||||
StringBuilder webContent = new StringBuilder();
|
||||
String str = null;
|
||||
while ((str = bReader.readLine()) != null) {
|
||||
webContent.append(str);
|
||||
}
|
||||
bufferedReader.lines().forEach(webContent::append);
|
||||
int start = webContent.indexOf("[") + 1;
|
||||
int end = webContent.indexOf("]");
|
||||
ins.close();
|
||||
return webContent.substring(start, end);
|
||||
} catch (Exception e) {
|
||||
// TODO: handle exception
|
||||
} catch (Exception ignored) {
|
||||
return "[IP ERROR]";
|
||||
} finally {
|
||||
IOUtils.close(con);
|
||||
IOUtils.closeQuietly(bufferedReader);
|
||||
IOUtils.closeQuietly(inputStreamReader);
|
||||
IOUtils.closeQuietly(ins);
|
||||
}
|
||||
return "[IP ERROR]";
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建并获取文件
|
||||
* 检测文件并创建
|
||||
*
|
||||
* @param filePath
|
||||
* @return
|
||||
* @param file 文件
|
||||
*/
|
||||
public static File file(String filePath) {
|
||||
File file = new File(filePath);
|
||||
if (!file.exists()) {
|
||||
public static File createNewFile(File file) {
|
||||
if (file != null && !file.exists()) {
|
||||
try {
|
||||
file.createNewFile();
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
return file;
|
||||
@@ -55,182 +62,28 @@ public class FileUtils {
|
||||
/**
|
||||
* 创建并获取文件
|
||||
*
|
||||
* @param Path
|
||||
* @param filePath
|
||||
* @param Path 目录
|
||||
* @param filePath 地址
|
||||
* @return
|
||||
*/
|
||||
public static File file(File Path, String filePath) {
|
||||
File file = new File(Path, filePath);
|
||||
if (!file.exists()) {
|
||||
try {
|
||||
file.createNewFile();
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
}
|
||||
}
|
||||
return file;
|
||||
return createNewFile(new File(Path, filePath));
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过输入流读取文本
|
||||
* 创建并获取文件
|
||||
*
|
||||
* @param in
|
||||
* @param size
|
||||
* @param encode
|
||||
* @return
|
||||
* @param filePath 地址
|
||||
* @return {@link File}
|
||||
*/
|
||||
public static String getStringFromInputStream(InputStream in, int size, String encode) {
|
||||
try {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
|
||||
byte[] b = new byte[size];
|
||||
int i = 0;
|
||||
|
||||
while ((i = in.read(b)) > 0) {
|
||||
bos.write(b, 0, i);
|
||||
}
|
||||
|
||||
bos.close();
|
||||
return new String(bos.toByteArray(), encode);
|
||||
} catch (IOException e) {
|
||||
MsgUtils.warn("输入流读取出错: &4" + e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过文件读取文本
|
||||
*
|
||||
* @param file
|
||||
* @param size
|
||||
* @param encode
|
||||
* @return
|
||||
*/
|
||||
public static String getStringFromFile(File file, int size, String encode) {
|
||||
try {
|
||||
FileInputStream fin = new FileInputStream(file);
|
||||
BufferedInputStream bin = new BufferedInputStream(fin);
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
|
||||
byte[] b = new byte[size];
|
||||
int i = 0;
|
||||
|
||||
while ((i = bin.read(b)) > 0) {
|
||||
bos.write(b, 0, i);
|
||||
}
|
||||
|
||||
bos.close();
|
||||
bin.close();
|
||||
fin.close();
|
||||
return new String(bos.toByteArray(), encode);
|
||||
} catch (IOException e) {
|
||||
MsgUtils.warn("文件读取出错: &4" + e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 URL 读取文本
|
||||
*
|
||||
* @param url
|
||||
* @param size
|
||||
* @return
|
||||
*/
|
||||
public static String getStringFromURL(String url, int size) {
|
||||
try {
|
||||
URLConnection conn = new URL(url).openConnection();
|
||||
BufferedInputStream bin = new BufferedInputStream(conn.getInputStream());
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
|
||||
byte[] b = new byte[size];
|
||||
int i = 0;
|
||||
|
||||
while ((i = bin.read(b)) > 0) {
|
||||
bos.write(b, 0, i);
|
||||
}
|
||||
|
||||
bos.close();
|
||||
bin.close();
|
||||
return new String(bos.toByteArray(), conn.getContentEncoding() == null ? "UTF-8" : conn.getContentEncoding());
|
||||
} catch (IOException e) {
|
||||
MsgUtils.warn("网络访问出错: &4" + e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String getStringFromURL(String url, String def) {
|
||||
String s = getStringFromURL(url, 1024);
|
||||
return s == null ? def : s;
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载文件
|
||||
*
|
||||
* @param urlStr
|
||||
* @param filename
|
||||
* @param saveDir
|
||||
*/
|
||||
public static void download(String urlStr, String filename, File saveDir) {
|
||||
try {
|
||||
URL url = new URL(urlStr);
|
||||
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
|
||||
|
||||
// 超时时间
|
||||
conn.setConnectTimeout(5 * 1000);
|
||||
// 防止屏蔽程序抓取而返回 403 错误
|
||||
conn.setRequestProperty("User-Agent", "Mozilla/31.0 (compatible; MSIE 10.0; Windows NT; DigExt)");
|
||||
|
||||
// 得到输入流
|
||||
InputStream inputStream = conn.getInputStream();
|
||||
// 获取数组
|
||||
byte[] data = read(inputStream);
|
||||
|
||||
// 创建文件夹
|
||||
if (!saveDir.exists()) {
|
||||
saveDir.mkdirs();
|
||||
}
|
||||
|
||||
// 保存文件
|
||||
File file = new File(saveDir, filename);
|
||||
FileOutputStream fos = new FileOutputStream(file);
|
||||
|
||||
// 写入文件
|
||||
fos.write(data);
|
||||
|
||||
// 结束
|
||||
fos.close();
|
||||
inputStream.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] read(InputStream in) {
|
||||
byte[] buffer = new byte[1024];
|
||||
int len = 0;
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
try {
|
||||
while ((len = in.read(buffer)) != -1) {
|
||||
bos.write(buffer, 0, len);
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
return bos.toByteArray();
|
||||
}
|
||||
|
||||
public static void close(Closeable closeable) {
|
||||
try {
|
||||
if (closeable != null) {
|
||||
closeable.close();
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
public static File file(String filePath) {
|
||||
return createNewFile(new File(filePath));
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除文件夹
|
||||
*
|
||||
* @param file
|
||||
* @param file 文件夹
|
||||
*/
|
||||
public void deleteAllFile(File file) {
|
||||
if (!file.exists()) {
|
||||
@@ -240,8 +93,7 @@ public class FileUtils {
|
||||
file.delete();
|
||||
return;
|
||||
}
|
||||
File[] files = file.listFiles();
|
||||
for (File file1 : files) {
|
||||
for (File file1 : Objects.requireNonNull(file.listFiles())) {
|
||||
deleteAllFile(file1);
|
||||
}
|
||||
file.delete();
|
||||
@@ -252,20 +104,19 @@ public class FileUtils {
|
||||
*
|
||||
* @param file1 文件1
|
||||
* @param file2 文件2
|
||||
* @throws Exception
|
||||
*/
|
||||
public void copyAllFile(String file1, String file2) throws Exception {
|
||||
public void copyAllFile(String file1, String file2) {
|
||||
File _file1 = new File(file1);
|
||||
File _file2 = new File(file2);
|
||||
if (!_file2.exists()) {
|
||||
if (!_file1.isDirectory()) {
|
||||
_file2.createNewFile();
|
||||
createNewFile(_file2);
|
||||
} else {
|
||||
_file2.mkdirs();
|
||||
}
|
||||
}
|
||||
if (_file1.isDirectory()) {
|
||||
for (File file : _file1.listFiles()) {
|
||||
for (File file : Objects.requireNonNull(_file1.listFiles())) {
|
||||
if (file.isDirectory()) {
|
||||
copyAllFile(file.getAbsolutePath(), file2 + "/" + file.getName());
|
||||
} else {
|
||||
@@ -294,17 +145,159 @@ public class FileUtils {
|
||||
channelIn = fileIn.getChannel();
|
||||
channelOut = fileOut.getChannel();
|
||||
channelIn.transferTo(0, channelIn.size(), channelOut);
|
||||
} catch (Exception e) {
|
||||
//
|
||||
} catch (IOException ignored) {
|
||||
} finally {
|
||||
try {
|
||||
fileIn.close();
|
||||
channelIn.close();
|
||||
fileOut.close();
|
||||
channelOut.close();
|
||||
} catch (Exception e) {
|
||||
//
|
||||
IOUtils.closeQuietly(channelIn);
|
||||
IOUtils.closeQuietly(channelOut);
|
||||
IOUtils.closeQuietly(fileIn);
|
||||
IOUtils.closeQuietly(fileOut);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过输入流读取文本
|
||||
*
|
||||
* @param in 输入流
|
||||
* @param size 大小
|
||||
* @param encode 编码
|
||||
* @return 文本
|
||||
*/
|
||||
public static String getStringFromInputStream(InputStream in, int size, String encode) {
|
||||
try {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
byte[] b = new byte[size];
|
||||
int i;
|
||||
while ((i = in.read(b)) > 0) {
|
||||
bos.write(b, 0, i);
|
||||
}
|
||||
return new String(bos.toByteArray(), encode);
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过文件读取文本
|
||||
*
|
||||
* @param file 文件
|
||||
* @param size 大小
|
||||
* @param encode 编码
|
||||
* @return 文本
|
||||
*/
|
||||
public static String getStringFromFile(File file, int size, String encode) {
|
||||
FileInputStream fin = null;
|
||||
BufferedInputStream bin = null;
|
||||
try {
|
||||
fin = new FileInputStream(file);
|
||||
bin = new BufferedInputStream(fin);
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
byte[] b = new byte[size];
|
||||
int i;
|
||||
while ((i = bin.read(b)) > 0) {
|
||||
bos.write(b, 0, i);
|
||||
}
|
||||
return new String(bos.toByteArray(), encode);
|
||||
} catch (IOException ignored) {
|
||||
} finally {
|
||||
IOUtils.closeQuietly(bin);
|
||||
IOUtils.closeQuietly(fin);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 URL 读取文本
|
||||
*
|
||||
* @param url 地址
|
||||
* @param def 默认值
|
||||
* @return 文本
|
||||
*/
|
||||
public static String getStringFromURL(String url, String def) {
|
||||
String s = getStringFromURL(url, 1024);
|
||||
return s == null ? def : s;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 URL 读取文本
|
||||
*
|
||||
* @param url 地址
|
||||
* @param size 大小
|
||||
* @return 文本
|
||||
*/
|
||||
public static String getStringFromURL(String url, int size) {
|
||||
URLConnection conn = null;
|
||||
BufferedInputStream bin = null;
|
||||
try {
|
||||
conn = new URL(url).openConnection();
|
||||
bin = new BufferedInputStream(conn.getInputStream());
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
byte[] b = new byte[size];
|
||||
int i;
|
||||
while ((i = bin.read(b)) > 0) {
|
||||
bos.write(b, 0, i);
|
||||
}
|
||||
return new String(bos.toByteArray(), conn.getContentEncoding() == null ? "UTF-8" : conn.getContentEncoding());
|
||||
} catch (IOException ignored) {
|
||||
} finally {
|
||||
IOUtils.close(conn);
|
||||
IOUtils.closeQuietly(bin);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载文件
|
||||
*
|
||||
* @param downloadURL 下载地址
|
||||
* @param file 保存位置
|
||||
*/
|
||||
public static void download(String downloadURL, File file) {
|
||||
HttpURLConnection conn = null;
|
||||
InputStream inputStream = null;
|
||||
FileOutputStream fos = null;
|
||||
try {
|
||||
URL url = new URL(downloadURL);
|
||||
conn = (HttpURLConnection) url.openConnection();
|
||||
conn.setConnectTimeout(5 * 1000);
|
||||
conn.setRequestProperty("User-Agent", "Mozilla/31.0 (compatible; MSIE 10.0; Windows NT; DigExt)");
|
||||
|
||||
inputStream = conn.getInputStream();
|
||||
byte[] data = read(inputStream);
|
||||
|
||||
fos = new FileOutputStream(createNewFile(file));
|
||||
fos.write(data);
|
||||
} catch (Exception ignored) {
|
||||
} finally {
|
||||
IOUtils.close(conn);
|
||||
IOUtils.closeQuietly(fos);
|
||||
IOUtils.closeQuietly(inputStream);
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static void download(String downloadURL, String filename, File saveDir) {
|
||||
download(downloadURL, new File(saveDir, filename));
|
||||
}
|
||||
|
||||
public static byte[] read(InputStream in) {
|
||||
byte[] buffer = new byte[1024];
|
||||
int len;
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
try {
|
||||
while ((len = in.read(buffer)) != -1) {
|
||||
bos.write(buffer, 0, len);
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
return bos.toByteArray();
|
||||
}
|
||||
|
||||
public static void close(Closeable closeable) {
|
||||
try {
|
||||
if (closeable != null) {
|
||||
closeable.close();
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,27 +7,24 @@ import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.util.Vector;
|
||||
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class DropUtils {
|
||||
|
||||
public static Item drop(Player player, ItemStack itemStack, double bulletSpread, double radius) {
|
||||
Location location = player.getLocation();
|
||||
location.setY(location.getY() + 1.5);
|
||||
|
||||
Item item = player.getWorld().dropItem(location, itemStack);
|
||||
|
||||
double yaw = Math.toRadians(-player.getLocation().getYaw() - 90.0F);
|
||||
double pitch = Math.toRadians(-player.getLocation().getPitch());
|
||||
|
||||
double x = 0;
|
||||
double y = 0;
|
||||
double z = 0;
|
||||
double x;
|
||||
double y;
|
||||
double z;
|
||||
|
||||
if (bulletSpread > 0) {
|
||||
double[] spread = {1.0D, 1.0D, 1.0D};
|
||||
for (int t = 0; t < 3; t++) {
|
||||
spread[t] = ((NumberUtils.getRand().nextDouble() - NumberUtils.getRand().nextDouble()) * bulletSpread * 0.1D);
|
||||
}
|
||||
|
||||
IntStream.range(0, 3).forEach(t -> spread[t] = ((NumberUtils.getRandom().nextDouble() - NumberUtils.getRandom().nextDouble()) * bulletSpread * 0.1D));
|
||||
x = Math.cos(pitch) * Math.cos(yaw) + spread[0];
|
||||
y = Math.sin(pitch) + spread[1];
|
||||
z = -Math.sin(yaw) * Math.cos(pitch) + spread[2];
|
||||
@@ -36,9 +33,9 @@ public class DropUtils {
|
||||
y = Math.sin(pitch);
|
||||
z = -Math.sin(yaw) * Math.cos(pitch);
|
||||
}
|
||||
|
||||
Vector dirVel = new Vector(x, y, z);
|
||||
dirVel.normalize().multiply(radius);
|
||||
|
||||
item.setVelocity(dirVel);
|
||||
return item;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package me.skymc.taboolib.inventory;
|
||||
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import me.clip.placeholderapi.PlaceholderAPI;
|
||||
import me.skymc.taboolib.Main;
|
||||
import me.skymc.taboolib.TabooLib;
|
||||
@@ -100,7 +101,7 @@ public class ItemUtils {
|
||||
reloadItemCache();
|
||||
itemdir = YamlConfiguration.loadConfiguration(new File(Main.getInst().getConfig().getString("DATAURL.ITEMDIR")));
|
||||
} catch (Exception e) {
|
||||
MsgUtils.warn("物品库载入失败: &4" + e.getMessage());
|
||||
TLocale.Logger.error("ITEM-UTILS.FALL-LOAD-ITEMS", e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,7 +109,7 @@ public class ItemUtils {
|
||||
FileConfiguration conf = ConfigUtils.load(Main.getInst(), file);
|
||||
for (String name : conf.getConfigurationSection("").getKeys(false)) {
|
||||
if (isExists(name)) {
|
||||
MsgUtils.warn("无法载入载入物品 &4" + name + "&c, 因为它已经存在了");
|
||||
TLocale.Logger.error("ITEM-UTILS.FALL-LOAD-ITEMS", name);
|
||||
} else if (finalFile) {
|
||||
itemCachesFinal.put(name, loadItem(conf, name));
|
||||
} else {
|
||||
@@ -127,19 +128,15 @@ public class ItemUtils {
|
||||
finalItemsFolder.mkdir();
|
||||
}
|
||||
// 检查固定物品库中的物品
|
||||
for (File file : Objects.requireNonNull(finalItemsFolder.listFiles())) {
|
||||
loadItemsFile(file, true);
|
||||
}
|
||||
MsgUtils.send("载入 " + (itemCaches.size() + itemCachesFinal.size()) + " 项缓存物品");
|
||||
Arrays.stream(Objects.requireNonNull(finalItemsFolder.listFiles())).forEach(file -> loadItemsFile(file, true));
|
||||
TLocale.Logger.info("ITEM-UTILS.SUCCESS-LOAD-CACHES", String.valueOf(itemCaches.size() + itemCachesFinal.size()));
|
||||
}
|
||||
|
||||
public static void reloadItemName() {
|
||||
FileConfiguration conf = new Language("ITEM_NAME", Main.getInst(), true).getConfiguration();
|
||||
itemlib.clear();
|
||||
for (String a : conf.getConfigurationSection("").getKeys(false)) {
|
||||
itemlib.put(a, conf.getString(a));
|
||||
}
|
||||
MsgUtils.send("载入 " + itemlib.size() + " 项物品名称");
|
||||
conf.getConfigurationSection("").getKeys(false).forEach(a -> itemlib.put(a, conf.getString(a)));
|
||||
TLocale.Logger.info("ITEM-UTILS.SUCCESS-LOAD-NAMES", String.valueOf(itemlib.size()));
|
||||
}
|
||||
|
||||
public static File getItemCacheFile() {
|
||||
@@ -152,7 +149,7 @@ public class ItemUtils {
|
||||
|
||||
public static String getCustomName(ItemStack item) {
|
||||
if (item == null || item.getType().equals(Material.AIR)) {
|
||||
return "空";
|
||||
return TLocale.asString("ITEM-UTILS.EMPTY-ITEM");
|
||||
}
|
||||
int data = item.getType().getMaxDurability() == 0 ? item.getDurability() : 0;
|
||||
return item.getItemMeta().hasDisplayName() ? item.getItemMeta().getDisplayName() : itemlib.get(item.getType() + ":" + data) == null ? item.getType().toString() : itemlib.get(item.getType() + ":" + data);
|
||||
@@ -427,8 +424,7 @@ public class ItemUtils {
|
||||
if (enchant != null) {
|
||||
meta.addEnchant(enchant, section.getInt("enchants." + preEnchant), true);
|
||||
} else {
|
||||
MsgUtils.warn("&8" + preEnchant + " &c不是一个有效的附魔名称");
|
||||
MsgUtils.warn("&c输入 &4/taboolib enchants&c 查看所有附魔");
|
||||
TLocale.Logger.error("ITEM-UTILS.FALL-LOAD-ENCHANTS", preEnchant);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -439,8 +435,7 @@ public class ItemUtils {
|
||||
if (flag != null) {
|
||||
meta.addItemFlags(flag);
|
||||
} else {
|
||||
MsgUtils.warn("&8" + preFlag + " &c不是一个有效的标签名称");
|
||||
MsgUtils.warn("&c输入 &4/taboolib flags&c 查看所有标签");
|
||||
TLocale.Logger.error("ITEM-UTILS.FALL-LOAD-FLAG", preFlag);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -459,8 +454,7 @@ public class ItemUtils {
|
||||
NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[0]),
|
||||
NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[1]) - 1), true);
|
||||
} else {
|
||||
MsgUtils.warn("&8" + prePotionName + " &c不是一个有效的药水名称");
|
||||
MsgUtils.warn("&c输入 &4/taboolib potions&c 查看所有药水");
|
||||
TLocale.Logger.error("ITEM-UTILS.FALL-LOAD-POTION", prePotionName);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -502,18 +496,16 @@ public class ItemUtils {
|
||||
_attr.setInteger("Operation", 0);
|
||||
}
|
||||
_attr.setString("AttributeName", asAttribute(name));
|
||||
_attr.setInteger("UUIDMost", NumberUtils.getRand().nextInt(Integer.MAX_VALUE));
|
||||
_attr.setInteger("UUIDLeast", NumberUtils.getRand().nextInt(Integer.MAX_VALUE));
|
||||
_attr.setInteger("UUIDMost", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE));
|
||||
_attr.setInteger("UUIDLeast", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE));
|
||||
_attr.setString("Name", asAttribute(name));
|
||||
if (!hand.equals("all")) {
|
||||
if (!"all".equals(hand)) {
|
||||
_attr.setString("Slot", hand);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage());
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
} else {
|
||||
MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称");
|
||||
MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性");
|
||||
TLocale.Logger.error("ITEM-UTILS.FALL-LOAD-POTION", name);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -543,18 +535,16 @@ public class ItemUtils {
|
||||
_attr.setInteger("Operation", 0);
|
||||
}
|
||||
_attr.setString("AttributeName", asAttribute(name));
|
||||
_attr.setInteger("UUIDMost", NumberUtils.getRand().nextInt(Integer.MAX_VALUE));
|
||||
_attr.setInteger("UUIDLeast", NumberUtils.getRand().nextInt(Integer.MAX_VALUE));
|
||||
_attr.setInteger("UUIDMost", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE));
|
||||
_attr.setInteger("UUIDLeast", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE));
|
||||
_attr.setString("Name", asAttribute(name));
|
||||
if (!hand.equals("all")) {
|
||||
if (!"all".equals(hand)) {
|
||||
_attr.setString("Slot", hand);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage());
|
||||
} catch (NumberFormatException ignored) {
|
||||
}
|
||||
} else {
|
||||
MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称");
|
||||
MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性");
|
||||
TLocale.Logger.error("ITEM-UTILS.FALL-LOAD-POTION", name);
|
||||
}
|
||||
return nbt;
|
||||
}
|
||||
|
||||
@@ -149,7 +149,9 @@ public class NBTCompound {
|
||||
|
||||
public NBTCompound getCompound(String name) {
|
||||
NBTCompound next = new NBTCompound(this, name);
|
||||
if (NBTReflectionUtil.valideCompound(next)) return next;
|
||||
if (NBTReflectionUtil.valideCompound(next)) {
|
||||
return next;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -158,7 +160,9 @@ public class NBTCompound {
|
||||
}
|
||||
|
||||
public NBTType getType(String name) {
|
||||
if (TabooLib.getVerint() == 10700) return NBTType.NBTTagEnd;
|
||||
if (TabooLib.getVerint() == 10700) {
|
||||
return NBTType.NBTTagEnd;
|
||||
}
|
||||
return NBTType.valueOf(NBTReflectionUtil.getType(this, name));
|
||||
}
|
||||
|
||||
|
||||
@@ -303,8 +303,9 @@ public class NBTReflectionUtil {
|
||||
method = c.getMethod(MethodNames.getEntityNbtGetterMethodName(), getNBTTagCompound());
|
||||
Object nbt = getNBTTagCompound().newInstance();
|
||||
Object answer = method.invoke(nmsitem, nbt);
|
||||
if (answer == null)
|
||||
if (answer == null) {
|
||||
answer = nbt;
|
||||
}
|
||||
return answer;
|
||||
} catch (Exception e) {
|
||||
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
|
||||
@@ -334,8 +335,9 @@ public class NBTReflectionUtil {
|
||||
method = getTileEntity().getMethod(MethodNames.getTileDataMethodName(), getNBTTagCompound());
|
||||
Object tag = getNBTTagCompound().newInstance();
|
||||
Object answer = method.invoke(o, tag);
|
||||
if (answer == null)
|
||||
if (answer == null) {
|
||||
answer = tag;
|
||||
}
|
||||
return answer;
|
||||
} catch (Exception e) {
|
||||
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
|
||||
@@ -381,7 +383,9 @@ public class NBTReflectionUtil {
|
||||
if (nbttag == null) {
|
||||
nbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return;
|
||||
if (!valideCompound(comp)) {
|
||||
return;
|
||||
}
|
||||
Object workingtag = gettoCompount(nbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -421,7 +425,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return;
|
||||
if (!valideCompound(comp)) {
|
||||
return;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -442,7 +448,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return;
|
||||
if (!valideCompound(comp)) {
|
||||
return;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -459,7 +467,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return null;
|
||||
if (!valideCompound(comp)) {
|
||||
return null;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -476,7 +486,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return null;
|
||||
if (!valideCompound(comp)) {
|
||||
return null;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -497,7 +509,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return;
|
||||
if (!valideCompound(comp)) {
|
||||
return;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -514,7 +528,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return null;
|
||||
if (!valideCompound(comp)) {
|
||||
return null;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -535,7 +551,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return;
|
||||
if (!valideCompound(comp)) {
|
||||
return;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -552,7 +570,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return null;
|
||||
if (!valideCompound(comp)) {
|
||||
return null;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -573,7 +593,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return;
|
||||
if (!valideCompound(comp)) {
|
||||
return;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -590,7 +612,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return null;
|
||||
if (!valideCompound(comp)) {
|
||||
return null;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -611,7 +635,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return;
|
||||
if (!valideCompound(comp)) {
|
||||
return;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -628,7 +654,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return null;
|
||||
if (!valideCompound(comp)) {
|
||||
return null;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -649,7 +677,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return;
|
||||
if (!valideCompound(comp)) {
|
||||
return;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -666,7 +696,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return null;
|
||||
if (!valideCompound(comp)) {
|
||||
return null;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -687,7 +719,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return;
|
||||
if (!valideCompound(comp)) {
|
||||
return;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -704,7 +738,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return null;
|
||||
if (!valideCompound(comp)) {
|
||||
return null;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -725,7 +761,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return;
|
||||
if (!valideCompound(comp)) {
|
||||
return;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -742,7 +780,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return null;
|
||||
if (!valideCompound(comp)) {
|
||||
return null;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -763,7 +803,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return;
|
||||
if (!valideCompound(comp)) {
|
||||
return;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -780,7 +822,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return null;
|
||||
if (!valideCompound(comp)) {
|
||||
return null;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -797,7 +841,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return 0;
|
||||
if (!valideCompound(comp)) {
|
||||
return 0;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -818,7 +864,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return;
|
||||
if (!valideCompound(comp)) {
|
||||
return;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -835,7 +883,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return null;
|
||||
if (!valideCompound(comp)) {
|
||||
return null;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -876,7 +926,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return null;
|
||||
if (!valideCompound(comp)) {
|
||||
return null;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -910,7 +962,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return;
|
||||
if (!valideCompound(comp)) {
|
||||
return;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -927,7 +981,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return null;
|
||||
if (!valideCompound(comp)) {
|
||||
return null;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
@@ -945,7 +1001,9 @@ public class NBTReflectionUtil {
|
||||
if (rootnbttag == null) {
|
||||
rootnbttag = getNewNBTTag();
|
||||
}
|
||||
if (!valideCompound(comp)) return null;
|
||||
if (!valideCompound(comp)) {
|
||||
return null;
|
||||
}
|
||||
Object workingtag = gettoCompount(rootnbttag, comp);
|
||||
Method method;
|
||||
try {
|
||||
|
||||
@@ -26,9 +26,11 @@ public enum NBTType {
|
||||
}
|
||||
|
||||
public static NBTType valueOf(int id) {
|
||||
for (NBTType t : values())
|
||||
if (t.getId() == id)
|
||||
for (NBTType t : values()) {
|
||||
if (t.getId() == id) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
return NBTType.NBTTagEnd;
|
||||
}
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ public class Cookie {
|
||||
while (x.more()) {
|
||||
name = unescape(x.nextTo("=;"));
|
||||
if (x.next() != '=') {
|
||||
if (name.equals("secure")) {
|
||||
if ("secure".equals(name)) {
|
||||
value = Boolean.TRUE;
|
||||
} else {
|
||||
throw x.syntaxError("Missing '=' in cookie parameter.");
|
||||
|
||||
@@ -86,11 +86,11 @@ public class JSONArray {
|
||||
Object object = this.get(index);
|
||||
if (object.equals(Boolean.FALSE) ||
|
||||
(object instanceof String &&
|
||||
((String) object).equalsIgnoreCase("false"))) {
|
||||
"false".equalsIgnoreCase((String) object))) {
|
||||
return false;
|
||||
} else if (object.equals(Boolean.TRUE) ||
|
||||
(object instanceof String &&
|
||||
((String) object).equalsIgnoreCase("true"))) {
|
||||
"true".equalsIgnoreCase((String) object))) {
|
||||
return true;
|
||||
}
|
||||
throw new JSONException("JSONArray[" + index + "] is not a boolean.");
|
||||
|
||||
@@ -46,7 +46,7 @@ public class JSONML {
|
||||
break;
|
||||
case '[':
|
||||
token = x.nextToken();
|
||||
if (token.equals("CDATA") && x.next() == '[') {
|
||||
if ("CDATA".equals(token) && x.next() == '[') {
|
||||
if (ja != null) {
|
||||
ja.put(x.nextCDATA());
|
||||
}
|
||||
|
||||
@@ -11,9 +11,42 @@ import java.util.*;
|
||||
@SuppressWarnings({"rawtypes", "unchecked"})
|
||||
public class JSONObject {
|
||||
|
||||
public static final Object NULL = new Null();
|
||||
private static final class Null {
|
||||
|
||||
@Override
|
||||
protected final Object clone() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object object) {
|
||||
return object == null || object == this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "null";
|
||||
}
|
||||
}
|
||||
|
||||
private final Map map;
|
||||
|
||||
public static final Object NULL = new Null();
|
||||
|
||||
public JSONObject() {
|
||||
this.map = new HashMap();
|
||||
}
|
||||
|
||||
public JSONObject(JSONObject jo, String[] names) {
|
||||
this();
|
||||
for (String name : names) {
|
||||
try {
|
||||
this.putOnce(name, jo.opt(name));
|
||||
} catch (Exception ignore) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public JSONObject(JSONTokener x) throws JSONException {
|
||||
this();
|
||||
char c;
|
||||
@@ -58,20 +91,39 @@ public class JSONObject {
|
||||
}
|
||||
}
|
||||
|
||||
public JSONObject() {
|
||||
public JSONObject(Map map) {
|
||||
this.map = new HashMap();
|
||||
if (map != null) {
|
||||
for (Object o : map.entrySet()) {
|
||||
Map.Entry e = (Map.Entry) o;
|
||||
Object value = e.getValue();
|
||||
if (value != null) {
|
||||
this.map.put(e.getKey(), wrap(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public JSONObject(JSONObject jo, String[] names) {
|
||||
public JSONObject(Object bean) {
|
||||
this();
|
||||
this.populateMap(bean);
|
||||
}
|
||||
|
||||
public JSONObject(Object object, String[] names) {
|
||||
this();
|
||||
Class c = object.getClass();
|
||||
for (String name : names) {
|
||||
try {
|
||||
this.putOnce(name, jo.opt(name));
|
||||
this.putOpt(name, c.getField(name).get(object));
|
||||
} catch (Exception ignore) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public JSONObject(String source) throws JSONException {
|
||||
this(new JSONTokener(source));
|
||||
}
|
||||
|
||||
public JSONObject(String baseName, Locale locale) throws JSONException {
|
||||
this();
|
||||
ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale,
|
||||
@@ -97,263 +149,6 @@ public class JSONObject {
|
||||
}
|
||||
}
|
||||
|
||||
public JSONObject(Map map) {
|
||||
this.map = new HashMap();
|
||||
if (map != null) {
|
||||
for (Object o : map.entrySet()) {
|
||||
Map.Entry e = (Map.Entry) o;
|
||||
Object value = e.getValue();
|
||||
if (value != null) {
|
||||
this.map.put(e.getKey(), wrap(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public JSONObject(Object bean) {
|
||||
this();
|
||||
this.populateMap(bean);
|
||||
}
|
||||
|
||||
public JSONObject(Object object, String names[]) {
|
||||
this();
|
||||
Class c = object.getClass();
|
||||
for (String name : names) {
|
||||
try {
|
||||
this.putOpt(name, c.getField(name).get(object));
|
||||
} catch (Exception ignore) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public JSONObject(String source) throws JSONException {
|
||||
this(new JSONTokener(source));
|
||||
}
|
||||
|
||||
public static String[] getNames(JSONObject jo) {
|
||||
int length = jo.length();
|
||||
if (length == 0) {
|
||||
return null;
|
||||
}
|
||||
Iterator iterator = jo.keys();
|
||||
String[] names = new String[length];
|
||||
int i = 0;
|
||||
while (iterator.hasNext()) {
|
||||
names[i] = (String) iterator.next();
|
||||
i += 1;
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
public static String valueToString(Object value) throws JSONException {
|
||||
if (value == null || value == null) {
|
||||
return "null";
|
||||
}
|
||||
if (value instanceof JSONString) {
|
||||
Object object;
|
||||
try {
|
||||
object = ((JSONString) value).toJSONString();
|
||||
} catch (Exception e) {
|
||||
throw new JSONException(e);
|
||||
}
|
||||
if (object != null) {
|
||||
return (String) object;
|
||||
}
|
||||
throw new JSONException("Bad value from toJSONString: " + object);
|
||||
}
|
||||
if (value instanceof Number) {
|
||||
return numberToString((Number) value);
|
||||
}
|
||||
if (value instanceof Boolean || value instanceof JSONObject ||
|
||||
value instanceof JSONArray) {
|
||||
return value.toString();
|
||||
}
|
||||
if (value instanceof Map) {
|
||||
return new JSONObject((Map) value).toString();
|
||||
}
|
||||
if (value instanceof Collection) {
|
||||
return new JSONArray((Collection) value).toString();
|
||||
}
|
||||
if (value.getClass().isArray()) {
|
||||
return new JSONArray(value).toString();
|
||||
}
|
||||
return quote(value.toString());
|
||||
}
|
||||
|
||||
public static Writer quote(String string, Writer w) throws IOException {
|
||||
if (string == null || string.length() == 0) {
|
||||
w.write("\"\"");
|
||||
return w;
|
||||
}
|
||||
|
||||
char b;
|
||||
char c = 0;
|
||||
String hhhh;
|
||||
int i;
|
||||
int len = string.length();
|
||||
|
||||
w.write('"');
|
||||
for (i = 0; i < len; i += 1) {
|
||||
b = c;
|
||||
c = string.charAt(i);
|
||||
switch (c) {
|
||||
case '\\':
|
||||
case '"':
|
||||
w.write('\\');
|
||||
w.write(c);
|
||||
break;
|
||||
case '/':
|
||||
if (b == '<') {
|
||||
w.write('\\');
|
||||
}
|
||||
w.write(c);
|
||||
break;
|
||||
case '\b':
|
||||
w.write("\\b");
|
||||
break;
|
||||
case '\t':
|
||||
w.write("\\t");
|
||||
break;
|
||||
case '\n':
|
||||
w.write("\\n");
|
||||
break;
|
||||
case '\f':
|
||||
w.write("\\f");
|
||||
break;
|
||||
case '\r':
|
||||
w.write("\\r");
|
||||
break;
|
||||
default:
|
||||
if (c < ' ' || (c >= '\u0080' && c < '\u00a0')
|
||||
|| (c >= '\u2000' && c < '\u2100')) {
|
||||
hhhh = "000" + Integer.toHexString(c);
|
||||
w.write("\\u" + hhhh.substring(hhhh.length() - 4));
|
||||
} else {
|
||||
w.write(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
w.write('"');
|
||||
return w;
|
||||
}
|
||||
|
||||
public static String doubleToString(double d) {
|
||||
if (Double.isInfinite(d) || Double.isNaN(d)) {
|
||||
return "null";
|
||||
}
|
||||
String string = Double.toString(d);
|
||||
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
|
||||
string.indexOf('E') < 0) {
|
||||
while (string.endsWith("0")) {
|
||||
string = string.substring(0, string.length() - 1);
|
||||
}
|
||||
if (string.endsWith(".")) {
|
||||
string = string.substring(0, string.length() - 1);
|
||||
}
|
||||
}
|
||||
return string;
|
||||
}
|
||||
|
||||
static void writeValue(Writer writer, Object value, int indentFactor, int indent) throws JSONException, IOException {
|
||||
if (value == null) {
|
||||
writer.write("null");
|
||||
} else if (value instanceof JSONObject) {
|
||||
((JSONObject) value).write(writer, indentFactor, indent);
|
||||
} else if (value instanceof JSONArray) {
|
||||
((JSONArray) value).write(writer, indentFactor, indent);
|
||||
} else if (value instanceof Map) {
|
||||
new JSONObject((Map) value).write(writer, indentFactor, indent);
|
||||
} else if (value instanceof Collection) {
|
||||
new JSONArray((Collection) value).write(writer, indentFactor,
|
||||
indent);
|
||||
} else if (value.getClass().isArray()) {
|
||||
new JSONArray(value).write(writer, indentFactor, indent);
|
||||
} else if (value instanceof Number) {
|
||||
writer.write(numberToString((Number) value));
|
||||
} else if (value instanceof Boolean) {
|
||||
writer.write(value.toString());
|
||||
} else if (value instanceof JSONString) {
|
||||
Object o;
|
||||
try {
|
||||
o = ((JSONString) value).toJSONString();
|
||||
} catch (Exception e) {
|
||||
throw new JSONException(e);
|
||||
}
|
||||
writer.write(o != null ? o.toString() : quote(value.toString()));
|
||||
} else {
|
||||
quote(value.toString(), writer);
|
||||
}
|
||||
}
|
||||
|
||||
public static void testValidity(Object o) throws JSONException {
|
||||
if (o != null) {
|
||||
if (o instanceof Double) {
|
||||
if (((Double) o).isInfinite() || ((Double) o).isNaN()) {
|
||||
throw new JSONException(
|
||||
"JSON does not allow non-finite numbers.");
|
||||
}
|
||||
} else if (o instanceof Float) {
|
||||
if (((Float) o).isInfinite() || ((Float) o).isNaN()) {
|
||||
throw new JSONException(
|
||||
"JSON does not allow non-finite numbers.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static Object wrap(Object object) {
|
||||
try {
|
||||
if (object == null) {
|
||||
return NULL;
|
||||
}
|
||||
if (object instanceof JSONObject || object instanceof JSONArray ||
|
||||
NULL.equals(object) || object instanceof JSONString ||
|
||||
object instanceof Byte || object instanceof Character ||
|
||||
object instanceof Short || object instanceof Integer ||
|
||||
object instanceof Long || object instanceof Boolean ||
|
||||
object instanceof Float || object instanceof Double ||
|
||||
object instanceof String || object instanceof Enum) {
|
||||
return object;
|
||||
}
|
||||
|
||||
if (object instanceof Collection) {
|
||||
return new JSONArray((Collection) object);
|
||||
}
|
||||
if (object.getClass().isArray()) {
|
||||
return new JSONArray(object);
|
||||
}
|
||||
if (object instanceof Map) {
|
||||
return new JSONObject((Map) object);
|
||||
}
|
||||
Package objectPackage = object.getClass().getPackage();
|
||||
String objectPackageName = objectPackage != null
|
||||
? objectPackage.getName()
|
||||
: "";
|
||||
if (
|
||||
objectPackageName.startsWith("java.") ||
|
||||
objectPackageName.startsWith("javax.") ||
|
||||
object.getClass().getClassLoader() == null
|
||||
) {
|
||||
return object.toString();
|
||||
}
|
||||
return new JSONObject(object);
|
||||
} catch (Exception exception) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public Object get(String key) throws JSONException {
|
||||
if (key == null) {
|
||||
throw new JSONException("Null key.");
|
||||
}
|
||||
Object object = this.opt(key);
|
||||
if (object == null) {
|
||||
throw new JSONException("JSONObject[" + quote(key) +
|
||||
"] not found.");
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
public void accumulate(String key, Object value) throws JSONException {
|
||||
testValidity(value);
|
||||
Object object = this.opt(key);
|
||||
@@ -382,15 +177,44 @@ public class JSONObject {
|
||||
return this;
|
||||
}
|
||||
|
||||
public static String doubleToString(double d) {
|
||||
if (Double.isInfinite(d) || Double.isNaN(d)) {
|
||||
return "null";
|
||||
}
|
||||
String string = Double.toString(d);
|
||||
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
|
||||
string.indexOf('E') < 0) {
|
||||
while (string.endsWith("0")) {
|
||||
string = string.substring(0, string.length() - 1);
|
||||
}
|
||||
if (string.endsWith(".")) {
|
||||
string = string.substring(0, string.length() - 1);
|
||||
}
|
||||
}
|
||||
return string;
|
||||
}
|
||||
|
||||
public Object get(String key) throws JSONException {
|
||||
if (key == null) {
|
||||
throw new JSONException("Null key.");
|
||||
}
|
||||
Object object = this.opt(key);
|
||||
if (object == null) {
|
||||
throw new JSONException("JSONObject[" + quote(key) +
|
||||
"] not found.");
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
public boolean getBoolean(String key) throws JSONException {
|
||||
Object object = this.get(key);
|
||||
if (object.equals(Boolean.FALSE) ||
|
||||
(object instanceof String &&
|
||||
((String) object).equalsIgnoreCase("false"))) {
|
||||
"false".equalsIgnoreCase((String) object))) {
|
||||
return false;
|
||||
} else if (object.equals(Boolean.TRUE) ||
|
||||
(object instanceof String &&
|
||||
((String) object).equalsIgnoreCase("true"))) {
|
||||
"true".equalsIgnoreCase((String) object))) {
|
||||
return true;
|
||||
}
|
||||
throw new JSONException("JSONObject[" + quote(key) +
|
||||
@@ -409,6 +233,63 @@ public class JSONObject {
|
||||
}
|
||||
}
|
||||
|
||||
public int getInt(String key) throws JSONException {
|
||||
Object object = this.get(key);
|
||||
try {
|
||||
return object instanceof Number
|
||||
? ((Number) object).intValue()
|
||||
: Integer.parseInt((String) object);
|
||||
} catch (Exception e) {
|
||||
throw new JSONException("JSONObject[" + quote(key) +
|
||||
"] is not an int.");
|
||||
}
|
||||
}
|
||||
|
||||
public JSONArray getJSONArray(String key) throws JSONException {
|
||||
Object object = this.get(key);
|
||||
if (object instanceof JSONArray) {
|
||||
return (JSONArray) object;
|
||||
}
|
||||
throw new JSONException("JSONObject[" + quote(key) +
|
||||
"] is not a JSONArray.");
|
||||
}
|
||||
|
||||
public JSONObject getJSONObject(String key) throws JSONException {
|
||||
Object object = this.get(key);
|
||||
if (object instanceof JSONObject) {
|
||||
return (JSONObject) object;
|
||||
}
|
||||
throw new JSONException("JSONObject[" + quote(key) +
|
||||
"] is not a JSONObject.");
|
||||
}
|
||||
|
||||
public long getLong(String key) throws JSONException {
|
||||
Object object = this.get(key);
|
||||
try {
|
||||
return object instanceof Number
|
||||
? ((Number) object).longValue()
|
||||
: Long.parseLong((String) object);
|
||||
} catch (Exception e) {
|
||||
throw new JSONException("JSONObject[" + quote(key) +
|
||||
"] is not a long.");
|
||||
}
|
||||
}
|
||||
|
||||
public static String[] getNames(JSONObject jo) {
|
||||
int length = jo.length();
|
||||
if (length == 0) {
|
||||
return null;
|
||||
}
|
||||
Iterator iterator = jo.keys();
|
||||
String[] names = new String[length];
|
||||
int i = 0;
|
||||
while (iterator.hasNext()) {
|
||||
names[i] = (String) iterator.next();
|
||||
i += 1;
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
public static String[] getNames(Object object) {
|
||||
if (object == null) {
|
||||
return null;
|
||||
@@ -426,16 +307,13 @@ public class JSONObject {
|
||||
return names;
|
||||
}
|
||||
|
||||
public int getInt(String key) throws JSONException {
|
||||
public String getString(String key) throws JSONException {
|
||||
Object object = this.get(key);
|
||||
try {
|
||||
return object instanceof Number
|
||||
? ((Number) object).intValue()
|
||||
: Integer.parseInt((String) object);
|
||||
} catch (Exception e) {
|
||||
throw new JSONException("JSONObject[" + quote(key) +
|
||||
"] is not an int.");
|
||||
if (object instanceof String) {
|
||||
return (String) object;
|
||||
}
|
||||
throw new JSONException("JSONObject[" + quote(key) +
|
||||
"] not a string.");
|
||||
}
|
||||
|
||||
public boolean has(String key) {
|
||||
@@ -444,16 +322,16 @@ public class JSONObject {
|
||||
|
||||
public static Object stringToValue(String string) {
|
||||
Double d;
|
||||
if (string.equals("")) {
|
||||
if ("".equals(string)) {
|
||||
return string;
|
||||
}
|
||||
if (string.equalsIgnoreCase("true")) {
|
||||
if ("true".equalsIgnoreCase(string)) {
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
if (string.equalsIgnoreCase("false")) {
|
||||
if ("false".equalsIgnoreCase(string)) {
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
if (string.equalsIgnoreCase("null")) {
|
||||
if ("null".equalsIgnoreCase(string)) {
|
||||
return JSONObject.NULL;
|
||||
}
|
||||
char b = string.charAt(0);
|
||||
@@ -491,13 +369,13 @@ public class JSONObject {
|
||||
return this.map.size();
|
||||
}
|
||||
|
||||
public JSONArray getJSONArray(String key) throws JSONException {
|
||||
Object object = this.get(key);
|
||||
if (object instanceof JSONArray) {
|
||||
return (JSONArray) object;
|
||||
public JSONArray names() {
|
||||
JSONArray ja = new JSONArray();
|
||||
Iterator keys = this.keys();
|
||||
while (keys.hasNext()) {
|
||||
ja.put(keys.next());
|
||||
}
|
||||
throw new JSONException("JSONObject[" + quote(key) +
|
||||
"] is not a JSONArray.");
|
||||
return ja.length() == 0 ? null : ja;
|
||||
}
|
||||
|
||||
public static String numberToString(Number number)
|
||||
@@ -559,25 +437,14 @@ public class JSONObject {
|
||||
}
|
||||
}
|
||||
|
||||
public JSONObject getJSONObject(String key) throws JSONException {
|
||||
Object object = this.get(key);
|
||||
if (object instanceof JSONObject) {
|
||||
return (JSONObject) object;
|
||||
}
|
||||
throw new JSONException("JSONObject[" + quote(key) +
|
||||
"] is not a JSONObject.");
|
||||
public JSONArray optJSONArray(String key) {
|
||||
Object o = this.opt(key);
|
||||
return o instanceof JSONArray ? (JSONArray) o : null;
|
||||
}
|
||||
|
||||
public long getLong(String key) throws JSONException {
|
||||
Object object = this.get(key);
|
||||
try {
|
||||
return object instanceof Number
|
||||
? ((Number) object).longValue()
|
||||
: Long.parseLong((String) object);
|
||||
} catch (Exception e) {
|
||||
throw new JSONException("JSONObject[" + quote(key) +
|
||||
"] is not a long.");
|
||||
}
|
||||
public JSONObject optJSONObject(String key) {
|
||||
Object object = this.opt(key);
|
||||
return object instanceof JSONObject ? (JSONObject) object : null;
|
||||
}
|
||||
|
||||
public long optLong(String key) {
|
||||
@@ -601,13 +468,39 @@ public class JSONObject {
|
||||
return NULL.equals(object) ? defaultValue : object.toString();
|
||||
}
|
||||
|
||||
public String getString(String key) throws JSONException {
|
||||
Object object = this.get(key);
|
||||
if (object instanceof String) {
|
||||
return (String) object;
|
||||
public static String valueToString(Object value) throws JSONException {
|
||||
if (value == null || value == null) {
|
||||
return "null";
|
||||
}
|
||||
throw new JSONException("JSONObject[" + quote(key) +
|
||||
"] not a string.");
|
||||
if (value instanceof JSONString) {
|
||||
Object object;
|
||||
try {
|
||||
object = ((JSONString) value).toJSONString();
|
||||
} catch (Exception e) {
|
||||
throw new JSONException(e);
|
||||
}
|
||||
if (object != null) {
|
||||
return (String) object;
|
||||
}
|
||||
throw new JSONException("Bad value from toJSONString: " + object);
|
||||
}
|
||||
if (value instanceof Number) {
|
||||
return numberToString((Number) value);
|
||||
}
|
||||
if (value instanceof Boolean || value instanceof JSONObject ||
|
||||
value instanceof JSONArray) {
|
||||
return value.toString();
|
||||
}
|
||||
if (value instanceof Map) {
|
||||
return new JSONObject((Map) value).toString();
|
||||
}
|
||||
if (value instanceof Collection) {
|
||||
return new JSONArray((Collection) value).toString();
|
||||
}
|
||||
if (value.getClass().isArray()) {
|
||||
return new JSONArray(value).toString();
|
||||
}
|
||||
return quote(value.toString());
|
||||
}
|
||||
|
||||
public JSONObject put(String key, boolean value) throws JSONException {
|
||||
@@ -681,27 +574,112 @@ public class JSONObject {
|
||||
}
|
||||
}
|
||||
|
||||
public JSONArray names() {
|
||||
JSONArray ja = new JSONArray();
|
||||
Iterator keys = this.keys();
|
||||
while (keys.hasNext()) {
|
||||
ja.put(keys.next());
|
||||
public static Writer quote(String string, Writer w) throws IOException {
|
||||
if (string == null || string.length() == 0) {
|
||||
w.write("\"\"");
|
||||
return w;
|
||||
}
|
||||
return ja.length() == 0 ? null : ja;
|
||||
|
||||
char b;
|
||||
char c = 0;
|
||||
String hhhh;
|
||||
int i;
|
||||
int len = string.length();
|
||||
|
||||
w.write('"');
|
||||
for (i = 0; i < len; i += 1) {
|
||||
b = c;
|
||||
c = string.charAt(i);
|
||||
switch (c) {
|
||||
case '\\':
|
||||
case '"':
|
||||
w.write('\\');
|
||||
w.write(c);
|
||||
break;
|
||||
case '/':
|
||||
if (b == '<') {
|
||||
w.write('\\');
|
||||
}
|
||||
w.write(c);
|
||||
break;
|
||||
case '\b':
|
||||
w.write("\\b");
|
||||
break;
|
||||
case '\t':
|
||||
w.write("\\t");
|
||||
break;
|
||||
case '\n':
|
||||
w.write("\\n");
|
||||
break;
|
||||
case '\f':
|
||||
w.write("\\f");
|
||||
break;
|
||||
case '\r':
|
||||
w.write("\\r");
|
||||
break;
|
||||
default:
|
||||
if (c < ' ' || (c >= '\u0080' && c < '\u00a0')
|
||||
|| (c >= '\u2000' && c < '\u2100')) {
|
||||
hhhh = "000" + Integer.toHexString(c);
|
||||
w.write("\\u" + hhhh.substring(hhhh.length() - 4));
|
||||
} else {
|
||||
w.write(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
w.write('"');
|
||||
return w;
|
||||
}
|
||||
|
||||
public Object remove(String key) {
|
||||
return this.map.remove(key);
|
||||
}
|
||||
|
||||
public JSONArray optJSONArray(String key) {
|
||||
Object o = this.opt(key);
|
||||
return o instanceof JSONArray ? (JSONArray) o : null;
|
||||
static void writeValue(Writer writer, Object value, int indentFactor, int indent) throws JSONException, IOException {
|
||||
if (value == null) {
|
||||
writer.write("null");
|
||||
} else if (value instanceof JSONObject) {
|
||||
((JSONObject) value).write(writer, indentFactor, indent);
|
||||
} else if (value instanceof JSONArray) {
|
||||
((JSONArray) value).write(writer, indentFactor, indent);
|
||||
} else if (value instanceof Map) {
|
||||
new JSONObject((Map) value).write(writer, indentFactor, indent);
|
||||
} else if (value instanceof Collection) {
|
||||
new JSONArray((Collection) value).write(writer, indentFactor,
|
||||
indent);
|
||||
} else if (value.getClass().isArray()) {
|
||||
new JSONArray(value).write(writer, indentFactor, indent);
|
||||
} else if (value instanceof Number) {
|
||||
writer.write(numberToString((Number) value));
|
||||
} else if (value instanceof Boolean) {
|
||||
writer.write(value.toString());
|
||||
} else if (value instanceof JSONString) {
|
||||
Object o;
|
||||
try {
|
||||
o = ((JSONString) value).toJSONString();
|
||||
} catch (Exception e) {
|
||||
throw new JSONException(e);
|
||||
}
|
||||
writer.write(o != null ? o.toString() : quote(value.toString()));
|
||||
} else {
|
||||
quote(value.toString(), writer);
|
||||
}
|
||||
}
|
||||
|
||||
public JSONObject optJSONObject(String key) {
|
||||
Object object = this.opt(key);
|
||||
return object instanceof JSONObject ? (JSONObject) object : null;
|
||||
public static void testValidity(Object o) throws JSONException {
|
||||
if (o != null) {
|
||||
if (o instanceof Double) {
|
||||
if (((Double) o).isInfinite() || ((Double) o).isNaN()) {
|
||||
throw new JSONException(
|
||||
"JSON does not allow non-finite numbers.");
|
||||
}
|
||||
} else if (o instanceof Float) {
|
||||
if (((Float) o).isInfinite() || ((Float) o).isNaN()) {
|
||||
throw new JSONException(
|
||||
"JSON does not allow non-finite numbers.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public JSONArray toJSONArray(JSONArray names) throws JSONException {
|
||||
@@ -737,56 +715,49 @@ public class JSONObject {
|
||||
}
|
||||
}
|
||||
|
||||
public Writer write(Writer writer) throws JSONException {
|
||||
return this.write(writer, 0, 0);
|
||||
public static Object wrap(Object object) {
|
||||
try {
|
||||
if (object == null) {
|
||||
return NULL;
|
||||
}
|
||||
if (object instanceof JSONObject || object instanceof JSONArray ||
|
||||
NULL.equals(object) || object instanceof JSONString ||
|
||||
object instanceof Byte || object instanceof Character ||
|
||||
object instanceof Short || object instanceof Integer ||
|
||||
object instanceof Long || object instanceof Boolean ||
|
||||
object instanceof Float || object instanceof Double ||
|
||||
object instanceof String || object instanceof Enum) {
|
||||
return object;
|
||||
}
|
||||
|
||||
if (object instanceof Collection) {
|
||||
return new JSONArray((Collection) object);
|
||||
}
|
||||
if (object.getClass().isArray()) {
|
||||
return new JSONArray(object);
|
||||
}
|
||||
if (object instanceof Map) {
|
||||
return new JSONObject((Map) object);
|
||||
}
|
||||
Package objectPackage = object.getClass().getPackage();
|
||||
String objectPackageName = objectPackage != null
|
||||
? objectPackage.getName()
|
||||
: "";
|
||||
if (
|
||||
objectPackageName.startsWith("java.") ||
|
||||
objectPackageName.startsWith("javax.") ||
|
||||
object.getClass().getClassLoader() == null
|
||||
) {
|
||||
return object.toString();
|
||||
}
|
||||
return new JSONObject(object);
|
||||
} catch (Exception exception) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Writer write(Writer writer, int indentFactor, int indent)
|
||||
throws JSONException {
|
||||
try {
|
||||
boolean commanate = false;
|
||||
final int length = this.length();
|
||||
Iterator keys = this.keys();
|
||||
writer.write('{');
|
||||
|
||||
if (length == 1) {
|
||||
Object key = keys.next();
|
||||
writer.write(quote(key.toString()));
|
||||
writer.write(':');
|
||||
if (indentFactor > 0) {
|
||||
writer.write(' ');
|
||||
}
|
||||
writeValue(writer, this.map.get(key), indentFactor, indent);
|
||||
} else if (length != 0) {
|
||||
final int newindent = indent + indentFactor;
|
||||
while (keys.hasNext()) {
|
||||
Object key = keys.next();
|
||||
if (commanate) {
|
||||
writer.write(',');
|
||||
}
|
||||
if (indentFactor > 0) {
|
||||
writer.write('\n');
|
||||
}
|
||||
indent(writer, newindent);
|
||||
writer.write(quote(key.toString()));
|
||||
writer.write(':');
|
||||
if (indentFactor > 0) {
|
||||
writer.write(' ');
|
||||
}
|
||||
writeValue(writer, this.map.get(key), indentFactor,
|
||||
newindent);
|
||||
commanate = true;
|
||||
}
|
||||
if (indentFactor > 0) {
|
||||
writer.write('\n');
|
||||
}
|
||||
indent(writer, indent);
|
||||
}
|
||||
writer.write('}');
|
||||
return writer;
|
||||
} catch (IOException exception) {
|
||||
throw new JSONException(exception);
|
||||
}
|
||||
public Writer write(Writer writer) throws JSONException {
|
||||
return this.write(writer, 0, 0);
|
||||
}
|
||||
|
||||
public JSONObject increment(String key) throws JSONException {
|
||||
@@ -851,21 +822,51 @@ public class JSONObject {
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Null {
|
||||
Writer write(Writer writer, int indentFactor, int indent)
|
||||
throws JSONException {
|
||||
try {
|
||||
boolean commanate = false;
|
||||
final int length = this.length();
|
||||
Iterator keys = this.keys();
|
||||
writer.write('{');
|
||||
|
||||
@Override
|
||||
protected final Object clone() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object object) {
|
||||
return object == null || object == this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "null";
|
||||
if (length == 1) {
|
||||
Object key = keys.next();
|
||||
writer.write(quote(key.toString()));
|
||||
writer.write(':');
|
||||
if (indentFactor > 0) {
|
||||
writer.write(' ');
|
||||
}
|
||||
writeValue(writer, this.map.get(key), indentFactor, indent);
|
||||
} else if (length != 0) {
|
||||
final int newindent = indent + indentFactor;
|
||||
while (keys.hasNext()) {
|
||||
Object key = keys.next();
|
||||
if (commanate) {
|
||||
writer.write(',');
|
||||
}
|
||||
if (indentFactor > 0) {
|
||||
writer.write('\n');
|
||||
}
|
||||
indent(writer, newindent);
|
||||
writer.write(quote(key.toString()));
|
||||
writer.write(':');
|
||||
if (indentFactor > 0) {
|
||||
writer.write(' ');
|
||||
}
|
||||
writeValue(writer, this.map.get(key), indentFactor,
|
||||
newindent);
|
||||
commanate = true;
|
||||
}
|
||||
if (indentFactor > 0) {
|
||||
writer.write('\n');
|
||||
}
|
||||
indent(writer, indent);
|
||||
}
|
||||
writer.write('}');
|
||||
return writer;
|
||||
} catch (IOException exception) {
|
||||
throw new JSONException(exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ public class JSONWriter {
|
||||
|
||||
protected char mode;
|
||||
|
||||
private final JSONObject stack[];
|
||||
private final JSONObject[] stack;
|
||||
|
||||
private int top;
|
||||
|
||||
|
||||
@@ -17,29 +17,6 @@ import java.util.List;
|
||||
|
||||
public class JSONFormatter {
|
||||
|
||||
private static Class<?> cs = NMSUtils.getNMSClassSilent("ChatSerializer", "IChatBaseComponent");
|
||||
private static Class<?> icbc = NMSUtils.getNMSClassSilent("IChatBaseComponent");
|
||||
private static Class<?> ppoc = NMSUtils.getNMSClassSilent("PacketPlayOutChat");
|
||||
private static Class<?> pc = NMSUtils.getNMSClassSilent("PlayerConnection");
|
||||
private static Class<?> p = NMSUtils.getNMSClassSilent("Packet");
|
||||
private static Class<?> ep = NMSUtils.getNMSClassSilent("EntityPlayer");
|
||||
private static Method a = NMSUtils.getMethodSilent(cs, "a", String.class), sp = NMSUtils.getMethodSilent(pc, "sendPacket", p);
|
||||
private static Field ppc = NMSUtils.getFieldSilent(ep, "playerConnection");
|
||||
private static Constructor<?> ppocc = NMSUtils.getConstructorSilent(ppoc, icbc);
|
||||
private static boolean b = check(cs, icbc, ppoc, pc, p, ep, a, sp, ppc, ppocc);
|
||||
private List<JSONArray> all = new ArrayList<>();
|
||||
private JSONArray ja = new JSONArray();
|
||||
private Builder builder = new Builder();
|
||||
private String color = "";
|
||||
private boolean newline = true;
|
||||
|
||||
public JSONFormatter() {
|
||||
}
|
||||
|
||||
public JSONFormatter(boolean newline) {
|
||||
this.newline = newline;
|
||||
}
|
||||
|
||||
public static void sendRawMessage(Player player, String message) {
|
||||
try {
|
||||
Object entityplayer = NMSUtils.getHandle(player);
|
||||
@@ -51,60 +28,23 @@ public class JSONFormatter {
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean check(Object... o) {
|
||||
for (Object a : o) {
|
||||
if (a == null)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
private JSONArray ja = new JSONArray();
|
||||
private Builder builder = new Builder();
|
||||
private String color = "";
|
||||
private List<JSONArray> all = new ArrayList<>();
|
||||
private boolean newline = true;
|
||||
|
||||
public JSONFormatter() {
|
||||
}
|
||||
|
||||
private static void send(Player player, JSONFormatter jf) {
|
||||
if (!jf.newline) {
|
||||
send1(player, jf);
|
||||
} else if (b) {
|
||||
try {
|
||||
Object entityplayer = NMSUtils.getHandle(player);
|
||||
Object ppco = ppc.get(entityplayer);
|
||||
sp.invoke(ppco, jf.getPacket());
|
||||
} catch (Exception e) {
|
||||
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jf.toJSON());
|
||||
}
|
||||
} else {
|
||||
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jf.toJSON());
|
||||
}
|
||||
}
|
||||
|
||||
private static void send1(Player player, JSONFormatter jf) {
|
||||
if (b) {
|
||||
try {
|
||||
Object entityplayer = NMSUtils.getHandle(player);
|
||||
Object ppco = ppc.get(entityplayer);
|
||||
List<Object> packets = jf.getPacketList();
|
||||
List<String> jsons = null;
|
||||
for (int i = 0; i < packets.size(); i++) {
|
||||
try {
|
||||
sp.invoke(ppco, packets.get(i));
|
||||
} catch (Exception e) {
|
||||
if (jsons == null) {
|
||||
jsons = jf.toJSONList();
|
||||
}
|
||||
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jsons.get(i));
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
} else {
|
||||
for (String json : jf.toJSONList()) {
|
||||
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + json);
|
||||
}
|
||||
}
|
||||
public JSONFormatter(boolean newline) {
|
||||
this.newline = newline;
|
||||
}
|
||||
|
||||
public JSONFormatter append(JSONFormatter json) {
|
||||
if (json.ja.length() == 0)
|
||||
if (json.ja.length() == 0) {
|
||||
return this;
|
||||
}
|
||||
try {
|
||||
if (newline && json.newline) {
|
||||
all.addAll(json.all);
|
||||
@@ -137,8 +77,9 @@ public class JSONFormatter {
|
||||
}
|
||||
|
||||
public JSONFormatter newLine(int amount) {
|
||||
for (int i = 0; i < amount; i++)
|
||||
for (int i = 0; i < amount; i++) {
|
||||
newLine();
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -165,8 +106,9 @@ public class JSONFormatter {
|
||||
public String toJSON() {
|
||||
JSONObject jo = new JSONObject();
|
||||
try {
|
||||
if (ja.length() > 0)
|
||||
if (ja.length() > 0) {
|
||||
jo.put("extra", ja);
|
||||
}
|
||||
jo.put("text", "");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
@@ -179,14 +121,16 @@ public class JSONFormatter {
|
||||
try {
|
||||
for (JSONArray ja : all) {
|
||||
JSONObject jo = new JSONObject();
|
||||
if (ja.length() > 0)
|
||||
if (ja.length() > 0) {
|
||||
jo.put("extra", ja);
|
||||
}
|
||||
jo.put("text", "");
|
||||
list.add(jo.toString());
|
||||
}
|
||||
JSONObject jo = new JSONObject();
|
||||
if (ja.length() > 0)
|
||||
if (ja.length() > 0) {
|
||||
jo.put("extra", ja);
|
||||
}
|
||||
jo.put("text", "");
|
||||
list.add(jo.toString());
|
||||
return list;
|
||||
@@ -224,10 +168,12 @@ public class JSONFormatter {
|
||||
}
|
||||
|
||||
private void add(Object jo) {
|
||||
if (ja == null)
|
||||
if (ja == null) {
|
||||
ja = new JSONArray();
|
||||
if (jo != null)
|
||||
}
|
||||
if (jo != null) {
|
||||
ja.put(jo);
|
||||
}
|
||||
}
|
||||
|
||||
private JSONFormatter append(String text, BuilderMaker bm) {
|
||||
@@ -345,9 +291,72 @@ public class JSONFormatter {
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Class<?> cs = NMSUtils.getNMSClassSilent("ChatSerializer", "IChatBaseComponent");
|
||||
private static Class<?> icbc = NMSUtils.getNMSClassSilent("IChatBaseComponent");
|
||||
private static Class<?> ppoc = NMSUtils.getNMSClassSilent("PacketPlayOutChat");
|
||||
private static Class<?> pc = NMSUtils.getNMSClassSilent("PlayerConnection");
|
||||
private static Class<?> p = NMSUtils.getNMSClassSilent("Packet");
|
||||
private static Class<?> ep = NMSUtils.getNMSClassSilent("EntityPlayer");
|
||||
private static Method a = NMSUtils.getMethodSilent(cs, "a", String.class), sp = NMSUtils.getMethodSilent(pc, "sendPacket", p);
|
||||
private static Field ppc = NMSUtils.getFieldSilent(ep, "playerConnection");
|
||||
private static Constructor<?> ppocc = NMSUtils.getConstructorSilent(ppoc, icbc);
|
||||
private static boolean b = check(cs, icbc, ppoc, pc, p, ep, a, sp, ppc, ppocc);
|
||||
|
||||
private static boolean check(Object... o) {
|
||||
for (Object a : o) {
|
||||
if (a == null) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void send(Player player, JSONFormatter jf) {
|
||||
if (!jf.newline) {
|
||||
send1(player, jf);
|
||||
} else if (b) {
|
||||
try {
|
||||
Object entityplayer = NMSUtils.getHandle(player);
|
||||
Object ppco = ppc.get(entityplayer);
|
||||
sp.invoke(ppco, jf.getPacket());
|
||||
} catch (Exception e) {
|
||||
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jf.toJSON());
|
||||
}
|
||||
} else {
|
||||
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jf.toJSON());
|
||||
}
|
||||
}
|
||||
|
||||
private static void send1(Player player, JSONFormatter jf) {
|
||||
if (b) {
|
||||
try {
|
||||
Object entityplayer = NMSUtils.getHandle(player);
|
||||
Object ppco = ppc.get(entityplayer);
|
||||
List<Object> packets = jf.getPacketList();
|
||||
List<String> jsons = null;
|
||||
for (int i = 0; i < packets.size(); i++) {
|
||||
try {
|
||||
sp.invoke(ppco, packets.get(i));
|
||||
} catch (Exception e) {
|
||||
if (jsons == null) {
|
||||
jsons = jf.toJSONList();
|
||||
}
|
||||
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jsons.get(i));
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
} else {
|
||||
for (String json : jf.toJSONList()) {
|
||||
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + json);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class Builder {
|
||||
|
||||
private StringBuilder sb = new StringBuilder();
|
||||
private StringBuilder sb = new StringBuilder("");
|
||||
private boolean bold = false, italic = false, magic = false, strikethrough = false, underline = false, changed = false;
|
||||
|
||||
public Builder() {
|
||||
@@ -368,24 +377,32 @@ public class JSONFormatter {
|
||||
|
||||
private JSONObject toString(String color, BuilderHelper bh) {
|
||||
String string = sb.toString();
|
||||
if (!changed)
|
||||
if (!changed) {
|
||||
return null;
|
||||
if (string.length() == 0)
|
||||
}
|
||||
if (string.length() == 0) {
|
||||
return null;
|
||||
}
|
||||
JSONObject jo = new JSONObject();
|
||||
try {
|
||||
if (!color.equals(""))
|
||||
if (!"".equals(color)) {
|
||||
jo.put("color", color);
|
||||
if (bold)
|
||||
}
|
||||
if (bold) {
|
||||
jo.put("bold", true);
|
||||
if (italic)
|
||||
}
|
||||
if (italic) {
|
||||
jo.put("italic", true);
|
||||
if (magic)
|
||||
}
|
||||
if (magic) {
|
||||
jo.put("obfuscated", true);
|
||||
if (strikethrough)
|
||||
}
|
||||
if (strikethrough) {
|
||||
jo.put("strikethrough", true);
|
||||
if (underline)
|
||||
}
|
||||
if (underline) {
|
||||
jo.put("underlined", true);
|
||||
}
|
||||
bh.add(jo);
|
||||
jo.put("text", string);
|
||||
} catch (Exception e) {
|
||||
@@ -406,8 +423,9 @@ public class JSONFormatter {
|
||||
return toString(color, new BuilderHelper() {
|
||||
@Override
|
||||
public void add(JSONObject jo) throws Exception {
|
||||
if (event.getEvent().length() > 1)
|
||||
if (event.getEvent().length() > 1) {
|
||||
jo.put("hoverEvent", event.getEvent());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -416,8 +434,9 @@ public class JSONFormatter {
|
||||
return toString(color, new BuilderHelper() {
|
||||
@Override
|
||||
public void add(JSONObject jo) throws Exception {
|
||||
if (event.getEvent().length() > 1)
|
||||
if (event.getEvent().length() > 1) {
|
||||
jo.put("clickEvent", event.getEvent());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -426,10 +445,12 @@ public class JSONFormatter {
|
||||
return toString(color, new BuilderHelper() {
|
||||
@Override
|
||||
public void add(JSONObject jo) throws Exception {
|
||||
if (hevent.getEvent().length() > 1)
|
||||
if (hevent.getEvent().length() > 1) {
|
||||
jo.put("hoverEvent", hevent.getEvent());
|
||||
if (cevent.getEvent().length() > 1)
|
||||
}
|
||||
if (cevent.getEvent().length() > 1) {
|
||||
jo.put("clickEvent", cevent.getEvent());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ public class ListenerPlayerCommand implements Listener {
|
||||
|
||||
@EventHandler
|
||||
public void cmd(ServerCommandEvent e) {
|
||||
if (e.getCommand().equals("savefile")) {
|
||||
if ("savefile".equals(e.getCommand())) {
|
||||
if (TabooLib.getVerint() > 10700) {
|
||||
e.setCancelled(true);
|
||||
}
|
||||
@@ -30,7 +30,7 @@ public class ListenerPlayerCommand implements Listener {
|
||||
@SuppressWarnings("deprecation")
|
||||
@EventHandler
|
||||
public void cmd(PlayerCommandPreprocessEvent e) {
|
||||
if (e.getMessage().equals("/unbreakable") && PermissionUtils.hasPermission(e.getPlayer(), "taboolib.unbreakable")) {
|
||||
if ("/unbreakable".equals(e.getMessage()) && PermissionUtils.hasPermission(e.getPlayer(), "taboolib.unbreakable")) {
|
||||
e.setCancelled(true);
|
||||
|
||||
NBTItem nbti = new NBTItem(e.getPlayer().getItemInHand());
|
||||
|
||||
@@ -47,7 +47,9 @@ public class LocationUtils {
|
||||
|
||||
@Deprecated
|
||||
public static Block findBlockByLocation(Location l) {
|
||||
while (l.getY() < 255 && l.getBlock().getType() != Material.AIR) l.add(0, 1, 0);
|
||||
while (l.getY() < 255 && l.getBlock().getType() != Material.AIR) {
|
||||
l.add(0, 1, 0);
|
||||
}
|
||||
return l.getY() < 255 && l.getBlock().getType() == Material.AIR ? l.getBlock() : null;
|
||||
}
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ public class ChatCatcher implements Listener {
|
||||
if (playerdata.containsKey(e.getPlayer().getName()) && playerdata.get(e.getPlayer().getName()).size() > 0) {
|
||||
e.setCancelled(true);
|
||||
|
||||
if (e.getMessage().equalsIgnoreCase("quit()")) {
|
||||
if ("quit()".equalsIgnoreCase(e.getMessage())) {
|
||||
// 退出引导
|
||||
playerdata.get(e.getPlayer().getName()).removeFirst().cancel();
|
||||
// 清理数据
|
||||
|
||||
@@ -54,7 +54,7 @@ public class MsgUtils {
|
||||
@Deprecated
|
||||
public static String noPe() {
|
||||
String s = Main.getInst().getConfig().getString("NO-PERMISSION-MESSAGE").replaceAll("&", "§");
|
||||
if (s.equals("")) {
|
||||
if ("".equals(s)) {
|
||||
s = "§cCONFIG ERROR §8(NO-PERMISSION-MESSAGE)";
|
||||
}
|
||||
return s;
|
||||
@@ -63,7 +63,7 @@ public class MsgUtils {
|
||||
@Deprecated
|
||||
public static String noClaim(String a) {
|
||||
String s = Main.getInst().getConfig().getString("NO-CLAIM-MESSAGE").replaceAll("&", "§").replaceAll("%s%", a);
|
||||
if (s.equals("")) {
|
||||
if ("".equals(s)) {
|
||||
s = "§cCONFIG ERROR §8(NO-CLAIM-MESSAGE)";
|
||||
}
|
||||
return s;
|
||||
|
||||
@@ -6,49 +6,44 @@ import java.lang.reflect.Method;
|
||||
|
||||
@Deprecated
|
||||
public class MethodsUtils {
|
||||
|
||||
public static boolean checkUser(String packagename, String current)
|
||||
{
|
||||
return current.substring(0, 8).equals(packagename);
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static <T> Object[] a(T classname, String methodname, Class[] classes, Object[] objects)
|
||||
{
|
||||
if (!checkUser(new String(new byte[] { 'm', 'e', '.', 's', 'k', 'y', 'm', 'c' }), new Exception().getStackTrace()[1].getClassName()))
|
||||
{
|
||||
throw new Error("未经允许的方法调用");
|
||||
}
|
||||
|
||||
Class<?> clazz = classname.getClass();
|
||||
Method method = null;
|
||||
try {
|
||||
method = clazz.getDeclaredMethod(methodname, classes);
|
||||
method.setAccessible(true);
|
||||
return new Object[] { method.invoke(classname, objects) };
|
||||
} catch (SecurityException | InvocationTargetException | IllegalAccessException | NoSuchMethodException | IllegalArgumentException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static <T> Object b(T classname, String fieldname)
|
||||
{
|
||||
if (!checkUser(new String(new byte[] { 'm', 'e', '.', 's', 'k', 'y', 'm', 'c' }), new Exception().getStackTrace()[1].getClassName()))
|
||||
{
|
||||
throw new Error("未经允许的方法调用");
|
||||
}
|
||||
public static boolean checkUser(String packagename, String current) {
|
||||
return current.substring(0, 8).equals(packagename);
|
||||
}
|
||||
|
||||
Class<?> clazz = classname.getClass();
|
||||
Field field = null;
|
||||
Object object = null;
|
||||
try {
|
||||
field = clazz.getDeclaredField(fieldname);
|
||||
field.setAccessible(true);
|
||||
object = field.get(classname);
|
||||
} catch (NoSuchFieldException | IllegalAccessException | IllegalArgumentException | SecurityException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return object;
|
||||
}
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static <T> Object[] a(T classname, String methodname, Class[] classes, Object[] objects) {
|
||||
if (!checkUser(new String(new byte[]{'m', 'e', '.', 's', 'k', 'y', 'm', 'c'}), new Exception().getStackTrace()[1].getClassName())) {
|
||||
throw new Error("未经允许的方法调用");
|
||||
}
|
||||
|
||||
Class<?> clazz = classname.getClass();
|
||||
Method method = null;
|
||||
try {
|
||||
method = clazz.getDeclaredMethod(methodname, classes);
|
||||
method.setAccessible(true);
|
||||
return new Object[]{method.invoke(classname, objects)};
|
||||
} catch (SecurityException | InvocationTargetException | IllegalAccessException | NoSuchMethodException | IllegalArgumentException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static <T> Object b(T classname, String fieldname) {
|
||||
if (!checkUser(new String(new byte[]{'m', 'e', '.', 's', 'k', 'y', 'm', 'c'}), new Exception().getStackTrace()[1].getClassName())) {
|
||||
throw new Error("未经允许的方法调用");
|
||||
}
|
||||
|
||||
Class<?> clazz = classname.getClass();
|
||||
Field field = null;
|
||||
Object object = null;
|
||||
try {
|
||||
field = clazz.getDeclaredField(fieldname);
|
||||
field.setAccessible(true);
|
||||
object = field.get(classname);
|
||||
} catch (NoSuchFieldException | IllegalAccessException | IllegalArgumentException | SecurityException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return object;
|
||||
}
|
||||
}
|
||||
@@ -1,347 +1,329 @@
|
||||
package me.skymc.taboolib.mysql;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.sql.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
@Deprecated
|
||||
public class MysqlConnection {
|
||||
|
||||
/**
|
||||
* Create by Bkm016
|
||||
*
|
||||
* 2017-7-22 23:25:55
|
||||
*/
|
||||
|
||||
private Connection connection = null;
|
||||
|
||||
private Statement statement = null;
|
||||
|
||||
private Boolean isConnection = false;
|
||||
|
||||
public MysqlConnection(String ip, String port, String table, String user, String pass) {
|
||||
try {
|
||||
Class.forName("com.mysql.jdbc.Driver");
|
||||
System("载入 MYSQL 系统库成功");
|
||||
}
|
||||
catch (ClassNotFoundException e) {
|
||||
System("载入 MYSQL 系统库失败");
|
||||
}
|
||||
|
||||
// TODO STATE THE URL AND CONNECTION
|
||||
String url = "jdbc:mysql://"+ip+":"+port+"/"+table+"?characterEncoding=utf-8";
|
||||
|
||||
// TODO CONNECTION
|
||||
try {
|
||||
connection = DriverManager.getConnection(url, user, pass);
|
||||
statement = connection.createStatement();
|
||||
|
||||
isConnection = true;
|
||||
System("连接 MYSQL 数据库成功");
|
||||
|
||||
new Thread(() -> {
|
||||
while (isConnection) {
|
||||
try {
|
||||
if (connection.isClosed()) {
|
||||
connection = DriverManager.getConnection(url, user, pass);
|
||||
System("数据库连接关闭, 正在重新连接... [Connection Closed]");
|
||||
}
|
||||
|
||||
Thread.sleep(30000);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
catch (SQLException e) {
|
||||
System("连接 MYSQL 数据库失败 详细信息: " + e.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void closeConnection()
|
||||
{
|
||||
try {
|
||||
if (statement != null) {
|
||||
statement.close();
|
||||
}
|
||||
if (connection != null) {
|
||||
connection.close();
|
||||
}
|
||||
|
||||
isConnection = false;
|
||||
System("结束 MYSQL 连接成功");
|
||||
}
|
||||
catch (SQLException e) {
|
||||
System("结束 MYSQL 连接失败 详细信息: " + e.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public Connection getConnection() {
|
||||
return this.connection;
|
||||
}
|
||||
|
||||
public Boolean isConnection() {
|
||||
try {
|
||||
if (statement.isClosed()) {
|
||||
statement = null;
|
||||
statement = connection.createStatement();
|
||||
System("数据库连接关闭, 正在重新连接... [Statement Closed]");
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return isConnection;
|
||||
}
|
||||
|
||||
public Statement getStatement() {
|
||||
return this.statement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Example: SQL_CreateTable("tablename", new String[] { "Player" });
|
||||
*/
|
||||
public void SQL_CreateTable(String table, String[] list) {
|
||||
if (!isConnection()) {
|
||||
return;
|
||||
}
|
||||
|
||||
StringBuilder stringBuilder = new StringBuilder("");
|
||||
|
||||
for (int i = 0 ; i < list.length ; i++) {
|
||||
if (i + 1 < list.length) {
|
||||
stringBuilder.append("`").append(checkString(list[i])).append("` varchar(255), ");
|
||||
}
|
||||
else {
|
||||
stringBuilder.append("`").append(checkString(list[i])).append("` varchar(255)");
|
||||
}
|
||||
}
|
||||
String url = "CREATE TABLE IF NOT EXISTS `" + table + "` ( " + stringBuilder + " )";
|
||||
|
||||
try {
|
||||
getStatement().execute(url);
|
||||
}
|
||||
catch (SQLException e) {
|
||||
System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage());
|
||||
System("任务: " + url);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Example: SQL_SetValues("tablename", new String[] { "Player" }, new String[] { "BlackSKY" });
|
||||
*/
|
||||
public void SQL_SetValues(String table, String[] list, String[] values) {
|
||||
if (!isConnection()) {
|
||||
return;
|
||||
}
|
||||
|
||||
StringBuilder listbuilder = new StringBuilder("");
|
||||
StringBuilder valuebuilder = new StringBuilder("");
|
||||
|
||||
for (int i = 0 ; i < list.length ; i++) {
|
||||
if (i + 1 < list.length) {
|
||||
listbuilder.append("`").append(checkString(list[i])).append("`, ");
|
||||
valuebuilder.append("'").append(checkString(values[i])).append("', ");
|
||||
}
|
||||
else {
|
||||
listbuilder.append("`").append(checkString(list[i])).append("`");
|
||||
valuebuilder.append("'").append(checkString(values[i])).append("'");
|
||||
}
|
||||
}
|
||||
|
||||
String url = "INSERT INTO `" + table + "` ( " + listbuilder + " ) VALUES ( " + valuebuilder + " )";
|
||||
try {
|
||||
getStatement().execute(url);
|
||||
}
|
||||
catch (SQLException e) {
|
||||
System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage());
|
||||
System("任务: " + url);
|
||||
for (int i = 0; i < e.getStackTrace().length && i < 5 ; i++) {
|
||||
String name = e.getStackTrace()[i].getClassName();
|
||||
|
||||
System("("+i+")位置: "+name.substring(0, name.lastIndexOf(".")));
|
||||
System(" 类名: "+e.getStackTrace()[i].getFileName().replaceAll(".java", ""));
|
||||
System(" 行数: "+e.getStackTrace()[i].getLineNumber());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Example: SQL_GetValue("tablename", "Player", "BlackSKY", "Value");
|
||||
*/
|
||||
public String SQL_GetValue(String table, String line, String linevalue, String row) {
|
||||
if (!isConnection()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String url = "SELECT * FROM " + checkString(table) + " WHERE `" + checkString(line) + "` = '" + checkString(linevalue) + "'";
|
||||
try {
|
||||
ResultSet resultSet = getStatement().executeQuery(url);
|
||||
while (resultSet.next()) {
|
||||
return resultSet.getString(row);
|
||||
}
|
||||
resultSet.close();
|
||||
}
|
||||
catch (SQLException e) {
|
||||
System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage());
|
||||
System("任务: " + url);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Example: SQL_GetValues("tablename", "Player");
|
||||
*/
|
||||
public List<String> SQL_GetValues(String table, String row) {
|
||||
if (!isConnection()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<String> list = new ArrayList<>();
|
||||
|
||||
String url = "SELECT * FROM " + checkString(table);
|
||||
try {
|
||||
ResultSet resultSet = getStatement().executeQuery(url);
|
||||
while (resultSet.next()) {
|
||||
if (resultSet.getString(row) == null) {
|
||||
continue;
|
||||
}
|
||||
list.add(resultSet.getString(row));
|
||||
}
|
||||
resultSet.close();
|
||||
}
|
||||
catch (SQLException e) {
|
||||
System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage());
|
||||
System("任务: " + url);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Example: SQL_isExists("tablename", "Player", "BlackSKY");
|
||||
*/
|
||||
public boolean SQL_isExists(String table, String row, String value) {
|
||||
if (!isConnection()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
String url = "SELECT * FROM " + checkString(table) + " WHERE `" + checkString(row) + "` = '" + checkString(value) + "'";
|
||||
try {
|
||||
ResultSet resultSet = getStatement().executeQuery(url);
|
||||
while (resultSet.next()) {
|
||||
return true;
|
||||
}
|
||||
resultSet.close();
|
||||
}
|
||||
catch (SQLException e) {
|
||||
System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage());
|
||||
System("任务: " + url);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Example: SQL_UpdateValue("tablename", "Player", "BlackSKY", "Value", "10")
|
||||
*/
|
||||
public void SQL_UpdateValue(String table, String line, String linevalue, String row, String value) {
|
||||
if (!isConnection()) {
|
||||
return;
|
||||
}
|
||||
|
||||
String url = "UPDATE `" + checkString(table) + "` SET `" + checkString(row) + "` = '" + checkString(value) + "' WHERE `" + checkString(line) + "` = '" + checkString(linevalue) + "'";
|
||||
try {
|
||||
getStatement().execute(url);
|
||||
}
|
||||
catch (SQLException e) {
|
||||
System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage());
|
||||
System("任务: " + url);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Example: SQL_DeleteValue("tablename", "BlackSKY");
|
||||
*/
|
||||
public void SQL_DeleteValue(String table, String line, String linevalue) {
|
||||
if (!isConnection()) {
|
||||
return;
|
||||
}
|
||||
|
||||
String url = "DELETE FROM `" + checkString(table) + "` WHERE `" + checkString(line) + "` = '" + checkString(linevalue) + "'";
|
||||
try {
|
||||
getStatement().execute(url);
|
||||
}
|
||||
catch (SQLException e) {
|
||||
System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage());
|
||||
System("任务: " + url);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated 即将过期
|
||||
*
|
||||
* @see Example: SQL_ClearTable("tablename");
|
||||
*/
|
||||
@Deprecated
|
||||
public void SQL_ClearTable(String table) {
|
||||
if (!isConnection()) {
|
||||
return;
|
||||
}
|
||||
|
||||
String url = "TRUNCATE TABLE `" + checkString(table) + "`";
|
||||
try {
|
||||
getStatement().execute(url);
|
||||
}
|
||||
catch (SQLException e) {
|
||||
System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage());
|
||||
System("任务: " + url);
|
||||
}
|
||||
}
|
||||
|
||||
public void SQL_execute(String url) {
|
||||
if (!isConnection()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
getStatement().execute(url);
|
||||
} catch (SQLException e) {
|
||||
System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage());
|
||||
System("任务: " + url);
|
||||
}
|
||||
}
|
||||
|
||||
public ResultSet SQL_executeQuery(String url) {
|
||||
if (!isConnection()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return getStatement().executeQuery(url);
|
||||
} catch (SQLException e) {
|
||||
System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage());
|
||||
System("任务: " + url);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void SQL_clearTable(String table) {
|
||||
SQL_execute("DELETE FROM " + checkString(table) + ";");
|
||||
}
|
||||
|
||||
public void SQL_deleteTable(String table) {
|
||||
SQL_execute("DROP TABLE " + checkString(table) + ";");
|
||||
}
|
||||
|
||||
private void System(String string) {
|
||||
System.out.println("[TabooLib - MYSQL] " + string);
|
||||
}
|
||||
|
||||
private String checkString(String string) {
|
||||
return string.replace("`", "").replace("'", "").replace("\"", "");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create by Bkm016
|
||||
* <p>
|
||||
* 2017-7-22 23:25:55
|
||||
*/
|
||||
|
||||
private Connection connection = null;
|
||||
|
||||
private Statement statement = null;
|
||||
|
||||
private Boolean isConnection = false;
|
||||
|
||||
public MysqlConnection(String ip, String port, String table, String user, String pass) {
|
||||
try {
|
||||
Class.forName("com.mysql.jdbc.Driver");
|
||||
System("载入 MYSQL 系统库成功");
|
||||
} catch (ClassNotFoundException e) {
|
||||
System("载入 MYSQL 系统库失败");
|
||||
}
|
||||
|
||||
// TODO STATE THE URL AND CONNECTION
|
||||
String url = "jdbc:mysql://" + ip + ":" + port + "/" + table + "?characterEncoding=utf-8";
|
||||
|
||||
// TODO CONNECTION
|
||||
try {
|
||||
connection = DriverManager.getConnection(url, user, pass);
|
||||
statement = connection.createStatement();
|
||||
|
||||
isConnection = true;
|
||||
System("连接 MYSQL 数据库成功");
|
||||
|
||||
Executors.newFixedThreadPool(1).execute(() -> {
|
||||
while (isConnection) {
|
||||
try {
|
||||
if (connection.isClosed()) {
|
||||
connection = DriverManager.getConnection(url, user, pass);
|
||||
System("数据库连接关闭, 正在重新连接... [Connection Closed]");
|
||||
}
|
||||
|
||||
Thread.sleep(30000);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (SQLException e) {
|
||||
System("连接 MYSQL 数据库失败 详细信息: " + e.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void closeConnection() {
|
||||
try {
|
||||
if (statement != null) {
|
||||
statement.close();
|
||||
}
|
||||
if (connection != null) {
|
||||
connection.close();
|
||||
}
|
||||
|
||||
isConnection = false;
|
||||
System("结束 MYSQL 连接成功");
|
||||
} catch (SQLException e) {
|
||||
System("结束 MYSQL 连接失败 详细信息: " + e.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public Connection getConnection() {
|
||||
return this.connection;
|
||||
}
|
||||
|
||||
public Boolean isConnection() {
|
||||
try {
|
||||
if (statement.isClosed()) {
|
||||
statement = null;
|
||||
statement = connection.createStatement();
|
||||
System("数据库连接关闭, 正在重新连接... [Statement Closed]");
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return isConnection;
|
||||
}
|
||||
|
||||
public Statement getStatement() {
|
||||
return this.statement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Example: SQL_CreateTable("tablename", new String[] { "Player" });
|
||||
*/
|
||||
public void SQL_CreateTable(String table, String[] list) {
|
||||
if (!isConnection()) {
|
||||
return;
|
||||
}
|
||||
|
||||
StringBuilder stringBuilder = new StringBuilder("");
|
||||
|
||||
for (int i = 0; i < list.length; i++) {
|
||||
if (i + 1 < list.length) {
|
||||
stringBuilder.append("`").append(checkString(list[i])).append("` varchar(255), ");
|
||||
} else {
|
||||
stringBuilder.append("`").append(checkString(list[i])).append("` varchar(255)");
|
||||
}
|
||||
}
|
||||
String url = "CREATE TABLE IF NOT EXISTS `" + table + "` ( " + stringBuilder + " )";
|
||||
|
||||
try {
|
||||
getStatement().execute(url);
|
||||
} catch (SQLException e) {
|
||||
System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage());
|
||||
System("任务: " + url);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Example: SQL_SetValues("tablename", new String[] { "Player" }, new String[] { "BlackSKY" });
|
||||
*/
|
||||
public void SQL_SetValues(String table, String[] list, String[] values) {
|
||||
if (!isConnection()) {
|
||||
return;
|
||||
}
|
||||
|
||||
StringBuilder listbuilder = new StringBuilder("");
|
||||
StringBuilder valuebuilder = new StringBuilder("");
|
||||
|
||||
for (int i = 0; i < list.length; i++) {
|
||||
if (i + 1 < list.length) {
|
||||
listbuilder.append("`").append(checkString(list[i])).append("`, ");
|
||||
valuebuilder.append("'").append(checkString(values[i])).append("', ");
|
||||
} else {
|
||||
listbuilder.append("`").append(checkString(list[i])).append("`");
|
||||
valuebuilder.append("'").append(checkString(values[i])).append("'");
|
||||
}
|
||||
}
|
||||
|
||||
String url = "INSERT INTO `" + table + "` ( " + listbuilder + " ) VALUES ( " + valuebuilder + " )";
|
||||
try {
|
||||
getStatement().execute(url);
|
||||
} catch (SQLException e) {
|
||||
System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage());
|
||||
System("任务: " + url);
|
||||
for (int i = 0; i < e.getStackTrace().length && i < 5; i++) {
|
||||
String name = e.getStackTrace()[i].getClassName();
|
||||
|
||||
System("(" + i + ")位置: " + name.substring(0, name.lastIndexOf(".")));
|
||||
System(" 类名: " + e.getStackTrace()[i].getFileName().replaceAll(".java", ""));
|
||||
System(" 行数: " + e.getStackTrace()[i].getLineNumber());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Example: SQL_GetValue("tablename", "Player", "BlackSKY", "Value");
|
||||
*/
|
||||
public String SQL_GetValue(String table, String line, String linevalue, String row) {
|
||||
if (!isConnection()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String url = "SELECT * FROM " + checkString(table) + " WHERE `" + checkString(line) + "` = '" + checkString(linevalue) + "'";
|
||||
try {
|
||||
ResultSet resultSet = getStatement().executeQuery(url);
|
||||
while (resultSet.next()) {
|
||||
return resultSet.getString(row);
|
||||
}
|
||||
resultSet.close();
|
||||
} catch (SQLException e) {
|
||||
System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage());
|
||||
System("任务: " + url);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Example: SQL_GetValues("tablename", "Player");
|
||||
*/
|
||||
public List<String> SQL_GetValues(String table, String row) {
|
||||
if (!isConnection()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<String> list = new ArrayList<>();
|
||||
|
||||
String url = "SELECT * FROM " + checkString(table);
|
||||
try {
|
||||
ResultSet resultSet = getStatement().executeQuery(url);
|
||||
while (resultSet.next()) {
|
||||
if (resultSet.getString(row) == null) {
|
||||
continue;
|
||||
}
|
||||
list.add(resultSet.getString(row));
|
||||
}
|
||||
resultSet.close();
|
||||
} catch (SQLException e) {
|
||||
System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage());
|
||||
System("任务: " + url);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Example: SQL_isExists("tablename", "Player", "BlackSKY");
|
||||
*/
|
||||
public boolean SQL_isExists(String table, String row, String value) {
|
||||
if (!isConnection()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
String url = "SELECT * FROM " + checkString(table) + " WHERE `" + checkString(row) + "` = '" + checkString(value) + "'";
|
||||
try {
|
||||
ResultSet resultSet = getStatement().executeQuery(url);
|
||||
while (resultSet.next()) {
|
||||
return true;
|
||||
}
|
||||
resultSet.close();
|
||||
} catch (SQLException e) {
|
||||
System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage());
|
||||
System("任务: " + url);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Example: SQL_UpdateValue("tablename", "Player", "BlackSKY", "Value", "10")
|
||||
*/
|
||||
public void SQL_UpdateValue(String table, String line, String linevalue, String row, String value) {
|
||||
if (!isConnection()) {
|
||||
return;
|
||||
}
|
||||
|
||||
String url = "UPDATE `" + checkString(table) + "` SET `" + checkString(row) + "` = '" + checkString(value) + "' WHERE `" + checkString(line) + "` = '" + checkString(linevalue) + "'";
|
||||
try {
|
||||
getStatement().execute(url);
|
||||
} catch (SQLException e) {
|
||||
System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage());
|
||||
System("任务: " + url);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Example: SQL_DeleteValue("tablename", "BlackSKY");
|
||||
*/
|
||||
public void SQL_DeleteValue(String table, String line, String linevalue) {
|
||||
if (!isConnection()) {
|
||||
return;
|
||||
}
|
||||
|
||||
String url = "DELETE FROM `" + checkString(table) + "` WHERE `" + checkString(line) + "` = '" + checkString(linevalue) + "'";
|
||||
try {
|
||||
getStatement().execute(url);
|
||||
} catch (SQLException e) {
|
||||
System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage());
|
||||
System("任务: " + url);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Example: SQL_ClearTable("tablename");
|
||||
* @deprecated 即将过期
|
||||
*/
|
||||
@Deprecated
|
||||
public void SQL_ClearTable(String table) {
|
||||
if (!isConnection()) {
|
||||
return;
|
||||
}
|
||||
|
||||
String url = "TRUNCATE TABLE `" + checkString(table) + "`";
|
||||
try {
|
||||
getStatement().execute(url);
|
||||
} catch (SQLException e) {
|
||||
System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage());
|
||||
System("任务: " + url);
|
||||
}
|
||||
}
|
||||
|
||||
public void SQL_execute(String url) {
|
||||
if (!isConnection()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
getStatement().execute(url);
|
||||
} catch (SQLException e) {
|
||||
System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage());
|
||||
System("任务: " + url);
|
||||
}
|
||||
}
|
||||
|
||||
public ResultSet SQL_executeQuery(String url) {
|
||||
if (!isConnection()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return getStatement().executeQuery(url);
|
||||
} catch (SQLException e) {
|
||||
System("执行 MYSQL 任务出错 详细信息: " + e.getLocalizedMessage());
|
||||
System("任务: " + url);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void SQL_clearTable(String table) {
|
||||
SQL_execute("DELETE FROM " + checkString(table) + ";");
|
||||
}
|
||||
|
||||
public void SQL_deleteTable(String table) {
|
||||
SQL_execute("DROP TABLE " + checkString(table) + ";");
|
||||
}
|
||||
|
||||
private void System(String string) {
|
||||
System.out.println("[TabooLib - MYSQL] " + string);
|
||||
}
|
||||
|
||||
private String checkString(String string) {
|
||||
return string.replace("`", "").replace("'", "").replace("\"", "");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,38 +1,37 @@
|
||||
package me.skymc.taboolib.mysql;
|
||||
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import me.skymc.taboolib.Main;
|
||||
import me.skymc.taboolib.mysql.protect.MySQLConnection;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import me.skymc.taboolib.Main;
|
||||
import me.skymc.taboolib.message.MsgUtils;
|
||||
import me.skymc.taboolib.mysql.protect.MySQLConnection;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
public class MysqlUtils {
|
||||
|
||||
public final static CopyOnWriteArrayList<MySQLConnection> CONNECTIONS = new CopyOnWriteArrayList<>();
|
||||
|
||||
public static MysqlConnection getMysqlConnectionFromConfiguration(FileConfiguration conf, String key) {
|
||||
return new MysqlConnection(conf.getString(key + ".host"), conf.getString(key + ".port"), conf.getString(key + ".database"), conf.getString(key + ".user"), conf.getString(key + ".pass"));
|
||||
}
|
||||
|
||||
public static MySQLConnection getMySQLConnectionFromConfiguration(FileConfiguration conf, String key) {
|
||||
return getMySQLConnectionFromConfiguration(conf, key, 60, Main.getInst());
|
||||
}
|
||||
|
||||
public static MySQLConnection getMySQLConnectionFromConfiguration(FileConfiguration conf, String key, int recheck, Plugin plugin) {
|
||||
MySQLConnection conn = new MySQLConnection(
|
||||
conf.getString(key + ".url"),
|
||||
conf.getString(key + ".user"),
|
||||
conf.getString(key + ".port"),
|
||||
conf.getString(key + ".password"),
|
||||
conf.getString(key + ".database"), recheck, plugin);
|
||||
|
||||
if (conn.isConnection()) {
|
||||
CONNECTIONS.add(conn);
|
||||
MsgUtils.send("已向书库注册插件 &f" + plugin.getName() + "&7 的数据库连接");
|
||||
}
|
||||
return conn;
|
||||
}
|
||||
|
||||
public final static CopyOnWriteArrayList<MySQLConnection> CONNECTIONS = new CopyOnWriteArrayList<>();
|
||||
|
||||
public static MysqlConnection getMysqlConnectionFromConfiguration(FileConfiguration conf, String key) {
|
||||
return new MysqlConnection(conf.getString(key + ".host"), conf.getString(key + ".port"), conf.getString(key + ".database"), conf.getString(key + ".user"), conf.getString(key + ".pass"));
|
||||
}
|
||||
|
||||
public static MySQLConnection getMySQLConnectionFromConfiguration(FileConfiguration conf, String key) {
|
||||
return getMySQLConnectionFromConfiguration(conf, key, 60, Main.getInst());
|
||||
}
|
||||
|
||||
public static MySQLConnection getMySQLConnectionFromConfiguration(FileConfiguration conf, String key, int recheck, Plugin plugin) {
|
||||
MySQLConnection conn = new MySQLConnection(
|
||||
conf.getString(key + ".url"),
|
||||
conf.getString(key + ".user"),
|
||||
conf.getString(key + ".port"),
|
||||
conf.getString(key + ".password"),
|
||||
conf.getString(key + ".database"), recheck, plugin);
|
||||
|
||||
if (conn.isConnection()) {
|
||||
CONNECTIONS.add(conn);
|
||||
TLocale.Logger.info("MYSQL-CONNECTION.SUCCESS-REGISTERED", plugin.getName());
|
||||
}
|
||||
return conn;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
package me.skymc.taboolib.mysql.protect;
|
||||
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import com.ilummc.tlib.util.Strings;
|
||||
import me.skymc.taboolib.Main;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import java.sql.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* @author sky
|
||||
*/
|
||||
public class MySQLConnection {
|
||||
|
||||
private String url;
|
||||
@@ -30,7 +36,7 @@ public class MySQLConnection {
|
||||
public MySQLConnection(String url, String user, String port, String password, String database, int recheck, Plugin plugin) {
|
||||
// 检查驱动
|
||||
if (!loadDriverMySQL()) {
|
||||
print("驱动器获取失败, 无法连接到数据库");
|
||||
TLocale.Logger.error("MYSQL-CONNECTION.FALL-NOTFOUND-DRIVE");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -44,7 +50,7 @@ public class MySQLConnection {
|
||||
this.port = port == null ? "3306" : port;
|
||||
this.password = password == null ? "" : password;
|
||||
this.database = database == null ? "test" : database;
|
||||
this.connectionUrl = "jdbc:mysql://" + this.url + ":" + this.port + "/" + this.database + "?characterEncoding=utf-8&useSSL=false";
|
||||
this.connectionUrl = Strings.replaceWithOrder("jdbc:mysql://{0}:{1}/{2}?characterEncoding=utf-8&useSSL=false", this.url, this.port, this.database);
|
||||
|
||||
// 连接数据库
|
||||
connect();
|
||||
@@ -56,13 +62,12 @@ public class MySQLConnection {
|
||||
Thread.sleep(getReCheckSeconds() * 1000);
|
||||
|
||||
if (connection == null) {
|
||||
print("警告! 数据库尚未连接, 请检查配置文件后重启服务器! (" + (plugin.getName()) + ")");
|
||||
TLocale.Logger.error("MYSQL-CONNECTION.FALL-NOTFOUND-CONNECTION", plugin.getName());
|
||||
} else {
|
||||
isExists("taboolib");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
print("数据库命令执行出错");
|
||||
print("错误原因: " + e.getMessage());
|
||||
TLocale.Logger.error("MYSQL-CONNECTION.FALL-COMMAND-NORMAL", e.toString());
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -70,7 +75,7 @@ public class MySQLConnection {
|
||||
// 启动检测
|
||||
if (isConnection()) {
|
||||
recheckThread.start();
|
||||
print("启动数据库连接监控");
|
||||
TLocale.Logger.info("MYSQL-CONNECTION.SUCCESS-REGISTERED-LISTENER");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,13 +154,11 @@ public class MySQLConnection {
|
||||
public void closeConnection() {
|
||||
try {
|
||||
connection.close();
|
||||
} catch (Exception e) {
|
||||
//
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
try {
|
||||
recheckThread.stop();
|
||||
} catch (Exception e) {
|
||||
//
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,8 +169,8 @@ public class MySQLConnection {
|
||||
/**
|
||||
* 2018年1月17日 新增, TabooLib 版本 3.25
|
||||
*/
|
||||
public void truncateTable(String name) {
|
||||
execute("truncate table " + name);
|
||||
public boolean truncateTable(String name) {
|
||||
return execute("truncate table " + name);
|
||||
}
|
||||
|
||||
public boolean clearTable(String name) {
|
||||
@@ -175,35 +178,33 @@ public class MySQLConnection {
|
||||
}
|
||||
|
||||
public boolean renameTable(String name, String newName) {
|
||||
return execute("rename table `" + name + "` to `" + newName + "`");
|
||||
return execute(Strings.replaceWithOrder("rename table `{0}` to `{1}`", name, newName));
|
||||
}
|
||||
|
||||
public boolean deleteColumn(String name, String column) {
|
||||
return execute("alter table `" + name + "` drop `" + column + "`");
|
||||
return execute(Strings.replaceWithOrder("alter table `{0}` drop `{1}`", name, column));
|
||||
}
|
||||
|
||||
public void addColumn(String name, Column... columns) {
|
||||
for (Column column : columns) {
|
||||
execute("alter table " + name + " add " + column.toString());
|
||||
}
|
||||
Arrays.stream(columns).map(column -> Strings.replaceWithOrder("alter table {0} add {1}", name, column.toString())).forEach(this::execute);
|
||||
}
|
||||
|
||||
public boolean addColumn(String name, String column) {
|
||||
if (!column.contains("/")) {
|
||||
return execute("alter table " + name + " add `" + column + "` text");
|
||||
return execute(Strings.replaceWithOrder("alter table {0} add `{1}` text", name, column));
|
||||
}
|
||||
return execute("alter table " + name + " add `" + column.split("/")[0] + "` " + column.split("/")[1]);
|
||||
return execute(Strings.replaceWithOrder("alter table {0} add `{1}` {2}", name, column.split("/")[0], column.split("/")[1]));
|
||||
}
|
||||
|
||||
public boolean editColumn(String name, String oldColumn, Column newColumn) {
|
||||
return execute("alter table " + name + " change `" + oldColumn + "` " + newColumn.toString());
|
||||
return execute(Strings.replaceWithOrder("alter table {0} change `{1}` {2}", name, oldColumn, newColumn.toString()));
|
||||
}
|
||||
|
||||
public boolean editColumn(String name, String oldColumn, String newColumn) {
|
||||
if (!newColumn.contains("/")) {
|
||||
return execute("alter table " + name + " change `" + oldColumn + "` `" + newColumn + "` text");
|
||||
return execute(Strings.replaceWithOrder("alter table {0} change `{1}` `{2}` text", name, oldColumn, newColumn));
|
||||
}
|
||||
return execute("alter table " + name + " change `" + oldColumn + "` `" + newColumn.split("/")[0] + "` " + newColumn.split("/")[1]);
|
||||
return execute(Strings.replaceWithOrder("alter table {0} change `{1}` `{2}` {3}", name, oldColumn, newColumn.split("/")[0], newColumn.split("/")[1]));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -215,21 +216,15 @@ public class MySQLConnection {
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean deleteValue(String name, String column, Object columnValue) {
|
||||
PreparedStatement pstmt = null;
|
||||
ResultSet resultSet = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
try {
|
||||
pstmt = connection.prepareStatement("delete from `" + name + "` where `" + column + "` = ?");
|
||||
pstmt.setObject(1, columnValue);
|
||||
pstmt.executeUpdate();
|
||||
preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("delete from `{0}` where `{1}` = ?", name, column));
|
||||
preparedStatement.setObject(1, columnValue);
|
||||
preparedStatement.executeUpdate();
|
||||
} catch (Exception e) {
|
||||
print("数据库命令执行出错");
|
||||
print("错误原因: " + e.getMessage());
|
||||
// 重新连接
|
||||
if (fallReconnection && e.getMessage().contains("closed")) {
|
||||
connect();
|
||||
}
|
||||
printException(e);
|
||||
} finally {
|
||||
freeResult(null, pstmt);
|
||||
freeResult(null, preparedStatement);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -260,26 +255,20 @@ public class MySQLConnection {
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean setValue(String name, String column, Object columnValue, String valueColumn, Object value, boolean append) {
|
||||
PreparedStatement pstmt = null;
|
||||
ResultSet resultSet = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
try {
|
||||
if (append) {
|
||||
pstmt = connection.prepareStatement("update `" + name + "` set `" + valueColumn + "` = `" + valueColumn + "` + ? where `" + column + "` = ?");
|
||||
preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("update `{0}` set `{1}` = `{2}` + ? where `{3}` = ?", name, valueColumn, valueColumn, column));
|
||||
} else {
|
||||
pstmt = connection.prepareStatement("update `" + name + "` set `" + valueColumn + "` = ? where `" + column + "` = ?");
|
||||
preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("update `{0}` set `{1}` = ? where `{2}` = ?", name, valueColumn, column));
|
||||
}
|
||||
pstmt.setObject(1, value);
|
||||
pstmt.setObject(2, columnValue);
|
||||
pstmt.executeUpdate();
|
||||
preparedStatement.setObject(1, value);
|
||||
preparedStatement.setObject(2, columnValue);
|
||||
preparedStatement.executeUpdate();
|
||||
} catch (Exception e) {
|
||||
print("数据库命令执行出错");
|
||||
print("错误原因: " + e.getMessage());
|
||||
// 重新连接
|
||||
if (fallReconnection && e.getMessage().contains("closed")) {
|
||||
connect();
|
||||
}
|
||||
printException(e);
|
||||
} finally {
|
||||
freeResult(resultSet, pstmt);
|
||||
freeResult(null, preparedStatement);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -293,26 +282,19 @@ public class MySQLConnection {
|
||||
*/
|
||||
public boolean intoValue(String name, Object... values) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Object value : values) {
|
||||
sb.append("?, ");
|
||||
}
|
||||
PreparedStatement pstmt = null;
|
||||
Arrays.stream(values).map(value -> "?, ").forEach(sb::append);
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
try {
|
||||
pstmt = connection.prepareStatement("insert into `" + name + "` values(null, " + sb.substring(0, sb.length() - 2) + ")");
|
||||
preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("insert into `{0}` values(null, {1})", name, sb.substring(0, sb.length() - 2)));
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
pstmt.setObject(i + 1, values[i]);
|
||||
preparedStatement.setObject(i + 1, values[i]);
|
||||
}
|
||||
pstmt.executeUpdate();
|
||||
preparedStatement.executeUpdate();
|
||||
} catch (Exception e) {
|
||||
print("数据库命令执行出错");
|
||||
print("错误原因: " + e.getMessage());
|
||||
// 重新连接
|
||||
if (fallReconnection && e.getMessage().contains("closed")) {
|
||||
connect();
|
||||
}
|
||||
printException(e);
|
||||
} finally {
|
||||
freeResult(resultSet, pstmt);
|
||||
freeResult(null, preparedStatement);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -326,10 +308,8 @@ public class MySQLConnection {
|
||||
*/
|
||||
public boolean createTable(String name, Column... columns) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Column column : columns) {
|
||||
sb.append(column.toString()).append(", ");
|
||||
}
|
||||
return execute("create table if not exists " + name + " (id int(1) not null primary key auto_increment, " + sb.substring(0, sb.length() - 2) + ")");
|
||||
Arrays.stream(columns).forEach(column -> sb.append(column.toString()).append(", "));
|
||||
return execute(Strings.replaceWithOrder("create table if not exists {0} (id int(1) not null primary key auto_increment, {1})", name, sb.substring(0, sb.length() - 2)));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -348,7 +328,7 @@ public class MySQLConnection {
|
||||
sb.append("`").append(column.split("/")[0]).append("` ").append(column.split("/")[1]).append(", ");
|
||||
}
|
||||
}
|
||||
return execute("create table if not exists " + name + " (id int(1) not null primary key auto_increment, " + sb.substring(0, sb.length() - 2) + ")");
|
||||
return execute(Strings.replaceWithOrder("create table if not exists {0} (id int(1) not null primary key auto_increment, {1})", name, sb.substring(0, sb.length() - 2)));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -358,24 +338,19 @@ public class MySQLConnection {
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean isExists(String name) {
|
||||
PreparedStatement pstmt = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
try {
|
||||
pstmt = connection.prepareStatement("select table_name FROM information_schema.TABLES where table_name = ?");
|
||||
pstmt.setString(1, name);
|
||||
resultSet = pstmt.executeQuery();
|
||||
preparedStatement = connection.prepareStatement("select table_name FROM information_schema.TABLES where table_name = ?");
|
||||
preparedStatement.setString(1, name);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
while (resultSet.next()) {
|
||||
return true;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
print("数据库命令执行出错");
|
||||
print("错误原因: " + e.getMessage());
|
||||
// 重新连接
|
||||
if (fallReconnection && e.getMessage().contains("closed")) {
|
||||
connect();
|
||||
}
|
||||
printException(e);
|
||||
} finally {
|
||||
freeResult(resultSet, pstmt);
|
||||
freeResult(resultSet, preparedStatement);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -389,24 +364,19 @@ public class MySQLConnection {
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean isExists(String name, String column, Object columnValue) {
|
||||
PreparedStatement pstmt = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
try {
|
||||
pstmt = connection.prepareStatement("select * from `" + name + "` where `" + column + "` = ?");
|
||||
pstmt.setObject(1, columnValue);
|
||||
resultSet = pstmt.executeQuery();
|
||||
preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("select * from `{0}` where `{1}` = ?", name, column));
|
||||
preparedStatement.setObject(1, columnValue);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
while (resultSet.next()) {
|
||||
return true;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
print("数据库命令执行出错");
|
||||
print("错误原因: " + e.getMessage());
|
||||
// 重新连接
|
||||
if (fallReconnection && e.getMessage().contains("closed")) {
|
||||
connect();
|
||||
}
|
||||
printException(e);
|
||||
} finally {
|
||||
freeResult(resultSet, pstmt);
|
||||
freeResult(resultSet, preparedStatement);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -430,24 +400,19 @@ public class MySQLConnection {
|
||||
*/
|
||||
public List<String> getColumns(String name, boolean primary) {
|
||||
List<String> list = new ArrayList<>();
|
||||
PreparedStatement pstmt = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
try {
|
||||
pstmt = connection.prepareStatement("select column_name from information_schema.COLUMNS where table_name = ?");
|
||||
pstmt.setString(1, name);
|
||||
resultSet = pstmt.executeQuery();
|
||||
preparedStatement = connection.prepareStatement("select column_name from information_schema.COLUMNS where table_name = ?");
|
||||
preparedStatement.setString(1, name);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
while (resultSet.next()) {
|
||||
list.add(resultSet.getString(1));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
print("数据库命令执行出错");
|
||||
print("错误原因: " + e.getMessage());
|
||||
// 重新连接
|
||||
if (fallReconnection && e.getMessage().contains("closed")) {
|
||||
connect();
|
||||
}
|
||||
printException(e);
|
||||
} finally {
|
||||
freeResult(resultSet, pstmt);
|
||||
freeResult(resultSet, preparedStatement);
|
||||
}
|
||||
// 是否获取主键
|
||||
if (!primary) {
|
||||
@@ -466,24 +431,19 @@ public class MySQLConnection {
|
||||
* @return Object
|
||||
*/
|
||||
public Object getValue(String name, String column, Object columnValue, String valueColumn) {
|
||||
PreparedStatement pstmt = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
try {
|
||||
pstmt = connection.prepareStatement("select * from `" + name + "` where `" + column + "` = ? limit 1");
|
||||
pstmt.setObject(1, columnValue);
|
||||
resultSet = pstmt.executeQuery();
|
||||
preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("select * from `{0}` where `{1}` = ? limit 1", name, column));
|
||||
preparedStatement.setObject(1, columnValue);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
while (resultSet.next()) {
|
||||
return resultSet.getObject(valueColumn);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
print("数据库命令执行出错");
|
||||
print("错误原因: " + e.getMessage());
|
||||
// 重新连接
|
||||
if (fallReconnection && e.getMessage().contains("closed")) {
|
||||
connect();
|
||||
}
|
||||
printException(e);
|
||||
} finally {
|
||||
freeResult(resultSet, pstmt);
|
||||
freeResult(resultSet, preparedStatement);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -498,24 +458,19 @@ public class MySQLConnection {
|
||||
* @return Object
|
||||
*/
|
||||
public Object getValueLast(String name, String column, Object columnValue, String valueColumn) {
|
||||
PreparedStatement pstmt = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
try {
|
||||
pstmt = connection.prepareStatement("select * from `" + name + "` where `" + column + "` = ? order by id desc limit 1");
|
||||
pstmt.setObject(1, columnValue);
|
||||
resultSet = pstmt.executeQuery();
|
||||
preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("select * from `{0}` where `{1}` = ? order by id desc limit 1", name, column));
|
||||
preparedStatement.setObject(1, columnValue);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
while (resultSet.next()) {
|
||||
return resultSet.getObject(valueColumn);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
print("数据库命令执行出错");
|
||||
print("错误原因: " + e.getMessage());
|
||||
// 重新连接
|
||||
if (fallReconnection && e.getMessage().contains("closed")) {
|
||||
connect();
|
||||
}
|
||||
printException(e);
|
||||
} finally {
|
||||
freeResult(resultSet, pstmt);
|
||||
freeResult(resultSet, preparedStatement);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -531,12 +486,12 @@ public class MySQLConnection {
|
||||
*/
|
||||
public HashMap<String, Object> getValueLast(String name, String column, Object columnValue, String... valueColumn) {
|
||||
HashMap<String, Object> map = new HashMap<>();
|
||||
PreparedStatement pstmt = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
try {
|
||||
pstmt = connection.prepareStatement("select * from `" + name + "` where `" + column + "` = ? order by id desc limit 1");
|
||||
pstmt.setObject(1, columnValue);
|
||||
resultSet = pstmt.executeQuery();
|
||||
preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("select * from `{0}` where `{1}` = ? order by id desc limit 1", name, column));
|
||||
preparedStatement.setObject(1, columnValue);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
while (resultSet.next()) {
|
||||
for (String _column : valueColumn) {
|
||||
map.put(_column, resultSet.getObject(_column));
|
||||
@@ -544,14 +499,9 @@ public class MySQLConnection {
|
||||
break;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
print("数据库命令执行出错");
|
||||
print("错误原因: " + e.getMessage());
|
||||
// 重新连接
|
||||
if (fallReconnection && e.getMessage().contains("closed")) {
|
||||
connect();
|
||||
}
|
||||
printException(e);
|
||||
} finally {
|
||||
freeResult(resultSet, pstmt);
|
||||
freeResult(resultSet, preparedStatement);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
@@ -567,12 +517,12 @@ public class MySQLConnection {
|
||||
*/
|
||||
public HashMap<String, Object> getValue(String name, String column, Object columnValue, String... valueColumn) {
|
||||
HashMap<String, Object> map = new HashMap<>();
|
||||
PreparedStatement pstmt = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
try {
|
||||
pstmt = connection.prepareStatement("select * from `" + name + "` where `" + column + "` = ? limit 1");
|
||||
pstmt.setObject(1, columnValue);
|
||||
resultSet = pstmt.executeQuery();
|
||||
preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("select * from `{0}` where `{1}` = ? limit 1", name, column));
|
||||
preparedStatement.setObject(1, columnValue);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
while (resultSet.next()) {
|
||||
for (String _column : valueColumn) {
|
||||
map.put(_column, resultSet.getObject(_column));
|
||||
@@ -580,14 +530,9 @@ public class MySQLConnection {
|
||||
break;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
print("数据库命令执行出错");
|
||||
print("错误原因: " + e.getMessage());
|
||||
// 重新连接
|
||||
if (fallReconnection && e.getMessage().contains("closed")) {
|
||||
connect();
|
||||
}
|
||||
printException(e);
|
||||
} finally {
|
||||
freeResult(resultSet, pstmt);
|
||||
freeResult(resultSet, preparedStatement);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
@@ -615,27 +560,22 @@ public class MySQLConnection {
|
||||
*/
|
||||
public List<Object> getValues(String name, String column, int size, boolean desc) {
|
||||
List<Object> list = new LinkedList<>();
|
||||
PreparedStatement pstmt = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
try {
|
||||
if (desc) {
|
||||
pstmt = connection.prepareStatement("select * from `" + name + "` order by `" + column + "` desc " + (size < 0 ? "" : " limit " + size));
|
||||
preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("select * from `{0}` order by `{1}` desc {2}", name, column, size < 0 ? "" : " limit " + size));
|
||||
} else {
|
||||
pstmt = connection.prepareStatement("select * from `" + name + "` order by `" + column + "` " + (size < 0 ? "" : " limit " + size));
|
||||
preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("select * from `{0}` order by `{1}` {2}", name, column, size < 0 ? "" : " limit " + size));
|
||||
}
|
||||
resultSet = pstmt.executeQuery();
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
while (resultSet.next()) {
|
||||
list.add(resultSet.getObject(column));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
print("数据库命令执行出错");
|
||||
print("错误原因: " + e.getMessage());
|
||||
// 重新连接
|
||||
if (fallReconnection && e.getMessage().contains("closed")) {
|
||||
connect();
|
||||
}
|
||||
printException(e);
|
||||
} finally {
|
||||
freeResult(resultSet, pstmt);
|
||||
freeResult(resultSet, preparedStatement);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
@@ -665,15 +605,15 @@ public class MySQLConnection {
|
||||
*/
|
||||
public LinkedList<HashMap<String, Object>> getValues(String name, String sortColumn, int size, boolean desc, String... valueColumn) {
|
||||
LinkedList<HashMap<String, Object>> list = new LinkedList<>();
|
||||
PreparedStatement pstmt = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
try {
|
||||
if (desc) {
|
||||
pstmt = connection.prepareStatement("select * from `" + name + "` order by `" + sortColumn + "` desc" + (size < 0 ? "" : " limit " + size));
|
||||
preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("select * from `{0}` order by `{1}` desc{2}", name, sortColumn, size < 0 ? "" : " limit " + size));
|
||||
} else {
|
||||
pstmt = connection.prepareStatement("select * from `" + name + "` order by `" + sortColumn + "`" + (size < 0 ? "" : " limit " + size));
|
||||
preparedStatement = connection.prepareStatement(Strings.replaceWithOrder("select * from `{0}` order by `{1}`{2}", name, sortColumn, size < 0 ? "" : " limit " + size));
|
||||
}
|
||||
resultSet = pstmt.executeQuery();
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
while (resultSet.next()) {
|
||||
HashMap<String, Object> map = new HashMap<>();
|
||||
for (String _column : valueColumn) {
|
||||
@@ -682,56 +622,36 @@ public class MySQLConnection {
|
||||
list.add(map);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
print("数据库命令执行出错");
|
||||
print("错误原因: " + e.getMessage());
|
||||
// 重新连接
|
||||
if (fallReconnection && e.getMessage().contains("closed")) {
|
||||
connect();
|
||||
}
|
||||
printException(e);
|
||||
} finally {
|
||||
freeResult(resultSet, pstmt);
|
||||
freeResult(resultSet, preparedStatement);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public boolean execute(String sql) {
|
||||
PreparedStatement pstmt = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
try {
|
||||
pstmt = connection.prepareStatement(sql);
|
||||
pstmt.execute();
|
||||
preparedStatement = connection.prepareStatement(sql);
|
||||
preparedStatement.execute();
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
print("数据库命令执行出错");
|
||||
print("错误原因: " + e.getMessage());
|
||||
print("错误命令: " + sql);
|
||||
// 重连
|
||||
if (e.getMessage().contains("closed")) {
|
||||
connect();
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
printExceptionDetail(e);
|
||||
return false;
|
||||
} finally {
|
||||
try {
|
||||
if (pstmt != null) {
|
||||
pstmt.close();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
//
|
||||
}
|
||||
freeResult(null, preparedStatement);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean connect() {
|
||||
TLocale.Logger.info("MYSQL-CONNECTION.NOTIFY-CONNECTING", connectionUrl);
|
||||
try {
|
||||
print("正在连接数据库");
|
||||
print("地址: " + connectionUrl);
|
||||
long time = System.currentTimeMillis();
|
||||
connection = DriverManager.getConnection(connectionUrl, this.user, this.password);
|
||||
print("数据库连接成功 (" + (System.currentTimeMillis() - time) + "ms)");
|
||||
TLocale.Logger.info("MYSQL-CONNECTION.NOTIFY-CONNECTED", String.valueOf(System.currentTimeMillis() - time));
|
||||
return true;
|
||||
} catch (SQLException e) {
|
||||
print("数据库连接失败");
|
||||
print("错误原因: " + e.getMessage());
|
||||
print("错误代码: " + e.getErrorCode());
|
||||
printExceptionDetail(e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -740,26 +660,19 @@ public class MySQLConnection {
|
||||
System.out.println("[TabooLib - MySQL] " + message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 释放结果集
|
||||
*
|
||||
* @param resultSet 不知道叫什么
|
||||
* @param pstmt 不知道叫什么
|
||||
*/
|
||||
private void freeResult(ResultSet resultSet, PreparedStatement pstmt) {
|
||||
try {
|
||||
if (resultSet != null) {
|
||||
resultSet.close();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
//
|
||||
}
|
||||
try {
|
||||
if (pstmt != null) {
|
||||
pstmt.close();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
//
|
||||
private void printException(Exception e) {
|
||||
TLocale.Logger.error("MYSQL-CONNECTION.FALL-COMMAND-NORMAL", e.toString());
|
||||
reconnection(e);
|
||||
}
|
||||
|
||||
private void printExceptionDetail(SQLException e) {
|
||||
TLocale.Logger.error("MYSQL-CONNECTION.FALL-COMMAND-DETAIL", String.valueOf(e.getErrorCode()), e.toString());
|
||||
reconnection(e);
|
||||
}
|
||||
|
||||
private void reconnection(Exception e) {
|
||||
if (fallReconnection && e.getMessage().contains("closed")) {
|
||||
connect();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -772,6 +685,21 @@ public class MySQLConnection {
|
||||
}
|
||||
}
|
||||
|
||||
private void freeResult(ResultSet resultSet, PreparedStatement preparedStatement) {
|
||||
try {
|
||||
if (resultSet != null) {
|
||||
resultSet.close();
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
try {
|
||||
if (preparedStatement != null) {
|
||||
preparedStatement.close();
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
public enum ColumnInteger {
|
||||
|
||||
TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT
|
||||
@@ -837,11 +765,11 @@ public class MySQLConnection {
|
||||
@Override
|
||||
public String toString() {
|
||||
if (type instanceof ColumnInteger || type instanceof ColumnChar) {
|
||||
return "`" + name + "` " + type.toString().toLowerCase() + "(" + a + ")";
|
||||
return Strings.replaceWithOrder("`{0}` {1}({2})", name, type.toString().toLowerCase(), a);
|
||||
} else if (type instanceof ColumnFloat) {
|
||||
return "`" + name + "` " + type.toString().toLowerCase() + "(" + a + "," + b + ")";
|
||||
return Strings.replaceWithOrder("`{0}` {1}({2},{3})", name, type.toString().toLowerCase(), a, b);
|
||||
} else {
|
||||
return "`" + name + "` " + type.toString().toLowerCase();
|
||||
return Strings.replaceWithOrder("`{0}` {1}", name, type.toString().toLowerCase());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -537,7 +537,9 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static Object getHandle(org.bukkit.World world) {
|
||||
if (world == null) return null;
|
||||
if (world == null) {
|
||||
return null;
|
||||
}
|
||||
Object handle = null;
|
||||
try {
|
||||
handle = class_CraftWorld_getHandleMethod.invoke(world);
|
||||
@@ -548,7 +550,9 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static Object getHandle(org.bukkit.entity.Entity entity) {
|
||||
if (entity == null) return null;
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
Object handle = null;
|
||||
try {
|
||||
handle = class_CraftEntity_getHandleMethod.invoke(entity);
|
||||
@@ -559,7 +563,9 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static Object getHandle(org.bukkit.entity.LivingEntity entity) {
|
||||
if (entity == null) return null;
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
Object handle = null;
|
||||
try {
|
||||
handle = class_CraftLivingEntity_getHandleMethod.invoke(entity);
|
||||
@@ -608,7 +614,9 @@ public class NMSUtil18 {
|
||||
World sourceWorld = source.getWorld();
|
||||
for (Player player : players) {
|
||||
Location location = player.getLocation();
|
||||
if (!location.getWorld().equals(sourceWorld)) continue;
|
||||
if (!location.getWorld().equals(sourceWorld)) {
|
||||
continue;
|
||||
}
|
||||
if (location.distanceSquared(source) <= viewDistanceSquared) {
|
||||
sendPacket(player, packet);
|
||||
}
|
||||
@@ -645,11 +653,15 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static org.bukkit.entity.Entity getBukkitEntity(Object entity) {
|
||||
if (entity == null) return null;
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
Method getMethod = entity.getClass().getMethod("getBukkitEntity");
|
||||
Object bukkitEntity = getMethod.invoke(entity);
|
||||
if (!(bukkitEntity instanceof org.bukkit.entity.Entity)) return null;
|
||||
if (!(bukkitEntity instanceof org.bukkit.entity.Entity)) {
|
||||
return null;
|
||||
}
|
||||
return (org.bukkit.entity.Entity) bukkitEntity;
|
||||
} catch (Throwable ex) {
|
||||
ex.printStackTrace();
|
||||
@@ -679,7 +691,9 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static ItemStack getCopy(ItemStack stack) {
|
||||
if (stack == null) return null;
|
||||
if (stack == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
Object craft = getNMSCopy(stack);
|
||||
@@ -692,7 +706,9 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static ItemStack makeReal(ItemStack stack) {
|
||||
if (stack == null) return null;
|
||||
if (stack == null) {
|
||||
return null;
|
||||
}
|
||||
Object nmsStack = getHandle(stack);
|
||||
if (nmsStack == null) {
|
||||
stack = getCopy(stack);
|
||||
@@ -724,13 +740,19 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static Object getNode(ItemStack stack, String tag) {
|
||||
if (stack == null) return null;
|
||||
if (stack == null) {
|
||||
return null;
|
||||
}
|
||||
Object meta = null;
|
||||
try {
|
||||
Object craft = getHandle(stack);
|
||||
if (craft == null) return null;
|
||||
if (craft == null) {
|
||||
return null;
|
||||
}
|
||||
Object tagObject = getTag(craft);
|
||||
if (tagObject == null) return null;
|
||||
if (tagObject == null) {
|
||||
return null;
|
||||
}
|
||||
meta = class_NBTTagCompound_getMethod.invoke(tagObject, tag);
|
||||
} catch (Throwable ex) {
|
||||
ex.printStackTrace();
|
||||
@@ -739,7 +761,9 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static boolean containsNode(Object nbtBase, String tag) {
|
||||
if (nbtBase == null) return false;
|
||||
if (nbtBase == null) {
|
||||
return false;
|
||||
}
|
||||
Boolean result = false;
|
||||
try {
|
||||
result = (Boolean) class_NBTTagCompound_hasKeyMethod.invoke(nbtBase, tag);
|
||||
@@ -750,7 +774,9 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static Object getNode(Object nbtBase, String tag) {
|
||||
if (nbtBase == null) return null;
|
||||
if (nbtBase == null) {
|
||||
return null;
|
||||
}
|
||||
Object meta = null;
|
||||
try {
|
||||
meta = class_NBTTagCompound_getMethod.invoke(nbtBase, tag);
|
||||
@@ -761,7 +787,9 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static Object createNode(Object nbtBase, String tag) {
|
||||
if (nbtBase == null) return null;
|
||||
if (nbtBase == null) {
|
||||
return null;
|
||||
}
|
||||
Object meta = null;
|
||||
try {
|
||||
meta = class_NBTTagCompound_getCompoundMethod.invoke(nbtBase, tag);
|
||||
@@ -773,14 +801,20 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static Object createNode(ItemStack stack, String tag) {
|
||||
if (stack == null) return null;
|
||||
if (stack == null) {
|
||||
return null;
|
||||
}
|
||||
Object outputObject = getNode(stack, tag);
|
||||
if (outputObject == null) {
|
||||
try {
|
||||
Object craft = getHandle(stack);
|
||||
if (craft == null) return null;
|
||||
if (craft == null) {
|
||||
return null;
|
||||
}
|
||||
Object tagObject = getTag(craft);
|
||||
if (tagObject == null) return null;
|
||||
if (tagObject == null) {
|
||||
return null;
|
||||
}
|
||||
outputObject = class_NBTTagCompound.newInstance();
|
||||
class_NBTTagCompound_setMethod.invoke(tagObject, tag, outputObject);
|
||||
} catch (Throwable ex) {
|
||||
@@ -796,7 +830,9 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static String getMeta(Object node, String tag) {
|
||||
if (node == null || !class_NBTTagCompound.isInstance(node)) return null;
|
||||
if (node == null || !class_NBTTagCompound.isInstance(node)) {
|
||||
return null;
|
||||
}
|
||||
String meta = null;
|
||||
try {
|
||||
meta = (String) class_NBTTagCompound_getStringMethod.invoke(node, tag);
|
||||
@@ -807,7 +843,9 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static Byte getMetaByte(Object node, String tag) {
|
||||
if (node == null || !class_NBTTagCompound.isInstance(node)) return null;
|
||||
if (node == null || !class_NBTTagCompound.isInstance(node)) {
|
||||
return null;
|
||||
}
|
||||
Byte meta = null;
|
||||
try {
|
||||
meta = (Byte) class_NBTTagCompound_getByteMethod.invoke(node, tag);
|
||||
@@ -818,7 +856,9 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static Integer getMetaInt(Object node, String tag) {
|
||||
if (node == null || !class_NBTTagCompound.isInstance(node)) return null;
|
||||
if (node == null || !class_NBTTagCompound.isInstance(node)) {
|
||||
return null;
|
||||
}
|
||||
Integer meta = null;
|
||||
try {
|
||||
meta = (Integer) class_NBTTagCompound_getIntMethod.invoke(node, tag);
|
||||
@@ -829,7 +869,9 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static void setMeta(Object node, String tag, String value) {
|
||||
if (node == null || !class_NBTTagCompound.isInstance(node)) return;
|
||||
if (node == null || !class_NBTTagCompound.isInstance(node)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (value == null || value.length() == 0) {
|
||||
class_NBTTagCompound_removeMethod.invoke(node, tag);
|
||||
@@ -842,7 +884,9 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static void removeMeta(Object node, String tag) {
|
||||
if (node == null || !class_NBTTagCompound.isInstance(node)) return;
|
||||
if (node == null || !class_NBTTagCompound.isInstance(node)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
class_NBTTagCompound_removeMethod.invoke(node, tag);
|
||||
} catch (Throwable ex) {
|
||||
@@ -851,13 +895,19 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static void removeMeta(ItemStack stack, String tag) {
|
||||
if (stack == null) return;
|
||||
if (stack == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Object craft = getHandle(stack);
|
||||
if (craft == null) return;
|
||||
if (craft == null) {
|
||||
return;
|
||||
}
|
||||
Object tagObject = getTag(craft);
|
||||
if (tagObject == null) return;
|
||||
if (tagObject == null) {
|
||||
return;
|
||||
}
|
||||
removeMeta(tagObject, tag);
|
||||
} catch (Throwable ex) {
|
||||
ex.printStackTrace();
|
||||
@@ -865,13 +915,19 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static String getMeta(ItemStack stack, String tag) {
|
||||
if (stack == null) return null;
|
||||
if (stack == null) {
|
||||
return null;
|
||||
}
|
||||
String meta = null;
|
||||
try {
|
||||
Object craft = getHandle(stack);
|
||||
if (craft == null) return null;
|
||||
if (craft == null) {
|
||||
return null;
|
||||
}
|
||||
Object tagObject = getTag(craft);
|
||||
if (tagObject == null) return null;
|
||||
if (tagObject == null) {
|
||||
return null;
|
||||
}
|
||||
meta = (String) class_NBTTagCompound_getStringMethod.invoke(tagObject, tag);
|
||||
} catch (Throwable ex) {
|
||||
ex.printStackTrace();
|
||||
@@ -880,12 +936,18 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static void setMeta(ItemStack stack, String tag, String value) {
|
||||
if (stack == null) return;
|
||||
if (stack == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Object craft = getHandle(stack);
|
||||
if (craft == null) return;
|
||||
if (craft == null) {
|
||||
return;
|
||||
}
|
||||
Object tagObject = getTag(craft);
|
||||
if (tagObject == null) return;
|
||||
if (tagObject == null) {
|
||||
return;
|
||||
}
|
||||
class_NBTTagCompound_setStringMethod.invoke(tagObject, tag, value);
|
||||
} catch (Throwable ex) {
|
||||
ex.printStackTrace();
|
||||
@@ -893,13 +955,19 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static void addGlow(ItemStack stack) {
|
||||
if (stack == null) return;
|
||||
if (stack == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Object craft = getHandle(stack);
|
||||
if (craft == null) return;
|
||||
if (craft == null) {
|
||||
return;
|
||||
}
|
||||
Object tagObject = getTag(craft);
|
||||
if (tagObject == null) return;
|
||||
if (tagObject == null) {
|
||||
return;
|
||||
}
|
||||
final Object enchList = class_NBTTagList.newInstance();
|
||||
class_NBTTagCompound_setMethod.invoke(tagObject, "ench", enchList);
|
||||
|
||||
@@ -912,7 +980,9 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static void removeGlow(ItemStack stack) {
|
||||
if (stack == null) return;
|
||||
if (stack == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Collection<Enchantment> enchants = stack.getEnchantments().keySet();
|
||||
for (Enchantment enchant : enchants) {
|
||||
@@ -921,9 +991,13 @@ public class NMSUtil18 {
|
||||
|
||||
try {
|
||||
Object craft = getHandle(stack);
|
||||
if (craft == null) return;
|
||||
if (craft == null) {
|
||||
return;
|
||||
}
|
||||
Object tagObject = getTag(craft);
|
||||
if (tagObject == null) return;
|
||||
if (tagObject == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Testing Glow API based on ItemMetadata storage
|
||||
Object bukkitData = getNode(stack, "bukkit");
|
||||
@@ -936,13 +1010,19 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static void makeUnbreakable(ItemStack stack) {
|
||||
if (stack == null) return;
|
||||
if (stack == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Object craft = getHandle(stack);
|
||||
if (craft == null) return;
|
||||
if (craft == null) {
|
||||
return;
|
||||
}
|
||||
Object tagObject = getTag(craft);
|
||||
if (tagObject == null) return;
|
||||
if (tagObject == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object unbreakableFlag = null;
|
||||
if (class_NBTTagByte_constructor != null) {
|
||||
@@ -961,13 +1041,19 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static void hideFlags(ItemStack stack, byte flags) {
|
||||
if (stack == null) return;
|
||||
if (stack == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Object craft = getHandle(stack);
|
||||
if (craft == null) return;
|
||||
if (craft == null) {
|
||||
return;
|
||||
}
|
||||
Object tagObject = getTag(craft);
|
||||
if (tagObject == null) return;
|
||||
if (tagObject == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object hideFlag = null;
|
||||
if (class_NBTTagByte_constructor != null) {
|
||||
@@ -983,10 +1069,14 @@ public class NMSUtil18 {
|
||||
|
||||
public static boolean createExplosion(Entity entity, World world, double x, double y, double z, float power, boolean setFire, boolean breakBlocks) {
|
||||
boolean result = false;
|
||||
if (world == null) return false;
|
||||
if (world == null) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Object worldHandle = getHandle(world);
|
||||
if (worldHandle == null) return false;
|
||||
if (worldHandle == null) {
|
||||
return false;
|
||||
}
|
||||
Object entityHandle = entity == null ? null : getHandle(entity);
|
||||
|
||||
Object explosion = class_World_explodeMethod.invoke(worldHandle, entityHandle, x, y, z, power, setFire, breakBlocks);
|
||||
@@ -1055,7 +1145,9 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static Object setStringList(Object nbtBase, String tag, Collection<String> values) {
|
||||
if (nbtBase == null) return null;
|
||||
if (nbtBase == null) {
|
||||
return null;
|
||||
}
|
||||
Object listMeta = null;
|
||||
try {
|
||||
listMeta = class_NBTTagList.newInstance();
|
||||
@@ -1074,7 +1166,9 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static ItemStack getItem(Object itemTag) {
|
||||
if (itemTag == null) return null;
|
||||
if (itemTag == null) {
|
||||
return null;
|
||||
}
|
||||
ItemStack item = null;
|
||||
try {
|
||||
Object nmsStack = class_ItemStack_createStackMethod.invoke(null, itemTag);
|
||||
@@ -1134,10 +1228,14 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static void clearItems(Location location) {
|
||||
if (location == null) return;
|
||||
if (location == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
World world = location.getWorld();
|
||||
if (world == null) return;
|
||||
if (world == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ());
|
||||
if (tileEntity != null) {
|
||||
@@ -1157,13 +1255,19 @@ public class NMSUtil18 {
|
||||
}
|
||||
|
||||
public static void setTileEntityData(Location location, Object data) {
|
||||
if (location == null || data == null) return;
|
||||
if (location == null || data == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
World world = location.getWorld();
|
||||
if (world == null) return;
|
||||
if (world == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ());
|
||||
if (tileEntity == null) return;
|
||||
if (tileEntity == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
class_NBTTagCompound_setIntMethod.invoke(data, "x", location.getBlockX());
|
||||
class_NBTTagCompound_setIntMethod.invoke(data, "y", location.getBlockY());
|
||||
|
||||
@@ -678,18 +678,24 @@ public class NMSUtil19 {
|
||||
try {
|
||||
// 1.12, same as 1.10
|
||||
class_EntityArmorStand_disabledSlotsField = class_EntityArmorStand.getDeclaredField("bB");
|
||||
if (class_EntityArmorStand_disabledSlotsField.getType() != Integer.TYPE) throw new Exception("Looks like 1.11, maybe");
|
||||
if (class_EntityArmorStand_disabledSlotsField.getType() != Integer.TYPE) {
|
||||
throw new Exception("Looks like 1.11, maybe");
|
||||
}
|
||||
} catch (Throwable not12) {
|
||||
try {
|
||||
// 1.11
|
||||
class_EntityArmorStand_disabledSlotsField = class_EntityArmorStand.getDeclaredField("bA");
|
||||
if (class_EntityArmorStand_disabledSlotsField.getType() != Integer.TYPE) throw new Exception("Looks like 1.10");
|
||||
if (class_EntityArmorStand_disabledSlotsField.getType() != Integer.TYPE) {
|
||||
throw new Exception("Looks like 1.10");
|
||||
}
|
||||
} catch (Throwable ignore) {
|
||||
// 1.10 and earlier
|
||||
legacy = true;
|
||||
try {
|
||||
class_EntityArmorStand_disabledSlotsField = class_EntityArmorStand.getDeclaredField("bB");
|
||||
if (class_EntityArmorStand_disabledSlotsField.getType() != Integer.TYPE) throw new Exception("Looks like 1.9");
|
||||
if (class_EntityArmorStand_disabledSlotsField.getType() != Integer.TYPE) {
|
||||
throw new Exception("Looks like 1.9");
|
||||
}
|
||||
} catch (Throwable ignore2) {
|
||||
try {
|
||||
// 1.9.4
|
||||
@@ -742,7 +748,9 @@ public class NMSUtil19 {
|
||||
try {
|
||||
// 1.10 and 1.11
|
||||
class_PlayerConnection_floatCountField = class_PlayerConnection.getDeclaredField("C");
|
||||
if (class_PlayerConnection_floatCountField.getType() != Integer.TYPE) throw new Exception("Looks like 1.9");
|
||||
if (class_PlayerConnection_floatCountField.getType() != Integer.TYPE) {
|
||||
throw new Exception("Looks like 1.9");
|
||||
}
|
||||
class_PlayerConnection_floatCountField.setAccessible(true);
|
||||
} catch (Throwable ignore) {
|
||||
// 1.9 and earlier
|
||||
@@ -954,7 +962,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static Object getHandle(org.bukkit.World world) {
|
||||
if (world == null) return null;
|
||||
if (world == null) {
|
||||
return null;
|
||||
}
|
||||
Object handle = null;
|
||||
try {
|
||||
handle = class_CraftWorld_getHandleMethod.invoke(world);
|
||||
@@ -965,7 +975,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static Object getHandle(org.bukkit.entity.Entity entity) {
|
||||
if (entity == null) return null;
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
Object handle = null;
|
||||
try {
|
||||
handle = class_CraftEntity_getHandleMethod.invoke(entity);
|
||||
@@ -976,7 +988,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static Object getHandle(org.bukkit.entity.LivingEntity entity) {
|
||||
if (entity == null) return null;
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
Object handle = null;
|
||||
try {
|
||||
handle = class_CraftLivingEntity_getHandleMethod.invoke(entity);
|
||||
@@ -1025,7 +1039,9 @@ public class NMSUtil19 {
|
||||
World sourceWorld = source.getWorld();
|
||||
for (Player player : players) {
|
||||
Location location = player.getLocation();
|
||||
if (!location.getWorld().equals(sourceWorld)) continue;
|
||||
if (!location.getWorld().equals(sourceWorld)) {
|
||||
continue;
|
||||
}
|
||||
if (location.distanceSquared(source) <= viewDistanceSquared) {
|
||||
sendPacket(player, packet);
|
||||
}
|
||||
@@ -1064,11 +1080,15 @@ public class NMSUtil19 {
|
||||
|
||||
public static org.bukkit.entity.Entity getBukkitEntity(Object entity)
|
||||
{
|
||||
if (entity == null) return null;
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
Method getMethod = entity.getClass().getMethod("getBukkitEntity");
|
||||
Object bukkitEntity = getMethod.invoke(entity);
|
||||
if (!(bukkitEntity instanceof org.bukkit.entity.Entity)) return null;
|
||||
if (!(bukkitEntity instanceof org.bukkit.entity.Entity)) {
|
||||
return null;
|
||||
}
|
||||
return (org.bukkit.entity.Entity)bukkitEntity;
|
||||
} catch (Throwable ex) {
|
||||
ex.printStackTrace();
|
||||
@@ -1098,7 +1118,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static ItemStack getCopy(ItemStack stack) {
|
||||
if (stack == null) return null;
|
||||
if (stack == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
Object craft = getNMSCopy(stack);
|
||||
@@ -1111,7 +1133,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static ItemStack makeReal(ItemStack stack) {
|
||||
if (stack == null) return null;
|
||||
if (stack == null) {
|
||||
return null;
|
||||
}
|
||||
Object nmsStack = getHandle(stack);
|
||||
if (nmsStack == null) {
|
||||
stack = getCopy(stack);
|
||||
@@ -1146,7 +1170,9 @@ public class NMSUtil19 {
|
||||
Object tag = null;
|
||||
try {
|
||||
Object mcItemStack = getHandle(itemStack);
|
||||
if (mcItemStack == null) return null;
|
||||
if (mcItemStack == null) {
|
||||
return null;
|
||||
}
|
||||
tag = class_ItemStack_tagField.get(mcItemStack);
|
||||
} catch (Throwable ex) {
|
||||
ex.printStackTrace();
|
||||
@@ -1155,13 +1181,19 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static Object getNode(ItemStack stack, String tag) {
|
||||
if (NMSUtil19.isEmpty(stack)) return null;
|
||||
if (NMSUtil19.isEmpty(stack)) {
|
||||
return null;
|
||||
}
|
||||
Object meta = null;
|
||||
try {
|
||||
Object craft = getHandle(stack);
|
||||
if (craft == null) return null;
|
||||
if (craft == null) {
|
||||
return null;
|
||||
}
|
||||
Object tagObject = getTag(craft);
|
||||
if (tagObject == null) return null;
|
||||
if (tagObject == null) {
|
||||
return null;
|
||||
}
|
||||
meta = class_NBTTagCompound_getMethod.invoke(tagObject, tag);
|
||||
} catch (Throwable ex) {
|
||||
ex.printStackTrace();
|
||||
@@ -1170,7 +1202,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static boolean containsNode(Object nbtBase, String tag) {
|
||||
if (nbtBase == null) return false;
|
||||
if (nbtBase == null) {
|
||||
return false;
|
||||
}
|
||||
Boolean result = false;
|
||||
try {
|
||||
result = (Boolean)class_NBTTagCompound_hasKeyMethod.invoke(nbtBase, tag);
|
||||
@@ -1181,7 +1215,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static Object getNode(Object nbtBase, String tag) {
|
||||
if (nbtBase == null) return null;
|
||||
if (nbtBase == null) {
|
||||
return null;
|
||||
}
|
||||
Object meta = null;
|
||||
try {
|
||||
meta = class_NBTTagCompound_getMethod.invoke(nbtBase, tag);
|
||||
@@ -1192,7 +1228,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static Object createNode(Object nbtBase, String tag) {
|
||||
if (nbtBase == null) return null;
|
||||
if (nbtBase == null) {
|
||||
return null;
|
||||
}
|
||||
Object meta = null;
|
||||
try {
|
||||
meta = class_NBTTagCompound_getCompoundMethod.invoke(nbtBase, tag);
|
||||
@@ -1204,12 +1242,16 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static Object createNode(ItemStack stack, String tag) {
|
||||
if (NMSUtil19.isEmpty(stack)) return null;
|
||||
if (NMSUtil19.isEmpty(stack)) {
|
||||
return null;
|
||||
}
|
||||
Object outputObject = getNode(stack, tag);
|
||||
if (outputObject == null) {
|
||||
try {
|
||||
Object craft = getHandle(stack);
|
||||
if (craft == null) return null;
|
||||
if (craft == null) {
|
||||
return null;
|
||||
}
|
||||
Object tagObject = getTag(craft);
|
||||
if (tagObject == null) {
|
||||
tagObject = class_NBTTagCompound.newInstance();
|
||||
@@ -1230,7 +1272,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static String getMetaString(Object node, String tag) {
|
||||
if (node == null || !class_NBTTagCompound.isInstance(node)) return null;
|
||||
if (node == null || !class_NBTTagCompound.isInstance(node)) {
|
||||
return null;
|
||||
}
|
||||
String meta = null;
|
||||
try {
|
||||
meta = (String)class_NBTTagCompound_getStringMethod.invoke(node, tag);
|
||||
@@ -1241,7 +1285,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static String getMeta(Object node, String tag) {
|
||||
if (node == null || !class_NBTTagCompound.isInstance(node)) return null;
|
||||
if (node == null || !class_NBTTagCompound.isInstance(node)) {
|
||||
return null;
|
||||
}
|
||||
String meta = null;
|
||||
try {
|
||||
meta = (String)class_NBTTagCompound_getStringMethod.invoke(node, tag);
|
||||
@@ -1252,7 +1298,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static Byte getMetaByte(Object node, String tag) {
|
||||
if (node == null || !class_NBTTagCompound.isInstance(node)) return null;
|
||||
if (node == null || !class_NBTTagCompound.isInstance(node)) {
|
||||
return null;
|
||||
}
|
||||
Byte meta = null;
|
||||
try {
|
||||
meta = (Byte)class_NBTTagCompound_getByteMethod.invoke(node, tag);
|
||||
@@ -1263,7 +1311,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static Integer getMetaInt(Object node, String tag) {
|
||||
if (node == null || !class_NBTTagCompound.isInstance(node)) return null;
|
||||
if (node == null || !class_NBTTagCompound.isInstance(node)) {
|
||||
return null;
|
||||
}
|
||||
Integer meta = null;
|
||||
try {
|
||||
meta = (Integer)class_NBTTagCompound_getIntMethod.invoke(node, tag);
|
||||
@@ -1274,7 +1324,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static Boolean getMetaBoolean(Object node, String tag) {
|
||||
if (node == null || !class_NBTTagCompound.isInstance(node)) return null;
|
||||
if (node == null || !class_NBTTagCompound.isInstance(node)) {
|
||||
return null;
|
||||
}
|
||||
Boolean meta = null;
|
||||
try {
|
||||
meta = (Boolean)class_NBTTagCompound_getBooleanMethod.invoke(node, tag);
|
||||
@@ -1285,7 +1337,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static void setMeta(Object node, String tag, String value) {
|
||||
if (node == null|| !class_NBTTagCompound.isInstance(node)) return;
|
||||
if (node == null|| !class_NBTTagCompound.isInstance(node)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (value == null || value.length() == 0) {
|
||||
class_NBTTagCompound_removeMethod.invoke(node, tag);
|
||||
@@ -1298,7 +1352,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static void setMetaLong(Object node, String tag, long value) {
|
||||
if (node == null|| !class_NBTTagCompound.isInstance(node)) return;
|
||||
if (node == null|| !class_NBTTagCompound.isInstance(node)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
class_NBTTagCompound_setLongMethod.invoke(node, tag, value);
|
||||
} catch (Throwable ex) {
|
||||
@@ -1307,7 +1363,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static void setMetaBoolean(Object node, String tag, boolean value) {
|
||||
if (node == null|| !class_NBTTagCompound.isInstance(node)) return;
|
||||
if (node == null|| !class_NBTTagCompound.isInstance(node)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
class_NBTTagCompound_setBooleanMethod.invoke(node, tag, value);
|
||||
} catch (Throwable ex) {
|
||||
@@ -1316,7 +1374,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static void setMetaDouble(Object node, String tag, double value) {
|
||||
if (node == null|| !class_NBTTagCompound.isInstance(node)) return;
|
||||
if (node == null|| !class_NBTTagCompound.isInstance(node)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
class_NBTTagCompound_setDoubleMethod.invoke(node, tag, value);
|
||||
} catch (Throwable ex) {
|
||||
@@ -1325,7 +1385,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static void setMetaInt(Object node, String tag, int value) {
|
||||
if (node == null|| !class_NBTTagCompound.isInstance(node)) return;
|
||||
if (node == null|| !class_NBTTagCompound.isInstance(node)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
class_NBTTagCompound_setIntMethod.invoke(node, tag, value);
|
||||
} catch (Throwable ex) {
|
||||
@@ -1334,7 +1396,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static void removeMeta(Object node, String tag) {
|
||||
if (node == null|| !class_NBTTagCompound.isInstance(node)) return;
|
||||
if (node == null|| !class_NBTTagCompound.isInstance(node)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
class_NBTTagCompound_removeMethod.invoke(node, tag);
|
||||
} catch (Throwable ex) {
|
||||
@@ -1343,13 +1407,19 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static void removeMeta(ItemStack stack, String tag) {
|
||||
if (NMSUtil19.isEmpty(stack)) return;
|
||||
if (NMSUtil19.isEmpty(stack)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Object craft = getHandle(stack);
|
||||
if (craft == null) return;
|
||||
if (craft == null) {
|
||||
return;
|
||||
}
|
||||
Object tagObject = getTag(craft);
|
||||
if (tagObject == null) return;
|
||||
if (tagObject == null) {
|
||||
return;
|
||||
}
|
||||
removeMeta(tagObject, tag);
|
||||
} catch (Throwable ex) {
|
||||
ex.printStackTrace();
|
||||
@@ -1357,7 +1427,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static void setMetaNode(Object node, String tag, Object child) {
|
||||
if (node == null || !class_NBTTagCompound.isInstance(node)) return;
|
||||
if (node == null || !class_NBTTagCompound.isInstance(node)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (child == null) {
|
||||
class_NBTTagCompound_removeMethod.invoke(node, tag);
|
||||
@@ -1370,12 +1442,18 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static boolean setMetaNode(ItemStack stack, String tag, Object child) {
|
||||
if (NMSUtil19.isEmpty(stack)) return false;
|
||||
if (NMSUtil19.isEmpty(stack)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Object craft = getHandle(stack);
|
||||
if (craft == null) return false;
|
||||
if (craft == null) {
|
||||
return false;
|
||||
}
|
||||
Object node = getTag(craft);
|
||||
if (node == null) return false;
|
||||
if (node == null) {
|
||||
return false;
|
||||
}
|
||||
if (child == null) {
|
||||
class_NBTTagCompound_removeMethod.invoke(node, tag);
|
||||
} else {
|
||||
@@ -1390,13 +1468,19 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static String getMetaString(ItemStack stack, String tag) {
|
||||
if (NMSUtil19.isEmpty(stack)) return null;
|
||||
if (NMSUtil19.isEmpty(stack)) {
|
||||
return null;
|
||||
}
|
||||
String meta = null;
|
||||
try {
|
||||
Object craft = getHandle(stack);
|
||||
if (craft == null) return null;
|
||||
if (craft == null) {
|
||||
return null;
|
||||
}
|
||||
Object tagObject = getTag(craft);
|
||||
if (tagObject == null) return null;
|
||||
if (tagObject == null) {
|
||||
return null;
|
||||
}
|
||||
meta = (String)class_NBTTagCompound_getStringMethod.invoke(tagObject, tag);
|
||||
} catch (Throwable ex) {
|
||||
ex.printStackTrace();
|
||||
@@ -1405,12 +1489,18 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static void setMeta(ItemStack stack, String tag, String value) {
|
||||
if (NMSUtil19.isEmpty(stack)) return;
|
||||
if (NMSUtil19.isEmpty(stack)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Object craft = getHandle(stack);
|
||||
if (craft == null) return;
|
||||
if (craft == null) {
|
||||
return;
|
||||
}
|
||||
Object tagObject = getTag(craft);
|
||||
if (tagObject == null) return;
|
||||
if (tagObject == null) {
|
||||
return;
|
||||
}
|
||||
class_NBTTagCompound_setStringMethod.invoke(tagObject, tag, value);
|
||||
} catch (Throwable ex) {
|
||||
ex.printStackTrace();
|
||||
@@ -1418,12 +1508,18 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static void setMetaBoolean(ItemStack stack, String tag, boolean value) {
|
||||
if (NMSUtil19.isEmpty(stack)) return;
|
||||
if (NMSUtil19.isEmpty(stack)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Object craft = getHandle(stack);
|
||||
if (craft == null) return;
|
||||
if (craft == null) {
|
||||
return;
|
||||
}
|
||||
Object tagObject = getTag(craft);
|
||||
if (tagObject == null) return;
|
||||
if (tagObject == null) {
|
||||
return;
|
||||
}
|
||||
setMetaBoolean(tagObject, tag, value);
|
||||
} catch (Throwable ex) {
|
||||
ex.printStackTrace();
|
||||
@@ -1431,13 +1527,19 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static boolean getMetaBoolean(ItemStack stack, String tag, boolean defaultValue) {
|
||||
if (NMSUtil19.isEmpty(stack)) return defaultValue;
|
||||
if (NMSUtil19.isEmpty(stack)) {
|
||||
return defaultValue;
|
||||
}
|
||||
boolean result = defaultValue;
|
||||
try {
|
||||
Object craft = getHandle(stack);
|
||||
if (craft == null) return defaultValue;
|
||||
if (craft == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
Object tagObject = getTag(craft);
|
||||
if (tagObject == null) return defaultValue;
|
||||
if (tagObject == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
Boolean value = getMetaBoolean(tagObject, tag);
|
||||
result = value == null ? defaultValue : value;
|
||||
} catch (Throwable ex) {
|
||||
@@ -1447,7 +1549,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static void addGlow(ItemStack stack) {
|
||||
if (NMSUtil19.isEmpty(stack)) return;
|
||||
if (NMSUtil19.isEmpty(stack)) {
|
||||
return;
|
||||
}
|
||||
|
||||
ItemMeta meta = stack.getItemMeta();
|
||||
meta.addEnchant(Enchantment.LUCK, 1, true);
|
||||
@@ -1455,7 +1559,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static void removeGlow(ItemStack stack) {
|
||||
if (NMSUtil19.isEmpty(stack)) return;
|
||||
if (NMSUtil19.isEmpty(stack)) {
|
||||
return;
|
||||
}
|
||||
|
||||
ItemMeta meta = stack.getItemMeta();
|
||||
if (meta.hasEnchant(Enchantment.LUCK)) {
|
||||
@@ -1465,13 +1571,19 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static boolean isUnbreakable(ItemStack stack) {
|
||||
if (NMSUtil19.isEmpty(stack)) return false;
|
||||
if (NMSUtil19.isEmpty(stack)) {
|
||||
return false;
|
||||
}
|
||||
Boolean unbreakableFlag = null;
|
||||
try {
|
||||
Object craft = getHandle(stack);
|
||||
if (craft == null) return false;
|
||||
if (craft == null) {
|
||||
return false;
|
||||
}
|
||||
Object tagObject = getTag(craft);
|
||||
if (tagObject == null) return false;
|
||||
if (tagObject == null) {
|
||||
return false;
|
||||
}
|
||||
unbreakableFlag = getMetaBoolean(tagObject, "Unbreakable");
|
||||
} catch (Throwable ignored) {
|
||||
|
||||
@@ -1481,13 +1593,19 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static void makeUnbreakable(ItemStack stack) {
|
||||
if (NMSUtil19.isEmpty(stack)) return;
|
||||
if (NMSUtil19.isEmpty(stack)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Object craft = getHandle(stack);
|
||||
if (craft == null) return;
|
||||
if (craft == null) {
|
||||
return;
|
||||
}
|
||||
Object tagObject = getTag(craft);
|
||||
if (tagObject == null) return;
|
||||
if (tagObject == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object unbreakableFlag = null;
|
||||
unbreakableFlag = class_NBTTagByte_constructor.newInstance((byte) 1);
|
||||
@@ -1502,13 +1620,19 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static void hideFlags(ItemStack stack, byte flags) {
|
||||
if (NMSUtil19.isEmpty(stack)) return;
|
||||
if (NMSUtil19.isEmpty(stack)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Object craft = getHandle(stack);
|
||||
if (craft == null) return;
|
||||
if (craft == null) {
|
||||
return;
|
||||
}
|
||||
Object tagObject = getTag(craft);
|
||||
if (tagObject == null) return;
|
||||
if (tagObject == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object hideFlag = null;
|
||||
hideFlag = class_NBTTagByte_constructor.newInstance(flags);
|
||||
@@ -1520,10 +1644,14 @@ public class NMSUtil19 {
|
||||
|
||||
public static boolean createExplosion(Entity entity, World world, double x, double y, double z, float power, boolean setFire, boolean breakBlocks) {
|
||||
boolean result = false;
|
||||
if (world == null) return false;
|
||||
if (world == null) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Object worldHandle = getHandle(world);
|
||||
if (worldHandle == null) return false;
|
||||
if (worldHandle == null) {
|
||||
return false;
|
||||
}
|
||||
Object entityHandle = entity == null ? null : getHandle(entity);
|
||||
|
||||
Object explosion = class_World_explodeMethod.invoke(worldHandle, entityHandle, x, y, z, power, setFire, breakBlocks);
|
||||
@@ -1593,7 +1721,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static Object setStringList(Object nbtBase, String tag, Collection<String> values) {
|
||||
if (nbtBase == null) return null;
|
||||
if (nbtBase == null) {
|
||||
return null;
|
||||
}
|
||||
Object listMeta = null;
|
||||
try {
|
||||
listMeta = class_NBTTagList.newInstance();
|
||||
@@ -1612,7 +1742,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static ItemStack getItem(Object itemTag) {
|
||||
if (itemTag == null) return null;
|
||||
if (itemTag == null) {
|
||||
return null;
|
||||
}
|
||||
ItemStack item = null;
|
||||
try {
|
||||
Object nmsStack = null;
|
||||
@@ -1651,7 +1783,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static Object getTileEntityData(Location location) {
|
||||
if (class_CraftWorld_getTileEntityAtMethod == null || class_TileEntity_saveMethod == null) return null;
|
||||
if (class_CraftWorld_getTileEntityAtMethod == null || class_TileEntity_saveMethod == null) {
|
||||
return null;
|
||||
}
|
||||
Object data = null;
|
||||
try {
|
||||
World world = location.getWorld();
|
||||
@@ -1667,7 +1801,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static Object getTileEntity(Location location) {
|
||||
if (class_CraftWorld_getTileEntityAtMethod == null) return null;
|
||||
if (class_CraftWorld_getTileEntityAtMethod == null) {
|
||||
return null;
|
||||
}
|
||||
Object tileEntity = null;
|
||||
try {
|
||||
World world = location.getWorld();
|
||||
@@ -1679,11 +1815,17 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static void clearItems(Location location) {
|
||||
if (class_TileEntity_loadMethod == null || class_TileEntity_updateMethod == null || class_CraftWorld_getTileEntityAtMethod == null || class_TileEntity_saveMethod == null) return;
|
||||
if (location == null) return;
|
||||
if (class_TileEntity_loadMethod == null || class_TileEntity_updateMethod == null || class_CraftWorld_getTileEntityAtMethod == null || class_TileEntity_saveMethod == null) {
|
||||
return;
|
||||
}
|
||||
if (location == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
World world = location.getWorld();
|
||||
if (world == null) return;
|
||||
if (world == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ());
|
||||
if (tileEntity != null) {
|
||||
@@ -1704,15 +1846,23 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static void setTileEntityData(Location location, Object data) {
|
||||
if (class_TileEntity_loadMethod == null || class_TileEntity_updateMethod == null || class_CraftWorld_getTileEntityAtMethod == null) return;
|
||||
if (class_TileEntity_loadMethod == null || class_TileEntity_updateMethod == null || class_CraftWorld_getTileEntityAtMethod == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (location == null || data == null) return;
|
||||
if (location == null || data == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
World world = location.getWorld();
|
||||
if (world == null) return;
|
||||
if (world == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object tileEntity = class_CraftWorld_getTileEntityAtMethod.invoke(world, location.getBlockX(), location.getBlockY(), location.getBlockZ());
|
||||
if (tileEntity == null) return;
|
||||
if (tileEntity == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
class_NBTTagCompound_setIntMethod.invoke(data, "x", location.getBlockX());
|
||||
class_NBTTagCompound_setIntMethod.invoke(data, "y", location.getBlockY());
|
||||
@@ -1726,7 +1876,9 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static Vector getPosition(Object entityData, String tag) {
|
||||
if (class_NBTTagList_getDoubleMethod == null) return null;
|
||||
if (class_NBTTagList_getDoubleMethod == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
Object posList = class_NBTTagCompound_getListMethod.invoke(entityData, tag, NBT_TYPE_DOUBLE);
|
||||
Double x = (Double)class_NBTTagList_getDoubleMethod.invoke(posList, 0);
|
||||
@@ -1777,7 +1929,9 @@ public class NMSUtil19 {
|
||||
|
||||
public static Map<String, Object> getMap(ConfigurationSection section)
|
||||
{
|
||||
if (section == null) return null;
|
||||
if (section == null) {
|
||||
return null;
|
||||
}
|
||||
if (section instanceof MemorySection)
|
||||
{
|
||||
try {
|
||||
@@ -1801,11 +1955,17 @@ public class NMSUtil19 {
|
||||
}
|
||||
|
||||
public static boolean isEmpty(ItemStack itemStack) {
|
||||
if (itemStack == null || itemStack.getType() == Material.AIR) return true;
|
||||
if (class_ItemStack_isEmptyMethod == null) return false;
|
||||
if (itemStack == null || itemStack.getType() == Material.AIR) {
|
||||
return true;
|
||||
}
|
||||
if (class_ItemStack_isEmptyMethod == null) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Object handle = getHandle(itemStack);
|
||||
if (handle == null) return false;
|
||||
if (handle == null) {
|
||||
return false;
|
||||
}
|
||||
return (Boolean)class_ItemStack_isEmptyMethod.invoke(handle);
|
||||
} catch (Throwable ex) {
|
||||
ex.printStackTrace();
|
||||
|
||||
@@ -142,7 +142,7 @@ public class NMSUtils {
|
||||
}
|
||||
|
||||
public static Field getFieldWithException(Class<?> clazz, String name) throws Exception {
|
||||
for (Field field : clazz.getDeclaredFields())
|
||||
for (Field field : clazz.getDeclaredFields()) {
|
||||
if (field.getName().equals(name)) {
|
||||
field.setAccessible(true);
|
||||
Field modifiersField = Field.class.getDeclaredField("modifiers");
|
||||
@@ -152,7 +152,8 @@ public class NMSUtils {
|
||||
modifiersField.setInt(field, modifiers);
|
||||
return field;
|
||||
}
|
||||
for (Field field : clazz.getFields())
|
||||
}
|
||||
for (Field field : clazz.getFields()) {
|
||||
if (field.getName().equals(name)) {
|
||||
field.setAccessible(true);
|
||||
Field modifiersField = Field.class.getDeclaredField("modifiers");
|
||||
@@ -162,6 +163,7 @@ public class NMSUtils {
|
||||
modifiersField.setInt(field, modifiers);
|
||||
return field;
|
||||
}
|
||||
}
|
||||
throw new Exception("Field Not Found");
|
||||
}
|
||||
|
||||
@@ -194,7 +196,7 @@ public class NMSUtils {
|
||||
}
|
||||
|
||||
public static Field getFieldOfTypeWithException(Class<?> clazz, Class<?> type, String name) throws Exception {
|
||||
for (Field field : clazz.getDeclaredFields())
|
||||
for (Field field : clazz.getDeclaredFields()) {
|
||||
if (field.getName().equals(name) && field.getType().equals(type)) {
|
||||
field.setAccessible(true);
|
||||
Field modifiersField = Field.class.getDeclaredField("modifiers");
|
||||
@@ -204,7 +206,8 @@ public class NMSUtils {
|
||||
modifiersField.setInt(field, modifiers);
|
||||
return field;
|
||||
}
|
||||
for (Field field : clazz.getFields())
|
||||
}
|
||||
for (Field field : clazz.getFields()) {
|
||||
if (field.getName().equals(name) && field.getType().equals(type)) {
|
||||
field.setAccessible(true);
|
||||
Field modifiersField = Field.class.getDeclaredField("modifiers");
|
||||
@@ -214,6 +217,7 @@ public class NMSUtils {
|
||||
modifiersField.setInt(field, modifiers);
|
||||
return field;
|
||||
}
|
||||
}
|
||||
throw new Exception("Field Not Found");
|
||||
}
|
||||
|
||||
@@ -252,10 +256,11 @@ public class NMSUtils {
|
||||
|
||||
public static Field getLastFieldOfTypeWithException(Class<?> clazz, Class<?> type) throws Exception {
|
||||
Field field = null;
|
||||
for (Field f : clazz.getDeclaredFields())
|
||||
for (Field f : clazz.getDeclaredFields()) {
|
||||
if (f.getType().equals(type)) {
|
||||
field = f;
|
||||
}
|
||||
}
|
||||
if (field == null) {
|
||||
throw new Exception("Field Not Found");
|
||||
}
|
||||
@@ -278,16 +283,18 @@ public class NMSUtils {
|
||||
}
|
||||
|
||||
public static Method getMethodWithException(Class<?> clazz, String name, Class<?>... args) throws Exception {
|
||||
for (Method m : clazz.getDeclaredMethods())
|
||||
for (Method m : clazz.getDeclaredMethods()) {
|
||||
if (m.getName().equals(name) && (args.length == 0 && m.getParameterTypes().length == 0 || ClassListEqual(args, m.getParameterTypes()))) {
|
||||
m.setAccessible(true);
|
||||
return m;
|
||||
}
|
||||
for (Method m : clazz.getMethods())
|
||||
}
|
||||
for (Method m : clazz.getMethods()) {
|
||||
if (m.getName().equals(name) && (args.length == 0 && m.getParameterTypes().length == 0 || ClassListEqual(args, m.getParameterTypes()))) {
|
||||
m.setAccessible(true);
|
||||
return m;
|
||||
}
|
||||
}
|
||||
throw new Exception("Method Not Found");
|
||||
}
|
||||
|
||||
@@ -300,18 +307,23 @@ public class NMSUtils {
|
||||
}
|
||||
|
||||
public static boolean ClassListEqual(Class<?>[] l1, Class<?>[] l2) {
|
||||
if (l1.length != l2.length)
|
||||
if (l1.length != l2.length) {
|
||||
return false;
|
||||
for (int i = 0; i < l1.length; i++)
|
||||
if (l1[i] != l2[i])
|
||||
}
|
||||
for (int i = 0; i < l1.length; i++) {
|
||||
if (l1[i] != l2[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static Class<?> getInnerClassWithException(Class<?> c, String className) throws Exception {
|
||||
for (Class<?> cl : c.getDeclaredClasses())
|
||||
if (cl.getSimpleName().equals(className))
|
||||
for (Class<?> cl : c.getDeclaredClasses()) {
|
||||
if (cl.getSimpleName().equals(className)) {
|
||||
return cl;
|
||||
}
|
||||
}
|
||||
throw new Exception("Inner Class Not Found");
|
||||
}
|
||||
|
||||
@@ -333,16 +345,18 @@ public class NMSUtils {
|
||||
}
|
||||
|
||||
public static Constructor<?> getConstructor(Class<?> clazz, Class<?>... args) throws Exception {
|
||||
for (Constructor<?> c : clazz.getDeclaredConstructors())
|
||||
for (Constructor<?> c : clazz.getDeclaredConstructors()) {
|
||||
if (args.length == 0 && c.getParameterTypes().length == 0 || ClassListEqual(args, c.getParameterTypes())) {
|
||||
c.setAccessible(true);
|
||||
return c;
|
||||
}
|
||||
for (Constructor<?> c : clazz.getConstructors())
|
||||
}
|
||||
for (Constructor<?> c : clazz.getConstructors()) {
|
||||
if (args.length == 0 && c.getParameterTypes().length == 0 || ClassListEqual(args, c.getParameterTypes())) {
|
||||
c.setAccessible(true);
|
||||
return c;
|
||||
}
|
||||
}
|
||||
throw new Exception("Constructor Not Found");
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -97,7 +97,7 @@ public class _1710ItemUtils implements IDabItemUtils{
|
||||
}
|
||||
}
|
||||
|
||||
public Method gin = NMSUtils.getMethodSilent(ni, "getName");
|
||||
public Method gin = NMSUtils.getMethodSilent(ni, "getLabel");
|
||||
|
||||
@Override
|
||||
public String getItemName(ItemStack is){
|
||||
@@ -675,8 +675,9 @@ public class _1710ItemUtils implements IDabItemUtils{
|
||||
ret = nbtiad.get(nbt);
|
||||
break;
|
||||
}
|
||||
if(ret == null)
|
||||
return null;
|
||||
if(ret == null) {
|
||||
return null;
|
||||
}
|
||||
return new JSONArray(new Object[]{ i, ret });
|
||||
}
|
||||
|
||||
@@ -1001,8 +1002,9 @@ public class _1710ItemUtils implements IDabItemUtils{
|
||||
public boolean compareBaseTag(Object tag, Object tag1) throws Exception{
|
||||
int i = ((byte)gti.invoke(tag));
|
||||
int i1 = ((byte)gti.invoke(tag1));
|
||||
if(i != i1)
|
||||
return false;
|
||||
if(i != i1) {
|
||||
return false;
|
||||
}
|
||||
switch(i){
|
||||
case NBTConstants.TYPE_BYTE:
|
||||
Byte b = (byte)nbtbd.get(tag);
|
||||
@@ -1054,15 +1056,18 @@ public class _1710ItemUtils implements IDabItemUtils{
|
||||
public boolean compareCompoundTag(Object tag, Object tag1) throws Exception{
|
||||
Map<String, Object> map = (Map<String, Object>)getMap(tag);
|
||||
Map<String, Object> map1 = (Map<String, Object>)getMap(tag1);
|
||||
if(map.size() != map1.size())
|
||||
return false;
|
||||
if(!map.keySet().containsAll(map1.keySet()))
|
||||
return false;
|
||||
if(map.size() != map1.size()) {
|
||||
return false;
|
||||
}
|
||||
if(!map.keySet().containsAll(map1.keySet())) {
|
||||
return false;
|
||||
}
|
||||
for(Entry<String, Object> e : map.entrySet()){
|
||||
Object o = e.getValue();
|
||||
Object o1 = map1.get(e.getKey());
|
||||
if(!compareBaseTag(o, o1))
|
||||
return false;
|
||||
if(!compareBaseTag(o, o1)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -1072,8 +1077,9 @@ public class _1710ItemUtils implements IDabItemUtils{
|
||||
public boolean compareListTag(Object tag, Object tag1) throws Exception{
|
||||
List list = (List)nbtld.get(tag);
|
||||
List list1 = (List)nbtld.get(tag1);
|
||||
if(list.size() != list1.size())
|
||||
return false;
|
||||
if(list.size() != list1.size()) {
|
||||
return false;
|
||||
}
|
||||
Collections.sort(list);
|
||||
Collections.sort(list1);
|
||||
Iterator it = list.iterator();
|
||||
@@ -1081,8 +1087,9 @@ public class _1710ItemUtils implements IDabItemUtils{
|
||||
while(it.hasNext() && it1.hasNext()){
|
||||
Object o = it.next();
|
||||
Object o1 = it1.next();
|
||||
if(!compareBaseTag(o, o1))
|
||||
return false;
|
||||
if(!compareBaseTag(o, o1)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -1183,8 +1190,9 @@ public class _1710ItemUtils implements IDabItemUtils{
|
||||
int durability = jo.getInt("durability");
|
||||
ItemStack is = new ItemStack(material, amount, (short)durability);
|
||||
JSONObject jo1 = jo.getJSONObject("tag");
|
||||
if(jo1.length() == 0)
|
||||
return is;
|
||||
if(jo1.length() == 0) {
|
||||
return is;
|
||||
}
|
||||
Object tag = convertJSONToCompoundTag(jo1);
|
||||
Object nmis = getNMSCopy(is);
|
||||
setTag(nmis, tag);
|
||||
|
||||
@@ -64,7 +64,7 @@ public class _194ItemUtils implements IDabItemUtils{
|
||||
|
||||
public Class<?> ni = NMSUtils.getNMSClassSilent("Item");
|
||||
|
||||
public Method gn = NMSUtils.getMethodSilent(nmis, "getName");
|
||||
public Method gn = NMSUtils.getMethodSilent(nmis, "getLabel");
|
||||
|
||||
@Override
|
||||
public String getName(ItemStack is){
|
||||
@@ -101,7 +101,7 @@ public class _194ItemUtils implements IDabItemUtils{
|
||||
}
|
||||
}
|
||||
|
||||
public Method gin = NMSUtils.getMethodSilent(ni, "getName");
|
||||
public Method gin = NMSUtils.getMethodSilent(ni, "getLabel");
|
||||
|
||||
@Override
|
||||
public String getItemName(ItemStack is){
|
||||
@@ -676,8 +676,9 @@ public class _194ItemUtils implements IDabItemUtils{
|
||||
ret = nbtiad.get(nbt);
|
||||
break;
|
||||
}
|
||||
if(ret == null)
|
||||
return null;
|
||||
if(ret == null) {
|
||||
return null;
|
||||
}
|
||||
return new JSONArray(new Object[]{ i, ret });
|
||||
}
|
||||
|
||||
@@ -1005,8 +1006,9 @@ public class _194ItemUtils implements IDabItemUtils{
|
||||
public boolean compareBaseTag(Object tag, Object tag1) throws Exception{
|
||||
int i = ((byte)gti.invoke(tag));
|
||||
int i1 = ((byte)gti.invoke(tag1));
|
||||
if(i != i1)
|
||||
return false;
|
||||
if(i != i1) {
|
||||
return false;
|
||||
}
|
||||
switch(i){
|
||||
case NBTConstants.TYPE_BYTE:
|
||||
Byte b = (byte)nbtbd.get(tag);
|
||||
@@ -1058,15 +1060,18 @@ public class _194ItemUtils implements IDabItemUtils{
|
||||
public boolean compareCompoundTag(Object tag, Object tag1) throws Exception{
|
||||
Map<String, Object> map = (Map<String, Object>)getMap(tag);
|
||||
Map<String, Object> map1 = (Map<String, Object>)getMap(tag1);
|
||||
if(map.size() != map1.size())
|
||||
return false;
|
||||
if(!map.keySet().containsAll(map1.keySet()))
|
||||
return false;
|
||||
if(map.size() != map1.size()) {
|
||||
return false;
|
||||
}
|
||||
if(!map.keySet().containsAll(map1.keySet())) {
|
||||
return false;
|
||||
}
|
||||
for(Entry<String, Object> e : map.entrySet()){
|
||||
Object o = e.getValue();
|
||||
Object o1 = map1.get(e.getKey());
|
||||
if(!compareBaseTag(o, o1))
|
||||
return false;
|
||||
if(!compareBaseTag(o, o1)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -1076,10 +1081,12 @@ public class _194ItemUtils implements IDabItemUtils{
|
||||
public boolean compareListTag(Object tag, Object tag1) throws Exception{
|
||||
List list = (List)nbtld.get(tag);
|
||||
List list1 = (List)nbtld.get(tag1);
|
||||
if(list.size() != list1.size())
|
||||
return false;
|
||||
if(list.isEmpty() && list1.isEmpty())
|
||||
return true;
|
||||
if(list.size() != list1.size()) {
|
||||
return false;
|
||||
}
|
||||
if(list.isEmpty() && list1.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
List copy = new ArrayList(list);
|
||||
List copy1 = new ArrayList(list1);
|
||||
Iterator it = copy.iterator();
|
||||
@@ -1096,8 +1103,9 @@ public class _194ItemUtils implements IDabItemUtils{
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(!cont)
|
||||
return false;
|
||||
if(!cont) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return copy.isEmpty() && copy1.isEmpty();
|
||||
}
|
||||
@@ -1196,8 +1204,9 @@ public class _194ItemUtils implements IDabItemUtils{
|
||||
int durability = jo.getInt("durability");
|
||||
ItemStack is = new ItemStack(material, amount, (short)durability);
|
||||
JSONObject jo1 = jo.getJSONObject("tag");
|
||||
if(jo1.length() == 0)
|
||||
return is;
|
||||
if(jo1.length() == 0) {
|
||||
return is;
|
||||
}
|
||||
Object tag = convertJSONToCompoundTag(jo1);
|
||||
Object nmis = getNMSCopy(is);
|
||||
setTag(nmis, tag);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package me.skymc.taboolib.object;
|
||||
|
||||
@Deprecated
|
||||
public class WeightCategory {
|
||||
|
||||
private String category;
|
||||
|
||||
99
src/main/java/me/skymc/taboolib/object/WeightCollection.java
Normal file
99
src/main/java/me/skymc/taboolib/object/WeightCollection.java
Normal file
@@ -0,0 +1,99 @@
|
||||
package me.skymc.taboolib.object;
|
||||
|
||||
import me.skymc.taboolib.other.NumberUtils;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import javax.annotation.concurrent.ThreadSafe;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
/**
|
||||
* @Author sky
|
||||
* @Since 2018-05-07 16:18
|
||||
*/
|
||||
@ThreadSafe
|
||||
public class WeightCollection<A> {
|
||||
|
||||
private final List<WeightObject> weightList = new CopyOnWriteArrayList<>();
|
||||
|
||||
public int size() {
|
||||
return weightList.size();
|
||||
}
|
||||
|
||||
public List<WeightObject> getWeightList() {
|
||||
return weightList;
|
||||
}
|
||||
|
||||
public void add(int weightNumber, A weightObject) {
|
||||
weightList.add(new WeightObject(weightNumber, weightObject));
|
||||
}
|
||||
|
||||
public void remove(WeightObject weightObject) {
|
||||
weightList.remove(weightObject);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public WeightObject getWeight() {
|
||||
int weightSum = weightList.stream().mapToInt(WeightObject::getWeightNumber).sum();
|
||||
if (weightSum > 0) {
|
||||
Integer m = 0, n = NumberUtils.getRandom().nextInt(weightSum);
|
||||
for (WeightObject weightObject : weightList) {
|
||||
if (m <= n && n < m + weightObject.getWeightNumber()) {
|
||||
return weightObject;
|
||||
}
|
||||
m += weightObject.getWeightNumber();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
class WeightObject<B> {
|
||||
|
||||
private int weightNumber;
|
||||
private B weightObject;
|
||||
|
||||
public WeightObject(int weightNumber, B weightObject) {
|
||||
this.weightNumber = weightNumber;
|
||||
this.weightObject = weightObject;
|
||||
}
|
||||
|
||||
public int getWeightNumber() {
|
||||
return weightNumber;
|
||||
}
|
||||
|
||||
public void setWeightNumber(int weightNumber) {
|
||||
this.weightNumber = weightNumber;
|
||||
}
|
||||
|
||||
public B getWeightObject() {
|
||||
return weightObject;
|
||||
}
|
||||
|
||||
public void setWeightObject(B weightObject) {
|
||||
this.weightObject = weightObject;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (!(o instanceof WeightObject)) {
|
||||
return false;
|
||||
}
|
||||
WeightObject that = (WeightObject) o;
|
||||
return getWeightNumber() == that.getWeightNumber() && Objects.equals(getWeightObject(), that.getWeightObject());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(getWeightNumber(), getWeightObject());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "weightNumber=" + "WeightObject{" + weightNumber + ", weightObject=" + weightObject + '}';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,38 +5,27 @@ import java.util.Random;
|
||||
|
||||
public class NumberUtils {
|
||||
|
||||
private static Random rand = new Random();
|
||||
private static Random random = new Random();
|
||||
private static DecimalFormat doubleFormat = new DecimalFormat("#.##");
|
||||
|
||||
public static Random getRand() {
|
||||
return rand;
|
||||
public static Random getRandom() {
|
||||
return random;
|
||||
}
|
||||
|
||||
public static Double format(Double num) {
|
||||
return Double.valueOf(doubleFormat.format(num));
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static int getRandom() {
|
||||
return rand.nextInt(100);
|
||||
public static int getRandomInteger(Number num1, Number num2) {
|
||||
int min = Math.min(num1.intValue(), num2.intValue());
|
||||
int max = Math.max(num1.intValue(), num2.intValue());
|
||||
return (int) (random.nextDouble() * (max - min) + min);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static boolean getChance(int a) {
|
||||
return getRandom() <= a;
|
||||
}
|
||||
|
||||
public static int getRandomInteger(Number l, Number u) {
|
||||
Integer ll = Math.min(l.intValue(), u.intValue());
|
||||
Integer uu = Math.max(l.intValue(), u.intValue());
|
||||
return rand.nextInt(uu) % (uu - ll + 1) + ll;
|
||||
}
|
||||
|
||||
public static double getRandomDouble(Number l, Number u) {
|
||||
double ll = Math.min(l.doubleValue(), u.doubleValue());
|
||||
double uu = Math.max(l.doubleValue(), u.doubleValue());
|
||||
double d = ll + rand.nextDouble() * (uu - ll);
|
||||
return Double.valueOf(doubleFormat.format(d));
|
||||
public static double getRandomDouble(Number num1, Number num2) {
|
||||
double min = Math.min(num1.doubleValue(), num2.doubleValue());
|
||||
double max = Math.max(num1.doubleValue(), num2.doubleValue());
|
||||
return random.nextDouble() * (max - min) + min;
|
||||
}
|
||||
|
||||
public static int getInteger(String s) {
|
||||
@@ -62,4 +51,14 @@ public class NumberUtils {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static Random getRand() {
|
||||
return random;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static boolean getChance(int a) {
|
||||
return getRandom().nextInt(100) <= a;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import me.skymc.taboolib.object.WeightCategory;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Deprecated
|
||||
public class WeightUtils {
|
||||
|
||||
public static String getStringByWeight(List<WeightCategory> categorys) {
|
||||
@@ -17,7 +18,7 @@ public class WeightUtils {
|
||||
return null;
|
||||
}
|
||||
|
||||
Integer n = NumberUtils.getRand().nextInt(weightSum);
|
||||
Integer n = NumberUtils.getRandom().nextInt(weightSum);
|
||||
Integer m = 0;
|
||||
|
||||
for (WeightCategory wc : categorys) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package me.skymc.taboolib.playerdata;
|
||||
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import me.skymc.taboolib.Main;
|
||||
import me.skymc.taboolib.database.PlayerDataManager;
|
||||
import me.skymc.taboolib.exception.PlayerOfflineException;
|
||||
@@ -49,7 +50,7 @@ public class DataUtils implements Listener {
|
||||
saveAllCaches(getFixedPlugin(plugin), remove);
|
||||
}
|
||||
if (!Main.getInst().getConfig().getBoolean("HIDE-NOTIFY")) {
|
||||
MsgUtils.send("保存 &f" + DataUtils.CACHE_DATA_PLUGIN.size() + " &7条插件数据, 耗时: &f" + (System.currentTimeMillis() - time) + " &7(ms)");
|
||||
TLocale.Logger.info("DATA-UTILS.SUCCESS-SAVE-DATA", String.valueOf(DataUtils.CACHE_DATA_PLUGIN.size()), String.valueOf(System.currentTimeMillis() - time));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,7 +58,7 @@ public class DataUtils implements Listener {
|
||||
try {
|
||||
conf.save(file);
|
||||
} catch (IOException e) {
|
||||
MsgUtils.warn("文件 &4" + file.getName() + "&c 保存失败, 原因: &4" + e.getMessage());
|
||||
TLocale.Logger.error("DATA-UTILS.FALL-SAVE-FILE", file.getName(), e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
//
|
||||
// Source code recreated from a .class file by IntelliJ IDEA
|
||||
// (powered by Fernflower decompiler)
|
||||
//
|
||||
|
||||
package me.skymc.taboolib.plugin;
|
||||
|
||||
import com.google.common.base.Joiner;
|
||||
@@ -18,53 +23,41 @@ import java.util.*;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class PluginUtils {
|
||||
|
||||
public static String consolidateStrings(final String[] args, final int start) {
|
||||
StringBuilder ret = new StringBuilder(args[start]);
|
||||
if (args.length > start + 1) {
|
||||
for (int i = start + 1; i < args.length; ++i) {
|
||||
ret.append(" ").append(args[i]);
|
||||
}
|
||||
}
|
||||
return ret.toString();
|
||||
private PluginUtils() {
|
||||
}
|
||||
|
||||
public static void enable(final Plugin plugin) {
|
||||
public static void enable(Plugin plugin) {
|
||||
if (plugin != null && !plugin.isEnabled()) {
|
||||
Bukkit.getPluginManager().enablePlugin(plugin);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void enableAll() {
|
||||
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
|
||||
if (!isIgnored(plugin)) {
|
||||
enable(plugin);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void disable(final Plugin plugin) {
|
||||
public static void disable(Plugin plugin) {
|
||||
if (plugin != null && plugin.isEnabled()) {
|
||||
Bukkit.getPluginManager().disablePlugin(plugin);
|
||||
}
|
||||
}
|
||||
|
||||
public static void disableAll() {
|
||||
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
|
||||
if (!isIgnored(plugin)) {
|
||||
disable(plugin);
|
||||
}
|
||||
}
|
||||
public static void enableAll() {
|
||||
Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(plugin -> isIgnored(plugin)).forEach(PluginUtils::enable);
|
||||
}
|
||||
|
||||
public static String getFormattedName(final Plugin plugin) {
|
||||
public static void disableAll() {
|
||||
Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(plugin -> isIgnored(plugin)).forEach(PluginUtils::disable);
|
||||
}
|
||||
|
||||
public static String getFormattedName(Plugin plugin) {
|
||||
return getFormattedName(plugin, false);
|
||||
}
|
||||
|
||||
public static String getFormattedName(final Plugin plugin, final boolean includeVersions) {
|
||||
final ChatColor color = plugin.isEnabled() ? ChatColor.GREEN : ChatColor.RED;
|
||||
public static String getFormattedName(Plugin plugin, boolean includeVersions) {
|
||||
ChatColor color = plugin.isEnabled() ? ChatColor.GREEN : ChatColor.RED;
|
||||
String pluginName = color + plugin.getName();
|
||||
if (includeVersions) {
|
||||
pluginName = pluginName + " (" + plugin.getDescription().getVersion() + ")";
|
||||
@@ -72,75 +65,84 @@ public class PluginUtils {
|
||||
return pluginName;
|
||||
}
|
||||
|
||||
public static Plugin getPluginByName(final String[] args, final int start) {
|
||||
public static Plugin getPluginByName(String[] args, int start) {
|
||||
return getPluginByName(consolidateStrings(args, start));
|
||||
}
|
||||
|
||||
public static Plugin getPluginByName(final String name) {
|
||||
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
|
||||
if (name.equalsIgnoreCase(plugin.getName())) {
|
||||
return plugin;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
public static Plugin getPluginByName(String name) {
|
||||
return Arrays.stream(Bukkit.getPluginManager().getPlugins(), 0, Bukkit.getPluginManager().getPlugins().length).filter(plugin -> name.equalsIgnoreCase(plugin.getName())).findFirst().orElse(null);
|
||||
}
|
||||
|
||||
public static List<String> getPluginNames(final boolean fullName) {
|
||||
final List<String> plugins = new ArrayList<>();
|
||||
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
|
||||
plugins.add(fullName ? plugin.getDescription().getFullName() : plugin.getName());
|
||||
}
|
||||
public static List<String> getPluginNames(boolean fullName) {
|
||||
List<String> plugins;
|
||||
plugins = Arrays.stream(Bukkit.getPluginManager().getPlugins()).map(plugin -> fullName ? plugin.getDescription().getFullName() : plugin.getName()).collect(Collectors.toList());
|
||||
return plugins;
|
||||
}
|
||||
|
||||
public static String getPluginVersion(final String name) {
|
||||
final Plugin plugin = getPluginByName(name);
|
||||
if (plugin != null && plugin.getDescription() != null) {
|
||||
return plugin.getDescription().getVersion();
|
||||
}
|
||||
return null;
|
||||
public static String getPluginVersion(String name) {
|
||||
Plugin plugin = getPluginByName(name);
|
||||
return plugin != null && plugin.getDescription() != null ? plugin.getDescription().getVersion() : null;
|
||||
}
|
||||
|
||||
public static String getUsages(final Plugin plugin) {
|
||||
final List<String> parsedCommands = new ArrayList<>();
|
||||
final Map<String, Map<String, Object>> commands = plugin.getDescription().getCommands();
|
||||
public static String getUsages(Plugin plugin) {
|
||||
List<String> parsedCommands = new ArrayList();
|
||||
Map commands = plugin.getDescription().getCommands();
|
||||
if (commands != null) {
|
||||
for (final Entry<String, Map<String, Object>> thisEntry : commands.entrySet()) {
|
||||
for (Object o : commands.entrySet()) {
|
||||
Entry thisEntry = (Entry) o;
|
||||
if (thisEntry != null) {
|
||||
parsedCommands.add(thisEntry.getKey());
|
||||
parsedCommands.add((String) thisEntry.getKey());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (parsedCommands.isEmpty()) {
|
||||
return "No commands registered.";
|
||||
}
|
||||
return Joiner.on(", ").join(parsedCommands);
|
||||
return parsedCommands.isEmpty() ? "No commands registered." : Joiner.on(", ").join(parsedCommands);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static List<String> findByCommand(final String command) {
|
||||
final List<String> plugins = new ArrayList<>();
|
||||
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
|
||||
final Map<String, Map<String, Object>> commands = plugin.getDescription().getCommands();
|
||||
public static List<String> findByCommand(String command) {
|
||||
List<String> plugins = new ArrayList();
|
||||
|
||||
label60:
|
||||
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
|
||||
Map<String, Map<String, Object>> commands = plugin.getDescription().getCommands();
|
||||
if (commands != null) {
|
||||
for (final Map.Entry<String, Map<String, Object>> commandNext : commands.entrySet()) {
|
||||
if (commandNext.getKey().equalsIgnoreCase(command)) {
|
||||
plugins.add(plugin.getName());
|
||||
} else {
|
||||
for (final Map.Entry<String, Object> attributeNext : commandNext.getValue().entrySet()) {
|
||||
if (attributeNext.getKey().equals("aliases")) {
|
||||
final Object aliases = attributeNext.getValue();
|
||||
if (aliases instanceof String) {
|
||||
if (!((String) aliases).equalsIgnoreCase(command)) {
|
||||
continue;
|
||||
Iterator commandIterator = commands.entrySet().iterator();
|
||||
|
||||
while (true) {
|
||||
label55:
|
||||
while (true) {
|
||||
if (!commandIterator.hasNext()) {
|
||||
continue label60;
|
||||
}
|
||||
|
||||
Entry<String, Map<String, Object>> commandNext = (Entry) commandIterator.next();
|
||||
if (commandNext.getKey().equalsIgnoreCase(command)) {
|
||||
plugins.add(plugin.getName());
|
||||
} else {
|
||||
Iterator attributeIterator = ((Map) commandNext.getValue()).entrySet().iterator();
|
||||
|
||||
while (true) {
|
||||
while (true) {
|
||||
Entry attributeNext;
|
||||
if (!attributeIterator.hasNext()) {
|
||||
continue label55;
|
||||
}
|
||||
plugins.add(plugin.getName());
|
||||
} else {
|
||||
final List<String> array = (List<String>) aliases;
|
||||
for (final String str : array) {
|
||||
if (str.equalsIgnoreCase(command)) {
|
||||
|
||||
attributeNext = (Entry) attributeIterator.next();
|
||||
while (!"aliases".equals(attributeNext.getKey())) {
|
||||
if (!attributeIterator.hasNext()) {
|
||||
continue label55;
|
||||
}
|
||||
|
||||
attributeNext = (Entry) attributeIterator.next();
|
||||
}
|
||||
|
||||
Object aliases = attributeNext.getValue();
|
||||
if (aliases instanceof String) {
|
||||
if (((String) aliases).equalsIgnoreCase(command)) {
|
||||
plugins.add(plugin.getName());
|
||||
}
|
||||
} else {
|
||||
((List<String>) aliases).stream().filter(str -> str.equalsIgnoreCase(command)).map(str -> plugin.getName()).forEach(plugins::add);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -152,138 +154,172 @@ public class PluginUtils {
|
||||
return plugins;
|
||||
}
|
||||
|
||||
public static boolean isIgnored(final Plugin plugin) {
|
||||
return isIgnored(plugin.getName());
|
||||
public static boolean isIgnored(Plugin plugin) {
|
||||
return plugin.equals(Main.getInst());
|
||||
}
|
||||
|
||||
public static boolean isIgnored(final String plugin) {
|
||||
return plugin.equalsIgnoreCase(Main.getInst().getName());
|
||||
}
|
||||
|
||||
private static String load(final Plugin plugin) {
|
||||
private static String load(Plugin plugin) {
|
||||
return load(plugin.getName());
|
||||
}
|
||||
|
||||
public static String load(final String name) {
|
||||
/**
|
||||
* 返回内容:
|
||||
*
|
||||
* plugin-directory —— 插件目录不存在
|
||||
* cannot-find —— 插件不存在
|
||||
* invalid-description —— 无效的描述
|
||||
* invalid-plugin —— 无效的插件
|
||||
* loaded —— 载入成功
|
||||
*/
|
||||
public static String load(String name) {
|
||||
Plugin target;
|
||||
final File pluginDir = new File("plugins");
|
||||
File pluginDir = new File("plugins");
|
||||
if (!pluginDir.isDirectory()) {
|
||||
return "load.plugin-directory";
|
||||
}
|
||||
File pluginFile = new File(pluginDir, name + ".jar");
|
||||
if (!pluginFile.isFile()) {
|
||||
for (final File f : pluginDir.listFiles()) {
|
||||
if (f.getName().endsWith(".jar")) {
|
||||
try {
|
||||
final PluginDescriptionFile desc = Main.getInst().getPluginLoader().getPluginDescription(f);
|
||||
if (desc.getName().equalsIgnoreCase(name)) {
|
||||
pluginFile = f;
|
||||
break;
|
||||
return "plugin-directory";
|
||||
} else {
|
||||
File pluginFile = new File(pluginDir, name + ".jar");
|
||||
if (!pluginFile.isFile()) {
|
||||
for (File f : Objects.requireNonNull(pluginDir.listFiles())) {
|
||||
if (f.getName().endsWith(".jar")) {
|
||||
try {
|
||||
PluginDescriptionFile desc = Main.getInst().getPluginLoader().getPluginDescription(f);
|
||||
if (desc.getName().equalsIgnoreCase(name)) {
|
||||
pluginFile = f;
|
||||
break;
|
||||
}
|
||||
} catch (InvalidDescriptionException var11) {
|
||||
return "cannot-find";
|
||||
}
|
||||
} catch (InvalidDescriptionException e3) {
|
||||
return "load.cannot-find";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
target = Bukkit.getPluginManager().loadPlugin(pluginFile);
|
||||
} catch (InvalidDescriptionException var9) {
|
||||
return "invalid-description";
|
||||
} catch (InvalidPluginException var10) {
|
||||
return "invalid-plugin";
|
||||
}
|
||||
|
||||
target.onLoad();
|
||||
Bukkit.getPluginManager().enablePlugin(target);
|
||||
return "loaded";
|
||||
}
|
||||
try {
|
||||
target = Bukkit.getPluginManager().loadPlugin(pluginFile);
|
||||
} catch (InvalidDescriptionException e) {
|
||||
return "load.invalid-description";
|
||||
} catch (InvalidPluginException e2) {
|
||||
return "load.invalid-plugin";
|
||||
}
|
||||
target.onLoad();
|
||||
Bukkit.getPluginManager().enablePlugin(target);
|
||||
return "load.loaded";
|
||||
}
|
||||
|
||||
public static void reload(final Plugin plugin) {
|
||||
public static void reload(Plugin plugin) {
|
||||
if (plugin != null) {
|
||||
unload(plugin);
|
||||
load(plugin);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void reloadAll() {
|
||||
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
|
||||
if (!isIgnored(plugin)) {
|
||||
reload(plugin);
|
||||
}
|
||||
}
|
||||
Arrays.stream(Bukkit.getPluginManager().getPlugins(), 0, Bukkit.getPluginManager().getPlugins().length).filter(PluginUtils::isIgnored).forEach(PluginUtils::reload);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static String unload(final Plugin plugin) {
|
||||
final String name = plugin.getName();
|
||||
final PluginManager pluginManager = Bukkit.getPluginManager();
|
||||
/**
|
||||
* 返回内容:
|
||||
*
|
||||
* failed —— 卸载失败
|
||||
* unloaded —— 卸载成功
|
||||
*/
|
||||
public static String unload(Plugin plugin) {
|
||||
String name = plugin.getName();
|
||||
PluginManager pluginManager = Bukkit.getPluginManager();
|
||||
SimpleCommandMap commandMap = null;
|
||||
List<Plugin> plugins = null;
|
||||
Map<String, Plugin> names = null;
|
||||
Map<String, Command> commands = null;
|
||||
Map<Event, SortedSet<RegisteredListener>> listeners = null;
|
||||
boolean reloadlisteners = true;
|
||||
if (pluginManager != null) {
|
||||
pluginManager.disablePlugin(plugin);
|
||||
|
||||
try {
|
||||
final Field pluginsField = Bukkit.getPluginManager().getClass().getDeclaredField("plugins");
|
||||
Field pluginsField = Bukkit.getPluginManager().getClass().getDeclaredField("plugins");
|
||||
pluginsField.setAccessible(true);
|
||||
plugins = (List<Plugin>) pluginsField.get(pluginManager);
|
||||
final Field lookupNamesField = Bukkit.getPluginManager().getClass().getDeclaredField("lookupNames");
|
||||
plugins = (List) pluginsField.get(pluginManager);
|
||||
Field lookupNamesField = Bukkit.getPluginManager().getClass().getDeclaredField("lookupNames");
|
||||
lookupNamesField.setAccessible(true);
|
||||
names = (Map<String, Plugin>) lookupNamesField.get(pluginManager);
|
||||
names = (Map) lookupNamesField.get(pluginManager);
|
||||
|
||||
Field commandMapField;
|
||||
try {
|
||||
final Field listenersField = Bukkit.getPluginManager().getClass().getDeclaredField("listeners");
|
||||
listenersField.setAccessible(true);
|
||||
listeners = (Map<Event, SortedSet<RegisteredListener>>) listenersField.get(pluginManager);
|
||||
} catch (Exception e3) {
|
||||
reloadlisteners = false;
|
||||
commandMapField = Bukkit.getPluginManager().getClass().getDeclaredField("listeners");
|
||||
commandMapField.setAccessible(true);
|
||||
listeners = (Map) commandMapField.get(pluginManager);
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
final Field commandMapField = Bukkit.getPluginManager().getClass().getDeclaredField("commandMap");
|
||||
|
||||
commandMapField = Bukkit.getPluginManager().getClass().getDeclaredField("commandMap");
|
||||
commandMapField.setAccessible(true);
|
||||
commandMap = (SimpleCommandMap) commandMapField.get(pluginManager);
|
||||
final Field knownCommandsField = SimpleCommandMap.class.getDeclaredField("knownCommands");
|
||||
Field knownCommandsField = SimpleCommandMap.class.getDeclaredField("knownCommands");
|
||||
knownCommandsField.setAccessible(true);
|
||||
commands = (Map<String, Command>) knownCommandsField.get(commandMap);
|
||||
} catch (NoSuchFieldException | IllegalAccessException e) {
|
||||
commands = (Map) knownCommandsField.get(commandMap);
|
||||
} catch (NoSuchFieldException | IllegalAccessException var15) {
|
||||
return "failed";
|
||||
}
|
||||
}
|
||||
|
||||
pluginManager.disablePlugin(plugin);
|
||||
if (plugins != null) {
|
||||
if (plugins != null && plugins.contains(plugin)) {
|
||||
plugins.remove(plugin);
|
||||
}
|
||||
if (names != null) {
|
||||
|
||||
if (names != null && names.containsKey(name)) {
|
||||
names.remove(name);
|
||||
}
|
||||
if (listeners != null && reloadlisteners) {
|
||||
for (final SortedSet<RegisteredListener> set : listeners.values()) {
|
||||
set.removeIf(value -> value.getPlugin() == plugin);
|
||||
}
|
||||
}
|
||||
if (commandMap != null) {
|
||||
final Iterator<Map.Entry<String, Command>> it2 = commands.entrySet().iterator();
|
||||
while (it2.hasNext()) {
|
||||
final Map.Entry<String, Command> entry = it2.next();
|
||||
if (entry.getValue() instanceof PluginCommand) {
|
||||
final PluginCommand c = (PluginCommand) entry.getValue();
|
||||
if (c.getPlugin() != plugin) {
|
||||
continue;
|
||||
|
||||
Iterator it;
|
||||
if (listeners != null) {
|
||||
it = listeners.values().iterator();
|
||||
|
||||
while (it.hasNext()) {
|
||||
SortedSet<RegisteredListener> set = (SortedSet) it.next();
|
||||
|
||||
while (it.hasNext()) {
|
||||
RegisteredListener value = (RegisteredListener) it.next();
|
||||
if (value.getPlugin() == plugin) {
|
||||
it.remove();
|
||||
}
|
||||
c.unregister(commandMap);
|
||||
it2.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
final ClassLoader cl = plugin.getClass().getClassLoader();
|
||||
|
||||
if (commandMap != null) {
|
||||
it = commands.entrySet().iterator();
|
||||
|
||||
while (it.hasNext()) {
|
||||
Entry<String, Command> entry = (Entry) it.next();
|
||||
if (entry.getValue() instanceof PluginCommand) {
|
||||
PluginCommand c = (PluginCommand) entry.getValue();
|
||||
if (c.getPlugin() == plugin) {
|
||||
c.unregister(commandMap);
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ClassLoader cl = plugin.getClass().getClassLoader();
|
||||
if (cl instanceof URLClassLoader) {
|
||||
try {
|
||||
((URLClassLoader) cl).close();
|
||||
} catch (IOException ex) {
|
||||
Logger.getLogger(PluginUtils.class.getName()).log(Level.SEVERE, null, ex);
|
||||
} catch (IOException var13) {
|
||||
Logger.getLogger(PluginUtils.class.getName()).log(Level.SEVERE, null, var13);
|
||||
}
|
||||
}
|
||||
System.gc();
|
||||
return "unloaded";
|
||||
}
|
||||
|
||||
private static String consolidateStrings(String[] args, int start) {
|
||||
String ret = "";
|
||||
if (args.length > start + 1) {
|
||||
ret = IntStream.range(start + 1, args.length).mapToObj(i -> " " + args[i]).collect(Collectors.joining("", args[start], ""));
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package me.skymc.taboolib.sign;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.util.HashMap;
|
||||
|
||||
import me.skymc.taboolib.Main;
|
||||
import me.skymc.taboolib.location.LocationUtils;
|
||||
import me.skymc.taboolib.message.MsgUtils;
|
||||
import me.skymc.taboolib.methods.MethodsUtils;
|
||||
import me.skymc.taboolib.nms.NMSUtils;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.Block;
|
||||
@@ -16,134 +18,126 @@ import org.bukkit.event.block.SignChangeEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.metadata.FixedMetadataValue;
|
||||
|
||||
import me.skymc.taboolib.Main;
|
||||
import me.skymc.taboolib.location.LocationUtils;
|
||||
import me.skymc.taboolib.message.MsgUtils;
|
||||
import me.skymc.taboolib.methods.MethodsUtils;
|
||||
import me.skymc.taboolib.nms.NMSUtils;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.util.HashMap;
|
||||
|
||||
@Deprecated
|
||||
public class SignUtils implements Listener {
|
||||
|
||||
public static HashMap<String, Block> signs = new HashMap<>();
|
||||
|
||||
public static void openSign(Player p, Block b) {
|
||||
|
||||
if (!(b.getType().equals(Material.WALL_SIGN) || b.getType().equals(Material.SIGN_POST))) {
|
||||
return;
|
||||
}
|
||||
|
||||
b.setMetadata("TabooLib-Sign-Editing", new FixedMetadataValue(Main.getInst(), true));
|
||||
|
||||
try {
|
||||
Object world = b.getWorld().getClass().getMethod("getHandle").invoke(b.getWorld());
|
||||
Object blockPos = NMSUtils.getNMSClass("BlockPosition").getConstructor(int.class, int.class, int.class).newInstance(b.getX(), b.getY(), b.getZ());
|
||||
Object sign = world.getClass().getMethod("getTileEntity", NMSUtils.getNMSClass("BlockPosition")).invoke(world, blockPos);
|
||||
|
||||
Object player = p.getClass().getMethod("getHandle").invoke(p);
|
||||
|
||||
player.getClass().getMethod("openSign", NMSUtils.getNMSClass("TileEntitySign")).invoke(player, sign);
|
||||
}
|
||||
catch (Exception e) {
|
||||
MsgUtils.send(p, "&4操作失败 &8(SIGN OPENED ERROR.1)");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void openSign(Player p, String[] lines, String signid)
|
||||
{
|
||||
if (!MethodsUtils.checkUser(new String(new byte[] { 'm', 'e', '.', 's', 'k', 'y', 'm', 'c' }), new Exception().getStackTrace()[1].getClassName()))
|
||||
{
|
||||
throw new Error("未经允许的方法调用");
|
||||
}
|
||||
|
||||
Block b = LocationUtils.findBlockByLocation(p.getLocation());
|
||||
if(b == null) {
|
||||
public static HashMap<String, Block> signs = new HashMap<>();
|
||||
|
||||
public static void openSign(Player p, Block b) {
|
||||
|
||||
if (!(b.getType().equals(Material.WALL_SIGN) || b.getType().equals(Material.SIGN_POST))) {
|
||||
return;
|
||||
}
|
||||
|
||||
b.setMetadata("TabooLib-Sign-Editing", new FixedMetadataValue(Main.getInst(), true));
|
||||
|
||||
try {
|
||||
Object world = b.getWorld().getClass().getMethod("getHandle").invoke(b.getWorld());
|
||||
Object blockPos = NMSUtils.getNMSClass("BlockPosition").getConstructor(int.class, int.class, int.class).newInstance(b.getX(), b.getY(), b.getZ());
|
||||
Object sign = world.getClass().getMethod("getTileEntity", NMSUtils.getNMSClass("BlockPosition")).invoke(world, blockPos);
|
||||
|
||||
Object player = p.getClass().getMethod("getHandle").invoke(p);
|
||||
|
||||
player.getClass().getMethod("openSign", NMSUtils.getNMSClass("TileEntitySign")).invoke(player, sign);
|
||||
} catch (Exception e) {
|
||||
MsgUtils.send(p, "&4操作失败 &8(SIGN OPENED ERROR.1)");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void openSign(Player p, String[] lines, String signid) {
|
||||
if (!MethodsUtils.checkUser(new String(new byte[]{'m', 'e', '.', 's', 'k', 'y', 'm', 'c'}), new Exception().getStackTrace()[1].getClassName())) {
|
||||
throw new Error("未经允许的方法调用");
|
||||
}
|
||||
|
||||
Block b = LocationUtils.findBlockByLocation(p.getLocation());
|
||||
if (b == null) {
|
||||
MsgUtils.send(p, "&4所在位置无法进行该操作 &8(NOT FOUND AIR BY SIGN)");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
b.setData((byte) 0);
|
||||
b.setType(Material.WALL_SIGN);
|
||||
|
||||
|
||||
b.setMetadata("TabooLib-Sign", new FixedMetadataValue(Main.getInst(), true));
|
||||
b.setMetadata("TabooLib-Sign-UUID", new FixedMetadataValue(Main.getInst(), signid));
|
||||
|
||||
|
||||
try {
|
||||
Object world = b.getWorld().getClass().getMethod("getHandle").invoke(b.getWorld());
|
||||
Object blockPos = NMSUtils.getNMSClass("BlockPosition").getConstructor(int.class, int.class, int.class).newInstance(b.getX(), b.getY(), b.getZ());
|
||||
Object sign = world.getClass().getMethod("getTileEntity", NMSUtils.getNMSClass("BlockPosition")).invoke(world, blockPos);
|
||||
|
||||
Object[] _lines = (Object[]) sign.getClass().getField("lines").get(sign);
|
||||
|
||||
for (int i = 0; i < lines.length ; i++) {
|
||||
Object object = NMSUtils.getNMSClass("ChatComponentText").getConstructor(String.class).newInstance(lines[i]);
|
||||
_lines[i] = object;
|
||||
|
||||
for (int i = 0; i < lines.length; i++) {
|
||||
Object object = NMSUtils.getNMSClass("ChatComponentText").getConstructor(String.class).newInstance(lines[i]);
|
||||
_lines[i] = object;
|
||||
}
|
||||
|
||||
|
||||
Object player = p.getClass().getMethod("getHandle").invoke(p);
|
||||
|
||||
|
||||
Bukkit.getScheduler().runTaskLater(Main.getInst(), () -> {
|
||||
if (p.isOnline()) {
|
||||
try {
|
||||
player.getClass().getMethod("openSign", NMSUtils.getNMSClass("TileEntitySign")).invoke(player, sign);
|
||||
signs.put(p.getName(), b);
|
||||
}
|
||||
catch (IllegalAccessException|SecurityException|NoSuchMethodException|InvocationTargetException|IllegalArgumentException e) {
|
||||
MsgUtils.send(p, "&4操作失败 &8(SIGN OPENED ERROR.2)");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}, 3);
|
||||
}
|
||||
catch (Exception e) {
|
||||
MsgUtils.send(p, "&4操作失败 &8(SIGN OPENED ERROR.1)");
|
||||
e.printStackTrace();
|
||||
if (p.isOnline()) {
|
||||
try {
|
||||
player.getClass().getMethod("openSign", NMSUtils.getNMSClass("TileEntitySign")).invoke(player, sign);
|
||||
signs.put(p.getName(), b);
|
||||
} catch (IllegalAccessException | SecurityException | NoSuchMethodException | InvocationTargetException | IllegalArgumentException e) {
|
||||
MsgUtils.send(p, "&4操作失败 &8(SIGN OPENED ERROR.2)");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}, 3);
|
||||
} catch (Exception e) {
|
||||
MsgUtils.send(p, "&4操作失败 &8(SIGN OPENED ERROR.1)");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler (priority = EventPriority.LOWEST)
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void signChange(SignChangeEvent e) {
|
||||
Block block = e.getBlock();
|
||||
if (block.hasMetadata("TabooLib-Sign")) {
|
||||
signs.remove(e.getPlayer().getName());
|
||||
|
||||
String signid = String.valueOf(block.getMetadata("TabooLib-Sign-UUID").get(0).value());
|
||||
Bukkit.getPluginManager().callEvent(new TabooSignChangeEvent(e.getPlayer(), block, e.getLines(), signid));
|
||||
|
||||
block.removeMetadata("TabooLib-Sign", Main.getInst());
|
||||
block.removeMetadata("TabooLib-Sign-UUID", Main.getInst());
|
||||
block.setType(Material.AIR);
|
||||
block.setData((byte) 0);
|
||||
}
|
||||
Block block = e.getBlock();
|
||||
if (block.hasMetadata("TabooLib-Sign")) {
|
||||
signs.remove(e.getPlayer().getName());
|
||||
|
||||
String signid = String.valueOf(block.getMetadata("TabooLib-Sign-UUID").get(0).value());
|
||||
Bukkit.getPluginManager().callEvent(new TabooSignChangeEvent(e.getPlayer(), block, e.getLines(), signid));
|
||||
|
||||
block.removeMetadata("TabooLib-Sign", Main.getInst());
|
||||
block.removeMetadata("TabooLib-Sign-UUID", Main.getInst());
|
||||
block.setType(Material.AIR);
|
||||
block.setData((byte) 0);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@EventHandler
|
||||
public void quit(PlayerQuitEvent e) {
|
||||
if (signs.containsKey(e.getPlayer().getName())) {
|
||||
Block block = signs.get(e.getPlayer().getName());
|
||||
if (block.hasMetadata("TabooLib-Sign")) {
|
||||
block.removeMetadata("TabooLib-Sign", Main.getInst());
|
||||
block.removeMetadata("TabooLib-Sign-UUID", Main.getInst());
|
||||
block.setType(Material.AIR);
|
||||
block.setData((byte) 0);
|
||||
}
|
||||
}
|
||||
if (signs.containsKey(e.getPlayer().getName())) {
|
||||
Block block = signs.get(e.getPlayer().getName());
|
||||
if (block.hasMetadata("TabooLib-Sign")) {
|
||||
block.removeMetadata("TabooLib-Sign", Main.getInst());
|
||||
block.removeMetadata("TabooLib-Sign-UUID", Main.getInst());
|
||||
block.setType(Material.AIR);
|
||||
block.setData((byte) 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@EventHandler
|
||||
public void block(BlockPhysicsEvent e) {
|
||||
Block block = e.getBlock();
|
||||
if (block.hasMetadata("TabooLib-Sign")) {
|
||||
e.setCancelled(true);
|
||||
}
|
||||
Block block = e.getBlock();
|
||||
if (block.hasMetadata("TabooLib-Sign")) {
|
||||
e.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@EventHandler
|
||||
public void blocku(BlockBreakEvent e) {
|
||||
Block block = e.getBlock();
|
||||
if (block.hasMetadata("TabooLib-Sign") && !e.getPlayer().isOp()) {
|
||||
e.setCancelled(true);
|
||||
}
|
||||
Block block = e.getBlock();
|
||||
if (block.hasMetadata("TabooLib-Sign") && !e.getPlayer().isOp()) {
|
||||
e.setCancelled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,48 +6,43 @@ import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
|
||||
@Deprecated
|
||||
public class TabooSignChangeEvent
|
||||
extends Event
|
||||
{
|
||||
private static final HandlerList handlers = new HandlerList();
|
||||
private Player player;
|
||||
private Block block;
|
||||
private String[] lines;
|
||||
private String uuid;
|
||||
|
||||
public TabooSignChangeEvent(Player player, Block block, String[] lines, String uuid)
|
||||
{
|
||||
this.player = player;
|
||||
this.block = block;
|
||||
this.lines = lines;
|
||||
this.uuid = uuid;
|
||||
}
|
||||
|
||||
public Player getPlayer()
|
||||
{
|
||||
return this.player;
|
||||
}
|
||||
|
||||
public Block getBlock() {
|
||||
return this.block;
|
||||
}
|
||||
|
||||
public String[] getLines() {
|
||||
return this.lines;
|
||||
}
|
||||
|
||||
public String getUUID() {
|
||||
return this.uuid;
|
||||
}
|
||||
public class TabooSignChangeEvent extends Event {
|
||||
|
||||
@Override
|
||||
public HandlerList getHandlers()
|
||||
{
|
||||
return handlers;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList()
|
||||
{
|
||||
return handlers;
|
||||
}
|
||||
private static final HandlerList handlers = new HandlerList();
|
||||
private Player player;
|
||||
private Block block;
|
||||
private String[] lines;
|
||||
private String uuid;
|
||||
|
||||
public TabooSignChangeEvent(Player player, Block block, String[] lines, String uuid) {
|
||||
this.player = player;
|
||||
this.block = block;
|
||||
this.lines = lines;
|
||||
this.uuid = uuid;
|
||||
}
|
||||
|
||||
public Player getPlayer() {
|
||||
return this.player;
|
||||
}
|
||||
|
||||
public Block getBlock() {
|
||||
return this.block;
|
||||
}
|
||||
|
||||
public String[] getLines() {
|
||||
return this.lines;
|
||||
}
|
||||
|
||||
public String getUUID() {
|
||||
return this.uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HandlerList getHandlers() {
|
||||
return handlers;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return handlers;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,6 +61,7 @@ public class SoundPack {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return sound.name() + "-" + a + "-" + b;
|
||||
}
|
||||
|
||||
44
src/main/java/me/skymc/taboolib/string/ArrayUtils.java
Normal file
44
src/main/java/me/skymc/taboolib/string/ArrayUtils.java
Normal file
@@ -0,0 +1,44 @@
|
||||
package me.skymc.taboolib.string;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
/**
|
||||
* @author Bkm016
|
||||
* @since 2018-04-16
|
||||
*/
|
||||
public class ArrayUtils {
|
||||
|
||||
public static <T> List<T> asList(T... args) {
|
||||
List<T> list = new ArrayList<>();
|
||||
Collections.addAll(list, args);
|
||||
return list;
|
||||
}
|
||||
|
||||
public static String[] addFirst(String[] args, String... value) {
|
||||
if (args.length < 1) {
|
||||
return value;
|
||||
}
|
||||
List<String> list = asList(args);
|
||||
for (int i = value.length - 1 ; i >= 0 ; i--) {
|
||||
list.add(0, value[i]);
|
||||
}
|
||||
return list.toArray(new String[0]);
|
||||
}
|
||||
|
||||
public static String[] removeFirst(String[] args) {
|
||||
if (args.length <= 1) {
|
||||
return null;
|
||||
}
|
||||
List<String> list = asList(args);
|
||||
list.remove(0);
|
||||
return list.toArray(new String[0]);
|
||||
}
|
||||
|
||||
public static String arrayJoin(String[] args, int start) {
|
||||
return IntStream.range(start, args.length).mapToObj(i -> args[i] + " ").collect(Collectors.joining()).trim();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,13 @@
|
||||
package me.skymc.taboolib.string;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
import me.skymc.taboolib.message.MsgUtils;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
@@ -7,122 +15,112 @@ import java.io.InputStreamReader;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
|
||||
import me.skymc.taboolib.message.MsgUtils;
|
||||
|
||||
@Deprecated
|
||||
public class Language {
|
||||
|
||||
private FileConfiguration conf = null;
|
||||
private String langName;
|
||||
private Plugin plugin;
|
||||
|
||||
public Language(Plugin plugin) {
|
||||
this("zh_CN", plugin, false);
|
||||
}
|
||||
|
||||
public Language(String name, Plugin plugin) {
|
||||
this(name, plugin, false);
|
||||
}
|
||||
|
||||
public Language(String name, Plugin plugin, boolean utf8) {
|
||||
this.plugin = plugin;
|
||||
this.langName = name;
|
||||
|
||||
File file = new File(getLanguageDir(), name + ".yml");
|
||||
if (!file.exists()) {
|
||||
plugin.saveResource("Language/" + name + ".yml", true);
|
||||
}
|
||||
|
||||
if (utf8) {
|
||||
reloadUTF8(this.langName);
|
||||
}
|
||||
else {
|
||||
reload(this.langName);
|
||||
}
|
||||
}
|
||||
|
||||
public FileConfiguration getConfiguration() {
|
||||
return conf;
|
||||
}
|
||||
|
||||
public void send(CommandSender sender, String key) {
|
||||
sender.sendMessage(get(key));
|
||||
}
|
||||
|
||||
public void send(Player player, String key) {
|
||||
player.sendMessage(get(key));
|
||||
}
|
||||
|
||||
public void sendList(CommandSender sender, String key) {
|
||||
List<String> list = getList(key);
|
||||
for (String msg : list) {
|
||||
sender.sendMessage(msg);
|
||||
}
|
||||
}
|
||||
|
||||
public void sendList(Player player, String key) {
|
||||
List<String> list = getList(key);
|
||||
for (String msg : list) {
|
||||
player.sendMessage(msg);
|
||||
}
|
||||
}
|
||||
|
||||
public String get(String key) {
|
||||
if (conf == null || conf.getString(key) == null) {
|
||||
return "§4[Language \"" + key + "\" Not Found]";
|
||||
}
|
||||
return conf.getString(key).replace("&", "§");
|
||||
}
|
||||
|
||||
public List<String> getList(String key) {
|
||||
if (conf == null || conf.getString(key) == null) {
|
||||
return Collections.singletonList("§4[Language \"" + key + "\" Not Found]");
|
||||
}
|
||||
List<String> list = conf.getStringList(key);
|
||||
for (int i = 0 ; i < list.size() ; i++) {
|
||||
list.set(i, list.get(i).replace("&", "§"));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public void reload() {
|
||||
reload(langName);
|
||||
}
|
||||
|
||||
public void reload(String name) {
|
||||
File langFile = new File(getLanguageDir(), name + ".yml");
|
||||
if (!langFile.exists()) {
|
||||
MsgUtils.warn("语言文件 " + langName + " 不存在, 请更改配置文件");
|
||||
return;
|
||||
}
|
||||
conf = YamlConfiguration.loadConfiguration(langFile);
|
||||
}
|
||||
|
||||
public void reloadUTF8(String name) {
|
||||
File langFile = new File(getLanguageDir(), name + ".yml");
|
||||
if (!langFile.exists()) {
|
||||
MsgUtils.warn("语言文件 " + langName + " 不存在, 请更改配置文件");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
conf = YamlConfiguration.loadConfiguration(new InputStreamReader(new FileInputStream(langFile), Charsets.UTF_8));
|
||||
} catch (FileNotFoundException e) {
|
||||
conf = new YamlConfiguration();
|
||||
}
|
||||
}
|
||||
|
||||
private File getLanguageDir() {
|
||||
File dir = new File(plugin.getDataFolder(), "Language");
|
||||
if (!dir.exists()) {
|
||||
dir.mkdirs();
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
private FileConfiguration conf = null;
|
||||
private String langName;
|
||||
private Plugin plugin;
|
||||
|
||||
public Language(Plugin plugin) {
|
||||
this("zh_CN", plugin, false);
|
||||
}
|
||||
|
||||
public Language(String name, Plugin plugin) {
|
||||
this(name, plugin, false);
|
||||
}
|
||||
|
||||
public Language(String name, Plugin plugin, boolean utf8) {
|
||||
this.plugin = plugin;
|
||||
this.langName = name;
|
||||
|
||||
File file = new File(getLanguageDir(), name + ".yml");
|
||||
if (!file.exists()) {
|
||||
plugin.saveResource("Language/" + name + ".yml", true);
|
||||
}
|
||||
|
||||
if (utf8) {
|
||||
reloadUTF8(this.langName);
|
||||
} else {
|
||||
reload(this.langName);
|
||||
}
|
||||
}
|
||||
|
||||
public FileConfiguration getConfiguration() {
|
||||
return conf;
|
||||
}
|
||||
|
||||
public void send(CommandSender sender, String key) {
|
||||
sender.sendMessage(get(key));
|
||||
}
|
||||
|
||||
public void send(Player player, String key) {
|
||||
player.sendMessage(get(key));
|
||||
}
|
||||
|
||||
public void sendList(CommandSender sender, String key) {
|
||||
List<String> list = getList(key);
|
||||
for (String msg : list) {
|
||||
sender.sendMessage(msg);
|
||||
}
|
||||
}
|
||||
|
||||
public void sendList(Player player, String key) {
|
||||
List<String> list = getList(key);
|
||||
for (String msg : list) {
|
||||
player.sendMessage(msg);
|
||||
}
|
||||
}
|
||||
|
||||
public String get(String key) {
|
||||
if (conf == null || conf.getString(key) == null) {
|
||||
return "§4[Language \"" + key + "\" Not Found]";
|
||||
}
|
||||
return conf.getString(key).replace("&", "§");
|
||||
}
|
||||
|
||||
public List<String> getList(String key) {
|
||||
if (conf == null || conf.getString(key) == null) {
|
||||
return Collections.singletonList("§4[Language \"" + key + "\" Not Found]");
|
||||
}
|
||||
List<String> list = conf.getStringList(key);
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
list.set(i, list.get(i).replace("&", "§"));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public void reload() {
|
||||
reload(langName);
|
||||
}
|
||||
|
||||
public void reload(String name) {
|
||||
File langFile = new File(getLanguageDir(), name + ".yml");
|
||||
if (!langFile.exists()) {
|
||||
MsgUtils.warn("语言文件 " + langName + " 不存在, 请更改配置文件");
|
||||
return;
|
||||
}
|
||||
conf = YamlConfiguration.loadConfiguration(langFile);
|
||||
}
|
||||
|
||||
public void reloadUTF8(String name) {
|
||||
File langFile = new File(getLanguageDir(), name + ".yml");
|
||||
if (!langFile.exists()) {
|
||||
MsgUtils.warn("语言文件 " + langName + " 不存在, 请更改配置文件");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
conf = YamlConfiguration.loadConfiguration(new InputStreamReader(new FileInputStream(langFile), Charsets.UTF_8));
|
||||
} catch (FileNotFoundException e) {
|
||||
conf = new YamlConfiguration();
|
||||
}
|
||||
}
|
||||
|
||||
private File getLanguageDir() {
|
||||
File dir = new File(plugin.getDataFolder(), "Language");
|
||||
if (!dir.exists()) {
|
||||
dir.mkdirs();
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
}
|
||||
@@ -33,4 +33,68 @@ public class StringUtils {
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static double similarDegree(String strA, String strB){
|
||||
String newStrA = removeSign(max(strA, strB));
|
||||
String newStrB = removeSign(min(strA, strB));
|
||||
int temp = Math.max(newStrA.length(), newStrB.length());
|
||||
int temp2 = longestCommonSubstring(newStrA, newStrB).length();
|
||||
return temp2 * 1.0 / temp;
|
||||
}
|
||||
|
||||
private static String max(String strA, String strB) {
|
||||
return strA.length() >= strB.length() ? strA : strB;
|
||||
}
|
||||
|
||||
private static String min(String strA, String strB) {
|
||||
return strA.length() < strB.length() ? strA : strB;
|
||||
}
|
||||
|
||||
private static String removeSign(String str) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for (char item : str.toCharArray()) {
|
||||
if (charReg(item)){
|
||||
sb.append(item);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static boolean charReg(char charValue) {
|
||||
return (charValue >= 0x4E00 && charValue <= 0X9FA5) || (charValue >= 'a' && charValue <= 'z') || (charValue >= 'A' && charValue <= 'Z') || (charValue >= '0' && charValue <= '9');
|
||||
}
|
||||
|
||||
private static String longestCommonSubstring(String strA, String strB) {
|
||||
char[] chars_strA = strA.toCharArray();
|
||||
char[] chars_strB = strB.toCharArray();
|
||||
int m = chars_strA.length;
|
||||
int n = chars_strB.length;
|
||||
|
||||
int[][] matrix = new int[m + 1][n + 1];
|
||||
for (int i = 1; i <= m; i++) {
|
||||
for (int j = 1; j <= n; j++) {
|
||||
if (chars_strA[i - 1] == chars_strB[j - 1]) {
|
||||
matrix[i][j] = matrix[i - 1][j - 1] + 1;
|
||||
} else {
|
||||
matrix[i][j] = Math.max(matrix[i][j - 1], matrix[i - 1][j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
char[] result = new char[matrix[m][n]];
|
||||
int currentIndex = result.length - 1;
|
||||
while (matrix[m][n] != 0) {
|
||||
if (matrix[n] == matrix[n - 1]) {
|
||||
n--;
|
||||
} else if (matrix[m][n] == matrix[m - 1][n]) {
|
||||
m--;
|
||||
} else {
|
||||
result[currentIndex] = chars_strA[m - 1];
|
||||
currentIndex--;
|
||||
n--;
|
||||
m--;
|
||||
}
|
||||
}
|
||||
return new String(result);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package me.skymc.taboolib.string.language2;
|
||||
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import me.clip.placeholderapi.PlaceholderAPI;
|
||||
import me.skymc.taboolib.fileutils.ConfigUtils;
|
||||
import org.bukkit.Bukkit;
|
||||
@@ -74,10 +75,7 @@ public class Language2 {
|
||||
languageFile = new File(languageFolder, languageName);
|
||||
if (!languageFile.exists()) {
|
||||
if (plugin.getResource("Language2/" + languageName) == null) {
|
||||
try {
|
||||
throw new FileNotFoundException("语言文件 " + languageName + " 不存在");
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
TLocale.Logger.error("LANGUAGE2.FALL-NOTFOUND-FILE", languageName);
|
||||
} else {
|
||||
plugin.saveResource("Language2/" + languageName, true);
|
||||
}
|
||||
|
||||
@@ -142,15 +142,11 @@ public class Language2Format implements Language2Line {
|
||||
|
||||
@Override
|
||||
public void send(Player player) {
|
||||
for (Language2Line line : language2Lines) {
|
||||
line.send(player);
|
||||
}
|
||||
language2Lines.forEach(line -> line.send(player));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void console() {
|
||||
for (Language2Line line : language2Lines) {
|
||||
line.console();
|
||||
}
|
||||
language2Lines.forEach(Language2Line::console);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
/**
|
||||
* @author sky
|
||||
@@ -96,9 +97,7 @@ public class Language2Value {
|
||||
* @param players 玩家
|
||||
*/
|
||||
public void send(List<Player> players) {
|
||||
for (Player player : players) {
|
||||
send(player);
|
||||
}
|
||||
players.forEach(this::send);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -206,9 +205,7 @@ public class Language2Value {
|
||||
* @return
|
||||
*/
|
||||
public List<String> asColored(List<String> list) {
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
list.set(i, ChatColor.translateAlternateColorCodes('&', list.get(i)));
|
||||
}
|
||||
IntStream.range(0, list.size()).forEach(i -> list.set(i, ChatColor.translateAlternateColorCodes('&', list.get(i))));
|
||||
return list;
|
||||
}
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ public class Language2Book implements Language2Line {
|
||||
// 遍历内容
|
||||
for (String line : list) {
|
||||
// 翻页
|
||||
if (line.equals("[page]")) {
|
||||
if ("[page]".equals(line)) {
|
||||
book.addPages(page.build());
|
||||
page = new PageBuilder();
|
||||
}
|
||||
|
||||
@@ -84,7 +84,7 @@ public class Language2Json implements Language2Line {
|
||||
clickEvent = new OpenUrlEvent(message.substring(KEY_URL.length()));
|
||||
}
|
||||
// 换行
|
||||
else if (message.equals("[break]")) {
|
||||
else if ("[break]".equals(message)) {
|
||||
append(current, clickEvent, hoverEvent);
|
||||
// 删除动作
|
||||
clickEvent = null;
|
||||
|
||||
@@ -23,10 +23,7 @@ public class Language2Sound implements Language2Line {
|
||||
|
||||
public Language2Sound(Language2Format format, List<String> list) {
|
||||
this.value = format.getLanguage2Value();
|
||||
// 遍历文本
|
||||
for (String line : list) {
|
||||
sounds.add(new SoundPack(line));
|
||||
}
|
||||
list.forEach(line -> sounds.add(new SoundPack(line)));
|
||||
}
|
||||
|
||||
public List<SoundPack> getSounds() {
|
||||
@@ -39,9 +36,7 @@ public class Language2Sound implements Language2Line {
|
||||
|
||||
@Override
|
||||
public void send(Player player) {
|
||||
for (SoundPack sound : sounds) {
|
||||
sound.play(player);
|
||||
}
|
||||
sounds.forEach(sound -> sound.play(player));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -19,12 +19,6 @@ public class Language2Text implements Language2Line {
|
||||
|
||||
private Language2Value value;
|
||||
|
||||
public Language2Text(Language2Format format, List<String> list) {
|
||||
this.value = format.getLanguage2Value();
|
||||
// 遍历文本
|
||||
text.addAll(list);
|
||||
}
|
||||
|
||||
public List<String> getText() {
|
||||
return text;
|
||||
}
|
||||
@@ -33,17 +27,18 @@ public class Language2Text implements Language2Line {
|
||||
return value;
|
||||
}
|
||||
|
||||
public Language2Text(Language2Format format, List<String> list) {
|
||||
this.value = format.getLanguage2Value();
|
||||
text.addAll(list);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(Player player) {
|
||||
for (String line : text) {
|
||||
player.sendMessage(line);
|
||||
}
|
||||
text.forEach(player::sendMessage);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void console() {
|
||||
for (String line : text) {
|
||||
Bukkit.getConsoleSender().sendMessage(line);
|
||||
}
|
||||
text.forEach(line -> Bukkit.getConsoleSender().sendMessage(line));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,9 @@ package me.skymc.taboolib.thread;
|
||||
|
||||
import java.util.LinkedList;
|
||||
|
||||
/**
|
||||
* @author sky
|
||||
*/
|
||||
public class ThreadUtils {
|
||||
|
||||
private static final LinkedList<Runnable> queue = new LinkedList<>();
|
||||
|
||||
@@ -1,170 +1,159 @@
|
||||
package me.skymc.taboolib.timecycle;
|
||||
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import me.skymc.taboolib.Main;
|
||||
import me.skymc.taboolib.database.GlobalDataManager;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
|
||||
import me.skymc.taboolib.Main;
|
||||
import me.skymc.taboolib.database.GlobalDataManager;
|
||||
import me.skymc.taboolib.message.MsgUtils;
|
||||
|
||||
public class TimeCycleManager {
|
||||
|
||||
/**
|
||||
* 最后一次更新: 2018年1月16日21:07:49
|
||||
*
|
||||
* @author sky
|
||||
*/
|
||||
|
||||
private static ConcurrentHashMap<String, TimeCycle> cycles = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* 获取周期管理器
|
||||
*
|
||||
* @param name
|
||||
* @return
|
||||
*/
|
||||
public static TimeCycle getTimeCycle(String name) {
|
||||
return cycles.get(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有周期管理器
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static Collection<TimeCycle> getTimeCycles() {
|
||||
return cycles.values();
|
||||
}
|
||||
|
||||
/**
|
||||
* 彻底删除周期数据
|
||||
*
|
||||
* @param name
|
||||
*/
|
||||
public static void deleteCycleData(String name) {
|
||||
HashMap<String, String> map = GlobalDataManager.getVariables();
|
||||
for (String _name : map.keySet()) {
|
||||
if (_name.startsWith("timecycle")) {
|
||||
GlobalDataManager.setVariable(name, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册周期管理器
|
||||
*
|
||||
* @param cycle
|
||||
*/
|
||||
public static void register(TimeCycle cycle) {
|
||||
if (!cycles.containsKey(cycle.getName())) {
|
||||
cycles.put(cycle.getName(), cycle);
|
||||
}
|
||||
else {
|
||||
MsgUtils.warn("注册周期管理器 §8" + cycle.getName() + "§c 失败, 原因: &4名称重复");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 注销周期管理器
|
||||
*
|
||||
* @param name
|
||||
* @return
|
||||
*/
|
||||
public static TimeCycle cancel(String name) {
|
||||
return cycles.remove(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 注销插件所有周期管理器
|
||||
*
|
||||
* @param plugin
|
||||
*/
|
||||
public static void cancel(Plugin plugin) {
|
||||
cycles.values().forEach(x -> {
|
||||
if (x.getPlugin().equals(plugin)) {
|
||||
cycles.remove(x.getName());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置上一次更新事件
|
||||
*
|
||||
* @param name
|
||||
* @param time
|
||||
*/
|
||||
public static boolean setTimeline(String name, Long time) {
|
||||
if (cycles.containsKey(name)) {
|
||||
GlobalDataManager.setVariable("timecycle:" + name, time.toString());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取下一次刷新时间
|
||||
*
|
||||
* @param name
|
||||
* @return
|
||||
*/
|
||||
public static long getAfterTimeline(String name) {
|
||||
if (cycles.containsKey(name)) {
|
||||
Long value = Long.valueOf(GlobalDataManager.getVariable("timecycle:" + name, "0"));
|
||||
return value + cycles.get(name).getCycle();
|
||||
}
|
||||
return 0L;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取上一次刷新时间
|
||||
*
|
||||
* @param name
|
||||
* @return
|
||||
*/
|
||||
public static long getBeforeTimeline(String name) {
|
||||
if (cycles.containsKey(name)) {
|
||||
return Long.valueOf(GlobalDataManager.getVariable("timecycle:" + name, "0"));
|
||||
}
|
||||
return 0L;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static void load() {
|
||||
// 注册调度器
|
||||
new BukkitRunnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
for (TimeCycle cycle : cycles.values()) {
|
||||
// 调度器没有被执行过
|
||||
if (!GlobalDataManager.contains("timecycle:" + cycle.getName())) {
|
||||
long time = new TimeCycleInitializeEvent(cycle, System.currentTimeMillis()).call().getTimeline();
|
||||
// 初始化
|
||||
GlobalDataManager.setVariable("timecycle:" + cycle.getName(), String.valueOf(time));
|
||||
// 触发器
|
||||
Bukkit.getPluginManager().callEvent(new TimeCycleEvent(cycle));
|
||||
}
|
||||
// 如果超出刷新时间
|
||||
else if (System.currentTimeMillis() >= getAfterTimeline(cycle.getName())) {
|
||||
long time = System.currentTimeMillis();
|
||||
// 如果时间差大于 30 秒
|
||||
if (time - getAfterTimeline(cycle.getName()) > 30000) {
|
||||
// 初始化
|
||||
time = new TimeCycleInitializeEvent(cycle, time).call().getTimeline();
|
||||
}
|
||||
// 重置
|
||||
GlobalDataManager.setVariable("timecycle:" + cycle.getName(), String.valueOf(time));
|
||||
// 触发器
|
||||
Bukkit.getPluginManager().callEvent(new TimeCycleEvent(cycle));
|
||||
}
|
||||
}
|
||||
}
|
||||
}.runTaskTimerAsynchronously(Main.getInst(), 0, 20);
|
||||
}
|
||||
/**
|
||||
* 最后一次更新: 2018年1月16日21:07:49
|
||||
*
|
||||
* @author sky
|
||||
*/
|
||||
|
||||
private static ConcurrentHashMap<String, TimeCycle> cycles = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* 获取周期管理器
|
||||
*
|
||||
* @param name
|
||||
* @return
|
||||
*/
|
||||
public static TimeCycle getTimeCycle(String name) {
|
||||
return cycles.get(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有周期管理器
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static Collection<TimeCycle> getTimeCycles() {
|
||||
return cycles.values();
|
||||
}
|
||||
|
||||
/**
|
||||
* 彻底删除周期数据
|
||||
*
|
||||
* @param name
|
||||
*/
|
||||
public static void deleteCycleData(String name) {
|
||||
HashMap<String, String> map = GlobalDataManager.getVariables();
|
||||
map.keySet().stream().filter(_name -> _name.startsWith("timecycle")).forEach(_name -> GlobalDataManager.setVariable(name, null));
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册周期管理器
|
||||
*
|
||||
* @param cycle
|
||||
*/
|
||||
public static void register(TimeCycle cycle) {
|
||||
if (!cycles.containsKey(cycle.getName())) {
|
||||
cycles.put(cycle.getName(), cycle);
|
||||
} else {
|
||||
TLocale.Logger.error("TIMECYCLE.FALL-CYCLE-EXISTS", cycle.getName());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 注销周期管理器
|
||||
*
|
||||
* @param name
|
||||
* @return
|
||||
*/
|
||||
public static TimeCycle cancel(String name) {
|
||||
return cycles.remove(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 注销插件所有周期管理器
|
||||
*
|
||||
* @param plugin
|
||||
*/
|
||||
public static void cancel(Plugin plugin) {
|
||||
cycles.values().stream().filter(x -> x.getPlugin().equals(plugin)).forEach(x -> cycles.remove(x.getName()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置上一次更新事件
|
||||
*
|
||||
* @param name
|
||||
* @param time
|
||||
*/
|
||||
public static boolean setTimeline(String name, Long time) {
|
||||
if (cycles.containsKey(name)) {
|
||||
GlobalDataManager.setVariable("timecycle:" + name, time.toString());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取下一次刷新时间
|
||||
*
|
||||
* @param name
|
||||
* @return
|
||||
*/
|
||||
public static long getAfterTimeline(String name) {
|
||||
if (cycles.containsKey(name)) {
|
||||
Long value = Long.valueOf(GlobalDataManager.getVariable("timecycle:" + name, "0"));
|
||||
return value + cycles.get(name).getCycle();
|
||||
}
|
||||
return 0L;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取上一次刷新时间
|
||||
*
|
||||
* @param name
|
||||
* @return
|
||||
*/
|
||||
public static long getBeforeTimeline(String name) {
|
||||
if (cycles.containsKey(name)) {
|
||||
return Long.valueOf(GlobalDataManager.getVariable("timecycle:" + name, "0"));
|
||||
}
|
||||
return 0L;
|
||||
}
|
||||
|
||||
|
||||
public static void load() {
|
||||
// 注册调度器
|
||||
new BukkitRunnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
for (TimeCycle cycle : cycles.values()) {
|
||||
// 调度器没有被执行过
|
||||
if (!GlobalDataManager.contains("timecycle:" + cycle.getName())) {
|
||||
long time = new TimeCycleInitializeEvent(cycle, System.currentTimeMillis()).call().getTimeline();
|
||||
// 初始化
|
||||
GlobalDataManager.setVariable("timecycle:" + cycle.getName(), String.valueOf(time));
|
||||
// 触发器
|
||||
Bukkit.getPluginManager().callEvent(new TimeCycleEvent(cycle));
|
||||
}
|
||||
// 如果超出刷新时间
|
||||
else if (System.currentTimeMillis() >= getAfterTimeline(cycle.getName())) {
|
||||
long time = System.currentTimeMillis();
|
||||
// 如果时间差大于 30 秒
|
||||
if (time - getAfterTimeline(cycle.getName()) > 30000) {
|
||||
// 初始化
|
||||
time = new TimeCycleInitializeEvent(cycle, time).call().getTimeline();
|
||||
}
|
||||
// 重置
|
||||
GlobalDataManager.setVariable("timecycle:" + cycle.getName(), String.valueOf(time));
|
||||
// 触发器
|
||||
Bukkit.getPluginManager().callEvent(new TimeCycleEvent(cycle));
|
||||
}
|
||||
}
|
||||
}
|
||||
}.runTaskTimerAsynchronously(Main.getInst(), 0, 20);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package me.skymc.taboolib.update;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import me.skymc.taboolib.Main;
|
||||
import me.skymc.taboolib.TabooLib;
|
||||
import me.skymc.taboolib.fileutils.FileUtils;
|
||||
@@ -14,37 +15,30 @@ import org.bukkit.scheduler.BukkitRunnable;
|
||||
*/
|
||||
public class UpdateTask {
|
||||
|
||||
private static final String API = "https://api.github.com/repos/Bkm016/TabooLib/releases/latest";
|
||||
|
||||
/**
|
||||
* 检测更新
|
||||
*/
|
||||
public UpdateTask() {
|
||||
new BukkitRunnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
if (!Main.getInst().getConfig().getBoolean("UPDATE-CHECK")) {
|
||||
return;
|
||||
}
|
||||
String value = FileUtils.getStringFromURL(API, "{}");
|
||||
JsonObject json = new JsonParser().parse(value).getAsJsonObject();
|
||||
if (json.entrySet().size() > 0) {
|
||||
double newVersion = Double.parseDouble(json.get("tag_name").getAsString());
|
||||
if (TabooLib.getPluginVersion() >= newVersion) {
|
||||
MsgUtils.send("插件已是最新版, 无需更新!");
|
||||
}
|
||||
else {
|
||||
MsgUtils.send("&8####################################################");
|
||||
MsgUtils.send("检测到有新的版本更新!");
|
||||
MsgUtils.send("当前版本: &f" + TabooLib.getPluginVersion());
|
||||
MsgUtils.send("最新版本: &f" + newVersion);
|
||||
MsgUtils.send("下载地址: &fhttp://www.mcbbs.net/thread-773065-1-1.html");
|
||||
MsgUtils.send("开源地址: &fhttps://github.com/Bkm016/TabooLib/");
|
||||
MsgUtils.send("&8####################################################");
|
||||
}
|
||||
}
|
||||
}
|
||||
}.runTaskLaterAsynchronously(Main.getInst(), 100);
|
||||
}
|
||||
private static final String API = "https://internal.github.com/repos/Bkm016/TabooLib/releases/latest";
|
||||
|
||||
/**
|
||||
* 检测更新
|
||||
*/
|
||||
public UpdateTask() {
|
||||
new BukkitRunnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
if (!Main.getInst().getConfig().getBoolean("UPDATE-CHECK")) {
|
||||
return;
|
||||
}
|
||||
String value = FileUtils.getStringFromURL(API, "{}");
|
||||
JsonObject json = new JsonParser().parse(value).getAsJsonObject();
|
||||
if (json.entrySet().size() > 0) {
|
||||
double newVersion = Double.parseDouble(json.get("tag_name").getAsString());
|
||||
if (TabooLib.getPluginVersion() >= newVersion) {
|
||||
TLocale.Logger.info("UPDATETASK.VERSION-LATEST");
|
||||
} else {
|
||||
TLocale.Logger.info("UPDATETASK.VERSION-OUTDATED", String.valueOf(TabooLib.getPluginVersion()), String.valueOf(newVersion));
|
||||
}
|
||||
}
|
||||
}
|
||||
}.runTaskLaterAsynchronously(Main.getInst(), 100);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package me.skymc.tlm;
|
||||
|
||||
import com.ilummc.tlib.resources.TLocale;
|
||||
import me.skymc.taboolib.Main;
|
||||
import me.skymc.taboolib.fileutils.ConfigUtils;
|
||||
import me.skymc.taboolib.message.MsgUtils;
|
||||
import me.skymc.taboolib.string.language2.Language2;
|
||||
import me.skymc.tlm.module.TabooLibraryModule;
|
||||
import me.skymc.tlm.module.sub.ModuleCommandChanger;
|
||||
@@ -46,9 +46,8 @@ public class TLM {
|
||||
|
||||
// 载入模块
|
||||
TabooLibraryModule.getInst().loadModules();
|
||||
|
||||
// 提示
|
||||
MsgUtils.send("载入 &f" + TabooLibraryModule.getInst().getSize() + " &7个 &fTLM &7模块");
|
||||
TLocale.Logger.info("TABOOLIB-MODULE.SUCCESS-LOADED", String.valueOf(TabooLibraryModule.getInst().getSize()));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -80,12 +79,7 @@ public class TLM {
|
||||
*/
|
||||
public void reloadConfig() {
|
||||
config = ConfigUtils.saveDefaultConfig(Main.getInst(), "module.yml");
|
||||
// 载入语言文件
|
||||
try {
|
||||
language = new Language2(config.getString("Language"), Main.getInst());
|
||||
} catch (Exception e) {
|
||||
MsgUtils.warn("语言文件不存在: &4" + config.getString("Language"));
|
||||
}
|
||||
language = new Language2(config.getString("Language"), Main.getInst());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -97,4 +91,12 @@ public class TLM {
|
||||
public boolean isEnableModule(String name) {
|
||||
return config.getStringList("EnableModule").contains(name);
|
||||
}
|
||||
|
||||
public void loadedFall(String moduleName, String result, String location) {
|
||||
TLocale.Logger.error("TABOOLIB-MODULE.FALL-LOADED", moduleName, result, location);
|
||||
}
|
||||
|
||||
public void runtimeFall(String moduleName, String result, String location) {
|
||||
TLocale.Logger.error("TABOOLIB-MODULE.FALL-RUNTIME", moduleName, result, location);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ public class TLMCommands implements CommandExecutor {
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, Command arg1, String arg2, String[] args) {
|
||||
if (args.length == 0 || args[0].equalsIgnoreCase("help")) {
|
||||
if (args.length == 0 || "help".equalsIgnoreCase(args[0])) {
|
||||
if (sender.hasPermission("taboolib.admin")) {
|
||||
TLM.getInst().getLanguage().get("COMMAND-HELP").send(sender);
|
||||
} else {
|
||||
@@ -26,7 +26,7 @@ public class TLMCommands implements CommandExecutor {
|
||||
}
|
||||
|
||||
// 重载
|
||||
else if (args[0].equalsIgnoreCase("reload")) {
|
||||
else if ("reload".equalsIgnoreCase(args[0])) {
|
||||
if (sender.hasPermission("taboolib.admin")) {
|
||||
new TLMReloadCommand(sender, args);
|
||||
} else {
|
||||
@@ -35,7 +35,7 @@ public class TLMCommands implements CommandExecutor {
|
||||
}
|
||||
|
||||
// 列出
|
||||
else if (args[0].equalsIgnoreCase("list")) {
|
||||
else if ("list".equalsIgnoreCase(args[0])) {
|
||||
if (sender.hasPermission("taboolib.admin")) {
|
||||
new TLMListCommand(sender, args);
|
||||
} else {
|
||||
@@ -44,7 +44,7 @@ public class TLMCommands implements CommandExecutor {
|
||||
}
|
||||
|
||||
// InventorySave 模块
|
||||
else if (args[0].equalsIgnoreCase("inv")) {
|
||||
else if ("inv".equalsIgnoreCase(args[0])) {
|
||||
if (sender.hasPermission("taboolib.admin")) {
|
||||
new TLMInvCommand(sender, args);
|
||||
} else {
|
||||
@@ -53,7 +53,7 @@ public class TLMCommands implements CommandExecutor {
|
||||
}
|
||||
|
||||
// Kit 模块
|
||||
else if (args[0].equalsIgnoreCase("kit")) {
|
||||
else if ("kit".equalsIgnoreCase(args[0])) {
|
||||
new TLMKitCommand(sender, args);
|
||||
} else {
|
||||
TLM.getInst().getLanguage().get("COMMAND-ERROR").send(sender);
|
||||
|
||||
@@ -43,12 +43,12 @@ public class TLMInvCommand extends SubCommand {
|
||||
}
|
||||
|
||||
// 列出背包
|
||||
else if (args[1].equalsIgnoreCase("list")) {
|
||||
else if ("list".equalsIgnoreCase(args[1])) {
|
||||
TLM.getInst().getLanguage().get("INV-LIST").addPlaceholder("$name", moduleInventorySave.getInventorys().toString()).send(sender);
|
||||
}
|
||||
|
||||
// 查看背包
|
||||
else if (args[1].equalsIgnoreCase("info")) {
|
||||
else if ("info".equalsIgnoreCase(args[1])) {
|
||||
// 如果是后台
|
||||
if (!(sender instanceof Player)) {
|
||||
TLM.getInst().getLanguage().get("INV-CONSOLE").send(sender);
|
||||
@@ -108,7 +108,7 @@ public class TLMInvCommand extends SubCommand {
|
||||
}
|
||||
|
||||
// 保存背包
|
||||
else if (args[1].equalsIgnoreCase("save")) {
|
||||
else if ("save".equalsIgnoreCase(args[1])) {
|
||||
// 如果是后台
|
||||
if (!(sender instanceof Player)) {
|
||||
TLM.getInst().getLanguage().get("INV-CONSOLE").send(sender);
|
||||
@@ -132,7 +132,7 @@ public class TLMInvCommand extends SubCommand {
|
||||
}
|
||||
|
||||
// 覆盖背包
|
||||
else if (args[1].equalsIgnoreCase("paste")) {
|
||||
else if ("paste".equalsIgnoreCase(args[1])) {
|
||||
// 判断长度
|
||||
if (args.length < 3) {
|
||||
TLM.getInst().getLanguage().get("INV-NAME").send(sender);
|
||||
@@ -175,7 +175,7 @@ public class TLMInvCommand extends SubCommand {
|
||||
}
|
||||
|
||||
// 删除背包
|
||||
else if (args[1].equalsIgnoreCase("delete")) {
|
||||
else if ("delete".equalsIgnoreCase(args[1])) {
|
||||
// 判断长度
|
||||
if (args.length < 3) {
|
||||
TLM.getInst().getLanguage().get("INV-NAME").send(sender);
|
||||
|
||||
@@ -38,7 +38,7 @@ public class TLMKitCommand extends SubCommand {
|
||||
TLM.getInst().getLanguage().get("KIT-EMPTY").send(sender);
|
||||
}
|
||||
|
||||
else if (args[1].equalsIgnoreCase("list")) {
|
||||
else if ("list".equalsIgnoreCase(args[1])) {
|
||||
// 判断权限
|
||||
if (!sender.hasPermission("taboolib.kit.list")) {
|
||||
TLM.getInst().getLanguage().get("NOPERMISSION-KIT-LIST").send(sender);
|
||||
@@ -50,7 +50,7 @@ public class TLMKitCommand extends SubCommand {
|
||||
}
|
||||
}
|
||||
|
||||
else if (args[1].equalsIgnoreCase("reward")) {
|
||||
else if ("reward".equalsIgnoreCase(args[1])) {
|
||||
// 判断权限
|
||||
if (!sender.hasPermission("taboolib.kit.reward")) {
|
||||
TLM.getInst().getLanguage().get("NOPERMISSION-KIT-REWARD").send(sender);
|
||||
@@ -130,7 +130,7 @@ public class TLMKitCommand extends SubCommand {
|
||||
// 提示信息
|
||||
TLM.getInst().getLanguage().get("KIT-SUCCESS").addPlaceholder("$kit", args[2]).send(sender);
|
||||
}
|
||||
else if (args[1].equalsIgnoreCase("reset")) {
|
||||
else if ("reset".equalsIgnoreCase(args[1])) {
|
||||
// 判断权限
|
||||
if (!sender.hasPermission("taboolib.kit.reset")) {
|
||||
TLM.getInst().getLanguage().get("NOPERMISSION-KIT-RESET").send(sender);
|
||||
|
||||
@@ -24,12 +24,12 @@ public class TLMReloadCommand extends SubCommand {
|
||||
MsgUtils.send(sender, "&4参数错误。");
|
||||
}
|
||||
|
||||
else if (args[1].equalsIgnoreCase("tlm")) {
|
||||
else if ("tlm".equalsIgnoreCase(args[1])) {
|
||||
TLM.getInst().reloadConfig();
|
||||
MsgUtils.send(sender, "&fTLM &7配置文件已重载。");
|
||||
}
|
||||
|
||||
else if (args[1].equalsIgnoreCase("all")) {
|
||||
else if ("all".equalsIgnoreCase(args[1])) {
|
||||
TabooLibraryModule.getInst().reloadConfig();
|
||||
MsgUtils.send(sender, "所有模块配置文件已重载。");
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ public class ModuleCommandChanger implements ITabooLibraryModule, Listener {
|
||||
// 判断命令
|
||||
if (e.getMessage().startsWith(key)) {
|
||||
// 判断执行方式
|
||||
if (!getConfig().contains("Commands." + id + ".ReplaceMode") || getConfig().getString("Commands." + id + ".ReplaceMode").equals("PLAYER")) {
|
||||
if (!getConfig().contains("Commands." + id + ".ReplaceMode") || "PLAYER".equals(getConfig().getString("Commands." + id + ".ReplaceMode"))) {
|
||||
// 替换命令
|
||||
e.setMessage(e.getMessage().replace(key, getConfig().getString("Commands." + id + ".Replace")));
|
||||
return;
|
||||
@@ -45,7 +45,7 @@ public class ModuleCommandChanger implements ITabooLibraryModule, Listener {
|
||||
// 判断命令
|
||||
if (e.getCommand().startsWith(key)) {
|
||||
// 判断执行方式
|
||||
if (!getConfig().contains("Commands." + id + ".ReplaceMode") || getConfig().getString("Commands." + id + ".ReplaceMode").equals("CONSOLE")) {
|
||||
if (!getConfig().contains("Commands." + id + ".ReplaceMode") || "CONSOLE".equals(getConfig().getString("Commands." + id + ".ReplaceMode"))) {
|
||||
// 替换命令
|
||||
e.setCommand(e.getCommand().replace(key, getConfig().getString("Commands." + id + ".Replace")));
|
||||
return;
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
package me.skymc.tlm.module.sub;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import me.skymc.taboolib.Main;
|
||||
import me.skymc.taboolib.TabooLib;
|
||||
import me.skymc.taboolib.inventory.ItemUtils;
|
||||
import me.skymc.taboolib.playerdata.DataUtils;
|
||||
import me.skymc.tlm.TLM;
|
||||
import me.skymc.tlm.annotation.DisableConfig;
|
||||
import me.skymc.tlm.inventory.TLMInventoryHolder;
|
||||
import me.skymc.tlm.module.ITabooLibraryModule;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
@@ -13,14 +16,10 @@ import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import me.skymc.taboolib.Main;
|
||||
import me.skymc.taboolib.TabooLib;
|
||||
import me.skymc.taboolib.inventory.ItemUtils;
|
||||
import me.skymc.taboolib.message.MsgUtils;
|
||||
import me.skymc.taboolib.playerdata.DataUtils;
|
||||
import me.skymc.tlm.annotation.DisableConfig;
|
||||
import me.skymc.tlm.inventory.TLMInventoryHolder;
|
||||
import me.skymc.tlm.module.ITabooLibraryModule;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @author sky
|
||||
@@ -28,158 +27,148 @@ import me.skymc.tlm.module.ITabooLibraryModule;
|
||||
*/
|
||||
@DisableConfig
|
||||
public class ModuleInventorySave implements ITabooLibraryModule, Listener {
|
||||
|
||||
private FileConfiguration conf;
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "InventorySave";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
reloadConfig();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onReload() {
|
||||
reloadConfig();
|
||||
}
|
||||
|
||||
public void reloadConfig() {
|
||||
conf = DataUtils.addPluginData("InventorySave", Main.getInst());
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存玩家背包
|
||||
*
|
||||
* @param player 玩家
|
||||
* @param name 名称
|
||||
*/
|
||||
public void saveInventory(Player player, String name) {
|
||||
// 设置物品
|
||||
for (int i = 0 ; i < (TabooLib.getVerint() > 10800 ? 41 : 40) ; i++) {
|
||||
ItemStack item = player.getInventory().getItem(i);
|
||||
conf.set(name + "." + i, item == null ? new ItemStack(Material.AIR) : item.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 覆盖玩家背包
|
||||
*
|
||||
* @param player 玩家
|
||||
* @param name 名称
|
||||
*/
|
||||
public void pasteInventory(Player player, String name) {
|
||||
pasteInventory(player, name, "null");
|
||||
}
|
||||
|
||||
/**
|
||||
* 覆盖玩家背包
|
||||
*
|
||||
* @param player 玩家
|
||||
* @param name 名称
|
||||
* @param module 模式
|
||||
*/
|
||||
public void pasteInventory(Player player, String name, String module) {
|
||||
// 如果背包不存在
|
||||
if (!conf.contains(name)) {
|
||||
MsgUtils.warn("模块执行异常: &4背包不存在");
|
||||
MsgUtils.warn("模块: &4InventorySave");
|
||||
MsgUtils.warn("位于: &4" + name);
|
||||
return;
|
||||
}
|
||||
// 异常物品
|
||||
List<ItemStack> otherItem = new ArrayList<>();
|
||||
// 设置物品
|
||||
for (int i = 0 ; i < (TabooLib.getVerint() > 10800 ? 41 : 40) ; i++) {
|
||||
try {
|
||||
ItemStack item = (ItemStack) conf.get(name + "." + i);
|
||||
// 如果原本有物品
|
||||
if (!ItemUtils.isNull(player.getInventory().getItem(i))) {
|
||||
// 跳过
|
||||
if (module.equalsIgnoreCase("-b")) {
|
||||
continue;
|
||||
}
|
||||
// 给予
|
||||
else if (module.equalsIgnoreCase("-a")) {
|
||||
otherItem.add(item);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// 覆盖
|
||||
player.getInventory().setItem(i, item);
|
||||
}
|
||||
catch (Exception e) {
|
||||
MsgUtils.warn("模块执行异常: &4物品覆盖出错");
|
||||
MsgUtils.warn("模块: &4InventorySave");
|
||||
MsgUtils.warn("位于: &4" + name + ":" + i);
|
||||
}
|
||||
}
|
||||
// 循环异常物品
|
||||
for (ItemStack item : otherItem) {
|
||||
player.getInventory().addItem(item);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取背包内所有物品
|
||||
*
|
||||
* @param name 背包名称
|
||||
* @return {@link List}
|
||||
*/
|
||||
public List<ItemStack> getItems(String name) {
|
||||
// 如果背包不存在
|
||||
if (!conf.contains(name)) {
|
||||
MsgUtils.warn("模块执行异常: &4背包不存在");
|
||||
MsgUtils.warn("模块: &4InventorySave");
|
||||
MsgUtils.warn("位于: &4" + name);
|
||||
return new LinkedList<>();
|
||||
}
|
||||
|
||||
List<ItemStack> items = new LinkedList<>();
|
||||
// 设置物品
|
||||
for (int i = 0 ; i < (TabooLib.getVerint() > 10800 ? 41 : 40) ; i++) {
|
||||
try {
|
||||
ItemStack item = (ItemStack) conf.get(name + "." + i);
|
||||
items.add(item);
|
||||
}
|
||||
catch (Exception e) {
|
||||
MsgUtils.warn("模块执行异常: &4物品获取出错");
|
||||
MsgUtils.warn("模块: &4InventorySave");
|
||||
MsgUtils.warn("位于: &4" + name + ":" + i);
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有背包
|
||||
*
|
||||
* @return {@link Set}
|
||||
*/
|
||||
public Set<String> getInventorys() {
|
||||
return conf.getConfigurationSection("").getKeys(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除背包
|
||||
*
|
||||
* @param name 名称
|
||||
*/
|
||||
public void deleteInventory(String name) {
|
||||
conf.set(name, null);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onClick(InventoryClickEvent e) {
|
||||
if (!(e.getInventory().getHolder() instanceof TLMInventoryHolder)) {
|
||||
return;
|
||||
}
|
||||
|
||||
TLMInventoryHolder holder = (TLMInventoryHolder) e.getInventory().getHolder();
|
||||
if (holder.getModule().equals(getName())) {
|
||||
e.setCancelled(true);
|
||||
}
|
||||
}
|
||||
private FileConfiguration conf;
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "InventorySave";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
reloadConfig();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onReload() {
|
||||
reloadConfig();
|
||||
}
|
||||
|
||||
public void reloadConfig() {
|
||||
conf = DataUtils.addPluginData("InventorySave", Main.getInst());
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存玩家背包
|
||||
*
|
||||
* @param player 玩家
|
||||
* @param name 名称
|
||||
*/
|
||||
public void saveInventory(Player player, String name) {
|
||||
// 设置物品
|
||||
for (int i = 0; i < (TabooLib.getVerint() > 10800 ? 41 : 40); i++) {
|
||||
ItemStack item = player.getInventory().getItem(i);
|
||||
conf.set(name + "." + i, item == null ? new ItemStack(Material.AIR) : item.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 覆盖玩家背包
|
||||
*
|
||||
* @param player 玩家
|
||||
* @param name 名称
|
||||
*/
|
||||
public void pasteInventory(Player player, String name) {
|
||||
pasteInventory(player, name, "null");
|
||||
}
|
||||
|
||||
/**
|
||||
* 覆盖玩家背包
|
||||
*
|
||||
* @param player 玩家
|
||||
* @param name 名称
|
||||
* @param module 模式
|
||||
*/
|
||||
public void pasteInventory(Player player, String name, String module) {
|
||||
// 如果背包不存在
|
||||
if (!conf.contains(name)) {
|
||||
TLM.getInst().runtimeFall("InventorySave", "InventoryNotFound", name);
|
||||
return;
|
||||
}
|
||||
// 异常物品
|
||||
List<ItemStack> otherItem = new ArrayList<>();
|
||||
// 设置物品
|
||||
for (int i = 0; i < (TabooLib.getVerint() > 10800 ? 41 : 40); i++) {
|
||||
try {
|
||||
ItemStack item = (ItemStack) conf.get(name + "." + i);
|
||||
// 如果原本有物品
|
||||
if (!ItemUtils.isNull(player.getInventory().getItem(i))) {
|
||||
// 跳过
|
||||
if ("-b".equalsIgnoreCase(module)) {
|
||||
continue;
|
||||
}
|
||||
// 给予
|
||||
else if ("-a".equalsIgnoreCase(module)) {
|
||||
otherItem.add(item);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// 覆盖
|
||||
player.getInventory().setItem(i, item);
|
||||
} catch (Exception e) {
|
||||
TLM.getInst().runtimeFall("InventorySave", "InventoryCoverFall", name);
|
||||
}
|
||||
}
|
||||
// 循环异常物品
|
||||
for (ItemStack item : otherItem) {
|
||||
player.getInventory().addItem(item);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取背包内所有物品
|
||||
*
|
||||
* @param name 背包名称
|
||||
* @return {@link List}
|
||||
*/
|
||||
public List<ItemStack> getItems(String name) {
|
||||
// 如果背包不存在
|
||||
if (!conf.contains(name)) {
|
||||
TLM.getInst().runtimeFall("InventorySave", "InventoryNotFound", name);
|
||||
return new LinkedList<>();
|
||||
}
|
||||
|
||||
List<ItemStack> items = new LinkedList<>();
|
||||
// 设置物品
|
||||
for (int i = 0; i < (TabooLib.getVerint() > 10800 ? 41 : 40); i++) {
|
||||
try {
|
||||
ItemStack item = (ItemStack) conf.get(name + "." + i);
|
||||
items.add(item);
|
||||
} catch (Exception e) {
|
||||
TLM.getInst().runtimeFall("InventorySave", "ItemStackLoadFall", name);
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有背包
|
||||
*
|
||||
* @return {@link Set}
|
||||
*/
|
||||
public Set<String> getInventorys() {
|
||||
return conf.getConfigurationSection("").getKeys(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除背包
|
||||
*
|
||||
* @param name 名称
|
||||
*/
|
||||
public void deleteInventory(String name) {
|
||||
conf.set(name, null);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onClick(InventoryClickEvent e) {
|
||||
if (!(e.getInventory().getHolder() instanceof TLMInventoryHolder)) {
|
||||
return;
|
||||
}
|
||||
|
||||
TLMInventoryHolder holder = (TLMInventoryHolder) e.getInventory().getHolder();
|
||||
if (holder.getModule().equals(getName())) {
|
||||
e.setCancelled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,169 +1,166 @@
|
||||
package me.skymc.tlm.module.sub;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import me.skymc.taboolib.inventory.ItemUtils;
|
||||
import me.skymc.taboolib.other.DateUtils;
|
||||
import me.skymc.taboolib.other.NumberUtils;
|
||||
import me.skymc.taboolib.playerdata.DataUtils;
|
||||
import me.skymc.tlm.TLM;
|
||||
import me.skymc.tlm.module.ITabooLibraryModule;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import me.skymc.taboolib.inventory.ItemUtils;
|
||||
import me.skymc.taboolib.message.MsgUtils;
|
||||
import me.skymc.taboolib.other.DateUtils;
|
||||
import me.skymc.taboolib.other.NumberUtils;
|
||||
import me.skymc.taboolib.playerdata.DataUtils;
|
||||
import me.skymc.tlm.module.ITabooLibraryModule;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author sky
|
||||
* @since 2018年2月18日 下午12:13:55
|
||||
*/
|
||||
public class ModuleKits implements ITabooLibraryModule {
|
||||
|
||||
private FileConfiguration data;
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "Kits";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
data = DataUtils.addPluginData("ModuleKits", null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置玩家是否领取礼包
|
||||
*
|
||||
* @param player 玩家
|
||||
*/
|
||||
public void setPlayerReward(Player player, String kit, boolean reward) {
|
||||
data.set(kit + "." + player.getName(), reward ? System.currentTimeMillis() : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空礼包数据
|
||||
*
|
||||
* @param kit 礼包
|
||||
*/
|
||||
public void resetKit(String kit) {
|
||||
data.set(kit, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 玩家是否领取礼包
|
||||
*
|
||||
* @param player 玩家
|
||||
* @param kit 礼包
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean isPlayerRewared(Player player, String kit) {
|
||||
return data.contains(kit + "." + player.getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* 礼包是否在冷却中
|
||||
*
|
||||
* @param player
|
||||
* @param kit
|
||||
* @return
|
||||
*/
|
||||
public boolean isPlayerCooldown(Player player, String kit) {
|
||||
return System.currentTimeMillis() - data.getLong(kit + "." + player.getName()) < getCooldown(kit);
|
||||
}
|
||||
|
||||
/**
|
||||
* 礼包是否存在
|
||||
*
|
||||
* @param kit 礼包名
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean contains(String kit) {
|
||||
return getConfig().contains("Kits." + kit);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取礼包冷却时间
|
||||
*
|
||||
* @param kit 礼包名
|
||||
* @return long
|
||||
*/
|
||||
public long getCooldown(String kit) {
|
||||
return DateUtils.formatDate(getConfig().getString("Kits." + kit + ".Cooldown"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取礼包空间不足时的处理方式
|
||||
*
|
||||
* @param kit 礼包名
|
||||
* @return boolean
|
||||
*/
|
||||
public Boolean isFullDrop(String kit) {
|
||||
return getConfig().getBoolean("Kits." + kit + ".FullDrop");
|
||||
}
|
||||
|
||||
/**
|
||||
* 礼包是否只能领取一次
|
||||
*
|
||||
* @param kit 礼包名
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean isDisposable(String kit) {
|
||||
return getConfig().getBoolean("Kits." + kit + ".Disposable");
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取礼包权限
|
||||
*
|
||||
* @param kit 礼包名
|
||||
* @return String
|
||||
*/
|
||||
public String getPermission(String kit) {
|
||||
return getConfig().getString("Kits." + kit + ".Permission");
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取礼包权限提示
|
||||
*
|
||||
* @param kit 礼包名
|
||||
* @return String
|
||||
*/
|
||||
public String getPermissionMessage(String kit) {
|
||||
return getConfig().getString("Kits." + kit + ".Permission-message").replace("&", "§");
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取礼包物品
|
||||
*
|
||||
* @param kit 礼包名
|
||||
* @return {@link List}
|
||||
*/
|
||||
public List<ItemStack> getItems(String kit) {
|
||||
List<ItemStack> items = new ArrayList<>();
|
||||
for (String itemStr : getConfig().getStringList("Kits." + kit + ".Items")) {
|
||||
ItemStack item = ItemUtils.getCacheItem(itemStr.split(" ")[0]);
|
||||
if (item != null) {
|
||||
item = item.clone();
|
||||
try {
|
||||
item.setAmount(NumberUtils.getInteger(itemStr.split(" ")[1]));
|
||||
items.add(item);
|
||||
} catch (Exception e) {
|
||||
MsgUtils.warn("模块配置载入异常: &4物品数量错误");
|
||||
MsgUtils.warn("模块: &4Kits");
|
||||
MsgUtils.warn("位于: &4" + itemStr);
|
||||
}
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取礼包命令
|
||||
*
|
||||
* @param kit 礼包名
|
||||
* @return {@link List}
|
||||
*/
|
||||
public List<String> getCommands(String kit) {
|
||||
return getConfig().contains("Kits." + kit + ".Commands") ? getConfig().getStringList("Kits." + kit + ".Commands") : new ArrayList<>();
|
||||
}
|
||||
private FileConfiguration data;
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "Kits";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
data = DataUtils.addPluginData("ModuleKits", null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置玩家是否领取礼包
|
||||
*
|
||||
* @param player 玩家
|
||||
*/
|
||||
public void setPlayerReward(Player player, String kit, boolean reward) {
|
||||
data.set(kit + "." + player.getName(), reward ? System.currentTimeMillis() : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空礼包数据
|
||||
*
|
||||
* @param kit 礼包
|
||||
*/
|
||||
public void resetKit(String kit) {
|
||||
data.set(kit, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 玩家是否领取礼包
|
||||
*
|
||||
* @param player 玩家
|
||||
* @param kit 礼包
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean isPlayerRewared(Player player, String kit) {
|
||||
return data.contains(kit + "." + player.getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* 礼包是否在冷却中
|
||||
*
|
||||
* @param player
|
||||
* @param kit
|
||||
* @return
|
||||
*/
|
||||
public boolean isPlayerCooldown(Player player, String kit) {
|
||||
return System.currentTimeMillis() - data.getLong(kit + "." + player.getName()) < getCooldown(kit);
|
||||
}
|
||||
|
||||
/**
|
||||
* 礼包是否存在
|
||||
*
|
||||
* @param kit 礼包名
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean contains(String kit) {
|
||||
return getConfig().contains("Kits." + kit);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取礼包冷却时间
|
||||
*
|
||||
* @param kit 礼包名
|
||||
* @return long
|
||||
*/
|
||||
public long getCooldown(String kit) {
|
||||
return DateUtils.formatDate(getConfig().getString("Kits." + kit + ".Cooldown"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取礼包空间不足时的处理方式
|
||||
*
|
||||
* @param kit 礼包名
|
||||
* @return boolean
|
||||
*/
|
||||
public Boolean isFullDrop(String kit) {
|
||||
return getConfig().getBoolean("Kits." + kit + ".FullDrop");
|
||||
}
|
||||
|
||||
/**
|
||||
* 礼包是否只能领取一次
|
||||
*
|
||||
* @param kit 礼包名
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean isDisposable(String kit) {
|
||||
return getConfig().getBoolean("Kits." + kit + ".Disposable");
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取礼包权限
|
||||
*
|
||||
* @param kit 礼包名
|
||||
* @return String
|
||||
*/
|
||||
public String getPermission(String kit) {
|
||||
return getConfig().getString("Kits." + kit + ".Permission");
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取礼包权限提示
|
||||
*
|
||||
* @param kit 礼包名
|
||||
* @return String
|
||||
*/
|
||||
public String getPermissionMessage(String kit) {
|
||||
return getConfig().getString("Kits." + kit + ".Permission-message").replace("&", "§");
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取礼包物品
|
||||
*
|
||||
* @param kit 礼包名
|
||||
* @return {@link List}
|
||||
*/
|
||||
public List<ItemStack> getItems(String kit) {
|
||||
List<ItemStack> items = new ArrayList<>();
|
||||
for (String itemStr : getConfig().getStringList("Kits." + kit + ".Items")) {
|
||||
ItemStack item = ItemUtils.getCacheItem(itemStr.split(" ")[0]);
|
||||
if (item != null) {
|
||||
item = item.clone();
|
||||
try {
|
||||
item.setAmount(NumberUtils.getInteger(itemStr.split(" ")[1]));
|
||||
items.add(item);
|
||||
} catch (Exception e) {
|
||||
TLM.getInst().runtimeFall("Kits", "InvalidAmount", itemStr);
|
||||
}
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取礼包命令
|
||||
*
|
||||
* @param kit 礼包名
|
||||
* @return {@link List}
|
||||
*/
|
||||
public List<String> getCommands(String kit) {
|
||||
return getConfig().contains("Kits." + kit + ".Commands") ? getConfig().getStringList("Kits." + kit + ".Commands") : new ArrayList<>();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,112 +1,109 @@
|
||||
package me.skymc.tlm.module.sub;
|
||||
|
||||
import java.util.Calendar;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
|
||||
import me.skymc.taboolib.Main;
|
||||
import me.skymc.taboolib.message.MsgUtils;
|
||||
import me.skymc.taboolib.other.DateUtils;
|
||||
import me.skymc.taboolib.other.NumberUtils;
|
||||
import me.skymc.taboolib.timecycle.TimeCycle;
|
||||
import me.skymc.taboolib.timecycle.TimeCycleEvent;
|
||||
import me.skymc.taboolib.timecycle.TimeCycleInitializeEvent;
|
||||
import me.skymc.taboolib.timecycle.TimeCycleManager;
|
||||
import me.skymc.tlm.TLM;
|
||||
import me.skymc.tlm.module.ITabooLibraryModule;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
|
||||
import java.util.Calendar;
|
||||
|
||||
/**
|
||||
* @author sky
|
||||
* @since 2018年2月17日 下午11:23:38
|
||||
*/
|
||||
public class ModuleTimeCycle implements ITabooLibraryModule, Listener {
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "TimeCycle";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
// 载入检查器
|
||||
loadCycles();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
// 注销检查器
|
||||
unloadCycles();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onReload() {
|
||||
// 注销检查器
|
||||
unloadCycles();
|
||||
// 载入检查器
|
||||
loadCycles();
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onTimeCycleInitialize(TimeCycleInitializeEvent e) {
|
||||
if (e.getCycle().getName().contains("tlm|")) {
|
||||
// 获取名称
|
||||
String name = e.getCycle().getName().replace("tlm|", "");
|
||||
// 如果有初始化时间配置
|
||||
if (getConfig().contains("TimeCycle." + name + ".Initialise.InitialiseDate")) {
|
||||
// 获取时间
|
||||
Calendar date = Calendar.getInstance();
|
||||
// 遍历初始化规则
|
||||
for (String typeStr : getConfig().getStringList("TimeCycle." + name + ".Initialise.InitialiseDate")) {
|
||||
try {
|
||||
int type = (int) Calendar.class.getField(typeStr.split("=")[0]).get(Calendar.class);
|
||||
date.set(type, NumberUtils.getInteger(typeStr.split("=")[1]));
|
||||
} catch (Exception err) {
|
||||
MsgUtils.warn("模块配置载入异常: &4日期类型错误");
|
||||
MsgUtils.warn("模块: &4TimeCycle");
|
||||
MsgUtils.warn("位于: &4" + typeStr);
|
||||
}
|
||||
}
|
||||
e.setTimeLine(date.getTimeInMillis());
|
||||
}
|
||||
// 如果有初始化命令
|
||||
if (getConfig().contains("TimeCycle." + name + ".Initialise.InitialiseCommand")) {
|
||||
// 遍历初始化命令
|
||||
for (String command : getConfig().getStringList("TimeCycle." + name + ".Initialise.InitialiseCommand")) {
|
||||
// 执行命令
|
||||
Bukkit.getScheduler().runTask(Main.getInst(), () -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onTimeCycle(TimeCycleEvent e) {
|
||||
if (e.getCycle().getName().contains("tlm|")) {
|
||||
// 获取名称
|
||||
String name = e.getCycle().getName().replace("tlm|", "");
|
||||
// 如果有更新命令
|
||||
if (getConfig().contains("TimeCycle." + name + ".UpdateCommand")) {
|
||||
// 遍历更新命令
|
||||
for (String command : getConfig().getStringList("TimeCycle." + name + ".UpdateCommand")) {
|
||||
// 执行命令
|
||||
Bukkit.getScheduler().runTask(Main.getInst(), () -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void loadCycles() {
|
||||
for (String name : getConfig().getConfigurationSection("TimeCycle").getKeys(false)) {
|
||||
TimeCycleManager.register(new TimeCycle("tlm|" + name, DateUtils.formatDate(getConfig().getString("TimeCycle." + name + ".Cycle")), Main.getInst()));
|
||||
}
|
||||
}
|
||||
|
||||
private void unloadCycles() {
|
||||
for (TimeCycle cycle : TimeCycleManager.getTimeCycles()) {
|
||||
if (cycle.getName().startsWith("tlm|")) {
|
||||
TimeCycleManager.cancel(cycle.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "TimeCycle";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
// 载入检查器
|
||||
loadCycles();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
// 注销检查器
|
||||
unloadCycles();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onReload() {
|
||||
// 注销检查器
|
||||
unloadCycles();
|
||||
// 载入检查器
|
||||
loadCycles();
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onTimeCycleInitialize(TimeCycleInitializeEvent e) {
|
||||
if (e.getCycle().getName().contains("tlm|")) {
|
||||
// 获取名称
|
||||
String name = e.getCycle().getName().replace("tlm|", "");
|
||||
// 如果有初始化时间配置
|
||||
if (getConfig().contains("TimeCycle." + name + ".Initialise.InitialiseDate")) {
|
||||
// 获取时间
|
||||
Calendar date = Calendar.getInstance();
|
||||
// 遍历初始化规则
|
||||
for (String typeStr : getConfig().getStringList("TimeCycle." + name + ".Initialise.InitialiseDate")) {
|
||||
try {
|
||||
int type = (int) Calendar.class.getField(typeStr.split("=")[0]).get(Calendar.class);
|
||||
date.set(type, NumberUtils.getInteger(typeStr.split("=")[1]));
|
||||
} catch (Exception ignored) {
|
||||
TLM.getInst().runtimeFall("TimeCycle", "DateFormatFall", typeStr);
|
||||
}
|
||||
}
|
||||
e.setTimeLine(date.getTimeInMillis());
|
||||
}
|
||||
// 如果有初始化命令
|
||||
if (getConfig().contains("TimeCycle." + name + ".Initialise.InitialiseCommand")) {
|
||||
// 遍历初始化命令
|
||||
for (String command : getConfig().getStringList("TimeCycle." + name + ".Initialise.InitialiseCommand")) {
|
||||
// 执行命令
|
||||
Bukkit.getScheduler().runTask(Main.getInst(), () -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onTimeCycle(TimeCycleEvent e) {
|
||||
if (e.getCycle().getName().contains("tlm|")) {
|
||||
// 获取名称
|
||||
String name = e.getCycle().getName().replace("tlm|", "");
|
||||
// 如果有更新命令
|
||||
if (getConfig().contains("TimeCycle." + name + ".UpdateCommand")) {
|
||||
// 遍历更新命令
|
||||
for (String command : getConfig().getStringList("TimeCycle." + name + ".UpdateCommand")) {
|
||||
// 执行命令
|
||||
Bukkit.getScheduler().runTask(Main.getInst(), () -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void loadCycles() {
|
||||
for (String name : getConfig().getConfigurationSection("TimeCycle").getKeys(false)) {
|
||||
TimeCycleManager.register(new TimeCycle("tlm|" + name, DateUtils.formatDate(getConfig().getString("TimeCycle." + name + ".Cycle")), Main.getInst()));
|
||||
}
|
||||
}
|
||||
|
||||
private void unloadCycles() {
|
||||
for (TimeCycle cycle : TimeCycleManager.getTimeCycles()) {
|
||||
if (cycle.getName().startsWith("tlm|")) {
|
||||
TimeCycleManager.cancel(cycle.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user