master
坏黑 2018-05-07 14:43:57 +08:00
parent 7181c487f9
commit 6f34cbc2e0
152 changed files with 9256 additions and 9003 deletions

137
TabooLib.iml Normal file
View File

@ -0,0 +1,137 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: com.zaxxer:HikariCP:3.1.0" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.25" level="project" />
<orderEntry type="library" name="Maven: com.ilummc.eagletdl:EagletCore:1.1.2" level="project" />
<orderEntry type="library" name="Maven: org.ow2.asm:asm:6.1.1" level="project" />
<orderEntry type="module-library">
<library name="Maven: bukkit:bukkit1_12:1">
<CLASSES>
<root url="jar://$MODULE_DIR$/libs/1_12_R1.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="library" name="Maven: net.milkbowl.vault:VaultAPI:1.6" level="project" />
<orderEntry type="library" name="Maven: org.bukkit:bukkit:1.9-R0.1-SNAPSHOT" level="project" />
<orderEntry type="library" name="Maven: commons-lang:commons-lang:2.6" level="project" />
<orderEntry type="library" name="Maven: com.googlecode.json-simple:json-simple:1.1.1" level="project" />
<orderEntry type="library" name="Maven: junit:junit:4.10" level="project" />
<orderEntry type="library" name="Maven: org.hamcrest:hamcrest-core:1.1" level="project" />
<orderEntry type="library" name="Maven: com.google.guava:guava:17.0" level="project" />
<orderEntry type="library" name="Maven: com.google.code.gson:gson:2.2.4" level="project" />
<orderEntry type="library" name="Maven: org.avaje:ebean:2.8.1" level="project" />
<orderEntry type="library" name="Maven: javax.persistence:persistence-api:1.0" level="project" />
<orderEntry type="library" name="Maven: org.yaml:snakeyaml:1.15" level="project" />
<orderEntry type="module-library">
<library name="Maven: bukkit:bukkit1_8:1">
<CLASSES>
<root url="jar://$MODULE_DIR$/libs/1_8_R3.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="Maven: bukkit:bukkit1_9:1">
<CLASSES>
<root url="jar://$MODULE_DIR$/libs/1_9_R3.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="Maven: bukkit:bukkit1_10:1">
<CLASSES>
<root url="jar://$MODULE_DIR$/libs/1_10_R1.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="Maven: bukkit:bukkit1_11:1">
<CLASSES>
<root url="jar://$MODULE_DIR$/libs/1_11_R1.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="Maven: com.sun.tools:jshell:1">
<CLASSES>
<root url="jar://$MODULE_DIR$/libs/com.sun.tools.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="Maven: placeholder:placeholder:1">
<CLASSES>
<root url="jar://$MODULE_DIR$/libs/PlaceholderAPI.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="Maven: plib:plib:1">
<CLASSES>
<root url="jar://$MODULE_DIR$/libs/ProtocolLib.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="Maven: sk:sk:1">
<CLASSES>
<root url="jar://$MODULE_DIR$/libs/Skript.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="Maven: taboocode:taboocode:1">
<CLASSES>
<root url="jar://$MODULE_DIR$/libs/TabooCode5.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="Maven: wg:wg:1">
<CLASSES>
<root url="jar://$MODULE_DIR$/libs/WorldGuard.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="Maven: yum:yum:1">
<CLASSES>
<root url="jar://$MODULE_DIR$/libs/Yum.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
</component>
</module>

View File

@ -77,11 +77,6 @@
<artifactId>asm</artifactId>
<version>6.1.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
</dependency>
<dependency>
<groupId>bukkit</groupId>
<artifactId>bukkit1_12</artifactId>

View File

@ -1,12 +1,11 @@
package com.ilummc.tlib;
import com.ilummc.tlib.annotations.TConfig;
import com.ilummc.tlib.bean.Property;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import com.ilummc.tlib.annotations.Config;
import com.ilummc.tlib.bean.Property;
@Config(name = "cfg.yml", charset = "GBK")
@TConfig(name = "cfg.yml", charset = "GBK")
public class ExampleMain extends JavaPlugin {
private Property<Boolean> update = Property.of(false);

View File

@ -11,7 +11,6 @@ import com.ilummc.tlib.logger.TLogger;
import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.resources.TLocaleLoader;
import com.ilummc.tlib.util.IO;
import lombok.Getter;
import me.skymc.taboolib.Main;
import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException;
@ -27,44 +26,40 @@ import java.nio.charset.Charset;
@Dependency(type = Dependency.Type.LIBRARY, maven = "org.slf4j:slf4j-api:1.7.25")
public class TLib {
@Getter
private static TLib tLib;
@Getter
private static YamlConfiguration internalLanguage;
private TLogger logger = new TLogger("§8[§3§lTabooLib§8][§r{1}§8] §f{2}", Main.getInst(), TLogger.FINE);
@Getter
private TLibConfig config;
@Getter
private TConfigWatcher configWatcher = new TConfigWatcher();
@Getter
private File libsFolder;
@Getter
private YamlConfiguration internalLang;
private TLib() {
libsFolder = new File(Main.getInst().getDataFolder(), "/libs");
if (!libsFolder.exists()) {
libsFolder.mkdirs();
}
try {
String yamlText = new String(IO.readFully(TLib.class.getResourceAsStream("/internalLang.yml")), Charset.forName("utf-8"));
internalLang = new YamlConfiguration();
internalLang.loadFromString(yamlText);
String yamlText = new String(IO.readFully(TLib.class.getResourceAsStream("/lang/internal.yml")), Charset.forName("utf-8"));
internalLanguage = new YamlConfiguration();
internalLanguage.loadFromString(yamlText);
} catch (IOException | InvalidConfigurationException ignored) {
}
}
public static TLib getTLib() {
return tLib;
}
public static YamlConfiguration getInternalLanguage() {
return internalLanguage;
}
public static void init() {
tLib = new TLib();
TLoggerFilter.init();
TLocaleLoader.init();
PlaceholderHook.init();
TLocaleLoader.load(Main.getInst(), false);
TDependencyInjector.inject(Main.getInst(), tLib);
}
@ -86,4 +81,20 @@ public class TLib {
TLocale.Logger.fatal("TLIB.INJECTION-FAILED");
}
}
public TLogger getLogger() {
return logger;
}
public TLibConfig getConfig() {
return config;
}
public TConfigWatcher getConfigWatcher() {
return configWatcher;
}
public File getLibsFolder() {
return libsFolder;
}
}

View File

@ -1,29 +0,0 @@
package com.ilummc.tlib.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Modifier;
import com.ilummc.tlib.util.Ref;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Config {
String name() default "config.yml";
boolean fromJar() default false;
boolean saveOnExit() default false;
boolean readOnly() default true;
String charset() default "UTF-8";
boolean listenChanges() default false;
int excludeModifiers() default Modifier.STATIC | Modifier.TRANSIENT | Ref.ACC_SYNTHETIC | Ref.ACC_BRIDGE;
}

View File

@ -5,14 +5,12 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.ilummc.tlib.logger.TLogger;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Logger {
String value() default "[{0}|{1}] {1}";
int level() default TLogger.INFO;
int level() default com.ilummc.tlib.logger.TLogger.INFO;
}

View File

@ -1,16 +1,20 @@
package com.ilummc.tlib.config;
import com.ilummc.tlib.annotations.Config;
import com.ilummc.tlib.annotations.TConfig;
/**
* @author sky
* @since 2018-04-22 14:31:11
*/
@Config(name = "tlib.yml", listenChanges = true, readOnly = false)
@TConfig(name = "tlib.yml", listenChanges = true)
public class TLibConfig {
private boolean enablePlaceholderHookByDefault = false;
public void setEnablePlaceholderHookByDefault(boolean enablePlaceholderHookByDefault) {
this.enablePlaceholderHookByDefault = enablePlaceholderHookByDefault;
}
public boolean isEnablePlaceholderHookByDefault() {
return enablePlaceholderHookByDefault;
}

View File

@ -7,6 +7,7 @@ import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import me.skymc.taboolib.message.MsgUtils;
import org.bukkit.plugin.Plugin;
public class TDependencyLoader {

View File

@ -1,7 +1,7 @@
package com.ilummc.tlib.inject;
import com.google.common.io.Files;
import com.ilummc.tlib.annotations.Config;
import com.ilummc.tlib.annotations.TConfig;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.fileutils.ConfigUtils;
import org.apache.commons.lang3.Validate;
@ -50,7 +50,7 @@ public class TConfigInjector {
public static Object loadConfig(Plugin plugin, Class<?> clazz) {
try {
Config config = clazz.getAnnotation(Config.class);
TConfig config = clazz.getAnnotation(TConfig.class);
Validate.notNull(config);
File file = new File(plugin.getDataFolder(), config.name());
if (!file.exists()) if (config.fromJar()) plugin.saveResource(config.name(), true);
@ -68,7 +68,7 @@ public class TConfigInjector {
public static void reloadConfig(Plugin plugin, Object object) {
try {
Config config = object.getClass().getAnnotation(Config.class);
TConfig config = object.getClass().getAnnotation(TConfig.class);
Validate.notNull(config);
File file = new File(plugin.getDataFolder(), config.name());
Map<String, Object> map = ConfigUtils.confToMap(ConfigUtils.loadYaml(plugin, file));
@ -83,7 +83,7 @@ public class TConfigInjector {
public static Object unserialize(Plugin plugin, Class<?> clazz) {
try {
Config config = clazz.getAnnotation(Config.class);
TConfig config = clazz.getAnnotation(TConfig.class);
Validate.notNull(config);
return ConfigUtils.confToObj(
ConfigUtils.mapToConf(
@ -104,7 +104,7 @@ public class TConfigInjector {
public static Map<String, Object> serialize(Plugin plugin, Object object) {
try {
Config config = object.getClass().getAnnotation(Config.class);
TConfig config = object.getClass().getAnnotation(TConfig.class);
Validate.notNull(config);
return ConfigUtils.objToConf(object).getValues(false);
} catch (NullPointerException e) {
@ -116,7 +116,7 @@ public class TConfigInjector {
}
public static void saveConfig(Plugin plugin, Object object) throws IOException, NullPointerException {
Config config = object.getClass().getAnnotation(Config.class);
TConfig config = object.getClass().getAnnotation(TConfig.class);
Validate.notNull(config);
Object obj = serialize(plugin, object);
Validate.notNull(obj);

View File

@ -3,10 +3,10 @@ package com.ilummc.tlib.inject;
import com.ilummc.tlib.TLib;
import com.ilummc.tlib.annotations.*;
import com.ilummc.tlib.dependency.TDependency;
import com.ilummc.tlib.logger.TLogger;
import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.resources.TLocaleLoader;
import com.ilummc.tlib.util.Ref;
import me.skymc.taboolib.Main;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
@ -17,15 +17,17 @@ import java.lang.reflect.Field;
public class TDependencyInjector {
public static void inject(Plugin plugin, Object o) {
TLocaleLoader.load(plugin, true);
injectDependencies(plugin, o);
injectLogger(plugin, o);
injectConfig(plugin, o);
injectPluginInstance(plugin, o);
TLocaleLoader.load(plugin, true);
}
static void injectOnEnable(Plugin plugin) {
inject(plugin, plugin);
if (!plugin.equals(Main.getInst())) {
inject(plugin, plugin);
}
}
static void onDisable(Plugin plugin) {
@ -41,8 +43,8 @@ public class TDependencyInjector {
private static void ejectConfig(Plugin plugin, Object o) {
for (Field field : Ref.getDeclaredFields(o.getClass())) {
Config config;
if ((config = field.getType().getAnnotation(Config.class)) != null && config.saveOnExit()) {
TConfig config;
if ((config = field.getType().getAnnotation(TConfig.class)) != null && config.saveOnExit()) {
try {
field.setAccessible(true);
TConfigInjector.saveConfig(plugin, field.get(o));
@ -58,8 +60,8 @@ public class TDependencyInjector {
private static void injectConfig(Plugin plugin, Object o) {
for (Field field : Ref.getDeclaredFields(o.getClass())) {
try {
Config config;
if ((config = field.getType().getAnnotation(Config.class)) != null) {
TConfig config;
if ((config = field.getType().getAnnotation(TConfig.class)) != null) {
field.setAccessible(true);
Object obj = TConfigInjector.loadConfig(plugin, field.getType());
if (obj != null) {
@ -92,8 +94,8 @@ public class TDependencyInjector {
try {
Logger logger;
if ((logger = field.getAnnotation(Logger.class)) != null) {
field.getType().asSubclass(TLogger.class);
TLogger tLogger = new TLogger(logger.value(), plugin, logger.level());
field.getType().asSubclass(com.ilummc.tlib.logger.TLogger.class);
com.ilummc.tlib.logger.TLogger tLogger = new com.ilummc.tlib.logger.TLogger(logger.value(), plugin, logger.level());
if (!field.isAccessible())
field.setAccessible(true);
field.set(o, tLogger);

View File

@ -1,8 +1,6 @@
package com.ilummc.tlib.logger;
import com.ilummc.tlib.util.Strings;
import lombok.Getter;
import lombok.Setter;
import me.skymc.taboolib.Main;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
@ -12,16 +10,31 @@ public class TLogger {
public static final int VERBOSE = 0, FINEST = 1, FINE = 2, INFO = 3, WARN = 4, ERROR = 5, FATAL = 6;
@Getter
private static TLogger globalLogger = new TLogger("§8[§3§lTabooLib§8][§r{1}§8] §f{2}", Main.getInst(), TLogger.FINE);
@Getter
private final String pattern;
@Getter
private Plugin plugin;
@Getter
@Setter
private int level;
public static TLogger getGlobalLogger() {
return globalLogger;
}
public String getPattern() {
return pattern;
}
public Plugin getPlugin() {
return plugin;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public TLogger(String pattern, Plugin plugin, int level) {
this.pattern = pattern;
this.plugin = plugin;

View File

@ -10,6 +10,8 @@ import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;
public class TLocale {
@ -17,25 +19,18 @@ public class TLocale {
throw new AssertionError();
}
private static JavaPlugin getCallerPlugin(Class<?> callerClass) {
try {
Field pluginField = callerClass.getClassLoader().getClass().getDeclaredField("plugin");
pluginField.setAccessible(true);
return (JavaPlugin) pluginField.get(callerClass.getClassLoader());
} catch (Exception ignored) {
TLib.getTLib().getLogger().error("无效的语言文件发送形式: &4" + callerClass.getName());
}
return (JavaPlugin) Main.getInst();
static String asString(String path, Class<?> callerClass, String... args) {
return TLocaleLoader.asString(getCallerPlugin(callerClass), path, args);
}
static List<String> asStringList(String path, Class<?> callerClass, String... args) {
return TLocaleLoader.asStringList(getCallerPlugin(callerClass), path, args);
}
private static void sendTo(String path, CommandSender sender, String[] args, Class<?> callerClass) {
TLocaleLoader.sendTo(getCallerPlugin(callerClass), path, sender, args);
}
static String asString(String path, Class<?> callerClass, String... args) {
return TLocaleLoader.asString(getCallerPlugin(callerClass), path, args);
}
public static void sendToConsole(String path, String... args) {
Ref.getCallerClass(3).ifPresent(clazz -> sendTo(path, Bukkit.getConsoleSender(), args, clazz));
}
@ -50,18 +45,39 @@ public class TLocale {
public static String asString(String path, String... args) {
try {
return asString(path, Ref.getCallerClass(3).get(), args);
return asString(path, Ref.getCallerClassNotOptional(3), args);
} catch (Exception e) {
TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("FETCH-LOCALE-ERROR"), path));
TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("LOCALE-ERROR-REASON"), e.getMessage()));
TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLanguage().getString("FETCH-LOCALE-ERROR"), path));
TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLanguage().getString("LOCALE-ERROR-REASON"), e.getMessage()));
return "§4<" + path + "§4>";
}
}
public static List<String> asStringList(String path, String... args) {
try {
return asStringList(path, Ref.getCallerClassNotOptional(3), args);
} catch (Exception e) {
TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLanguage().getString("FETCH-LOCALE-ERROR"), path));
TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLanguage().getString("LOCALE-ERROR-REASON"), e.getMessage()));
return Collections.singletonList("§4<" + path + "§4>");
}
}
public static void reload() {
Ref.getCallerClass(3).ifPresent(clazz -> TLocaleLoader.load(getCallerPlugin(clazz), false));
}
private static JavaPlugin getCallerPlugin(Class<?> callerClass) {
try {
Field pluginField = callerClass.getClassLoader().getClass().getDeclaredField("plugin");
pluginField.setAccessible(true);
return (JavaPlugin) pluginField.get(callerClass.getClassLoader());
} catch (Exception ignored) {
TLib.getTLib().getLogger().error("无效的语言文件发送形式: &4" + callerClass.getName());
}
return (JavaPlugin) Main.getInst();
}
public static final class Logger extends TLocale {
public static void info(String path, String... args) {

View File

@ -2,6 +2,7 @@ package com.ilummc.tlib.resources;
import com.google.common.collect.ImmutableList;
import com.ilummc.tlib.TLib;
import com.ilummc.tlib.logger.TLogger;
import com.ilummc.tlib.resources.type.TLocaleText;
import com.ilummc.tlib.util.Strings;
import org.bukkit.Bukkit;
@ -22,13 +23,36 @@ import java.util.stream.Collectors;
@SuppressWarnings("rawtypes")
class TLocaleInstance {
private final Map<String, List<TLocaleSendable>> map = new HashMap<>();
private final Plugin plugin;
private int updateNodes;
TLocaleInstance(Plugin plugin) {
this.plugin = plugin;
}
void sendTo(String path, CommandSender sender, String... args) {
@Override
public String toString() {
return map.toString();
}
public int size() {
return map.size();
}
public Map<String, List<TLocaleSendable>> getMap() {
return map;
}
public Plugin getPlugin() {
return plugin;
}
public int getUpdateNodes() {
return updateNodes;
}
public void sendTo(String path, CommandSender sender, String... args) {
try {
map.getOrDefault(path, ImmutableList.of(TLocaleSendable.getEmpty(path))).forEach(sendable -> {
if (Bukkit.isPrimaryThread()) {
@ -38,39 +62,39 @@ class TLocaleInstance {
}
});
} catch (Exception | Error e) {
TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("SEND-LOCALE-ERROR"), path));
TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("LOCALE-ERROR-REASON"), e.toString()));
TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLanguage().getString("SEND-LOCALE-ERROR"), path));
TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLanguage().getString("LOCALE-ERROR-REASON"), e.toString()));
e.printStackTrace();
}
}
String asString(String path, String... args) {
public String asString(String path, String... args) {
return map.getOrDefault(path, ImmutableList.of(TLocaleSendable.getEmpty(path))).get(0).asString(args);
}
void load(YamlConfiguration configuration) {
public List<String> asStringList(String path, String... args) {
return map.getOrDefault(path, ImmutableList.of(TLocaleSendable.getEmpty(path))).get(0).asStringList(args);
}
public void load(YamlConfiguration configuration) {
updateNodes = 0;
configuration.getKeys(true).forEach(s -> {
boolean isCover = false;
Object object = configuration.get(s);
if (object instanceof TLocaleSendable) {
map.put(s, Collections.singletonList((TLocaleSendable) object));
isCover = map.put(s, Collections.singletonList((TLocaleSendable) object)) != null;
} else if (object instanceof List && !((List) object).isEmpty()) {
map.put(s, ((List<?>) object).stream().map(TO_SENDABLE).collect(Collectors.toList()));
isCover = map.put(s, ((List<?>) object).stream().map(TO_SENDABLE).collect(Collectors.toList())) != null;
} else if (!(object instanceof ConfigurationSection)) {
String str = String.valueOf(object);
map.put(s, Collections.singletonList(str.length() == 0 ? TLocaleSendable.getEmpty() : TLocaleText.of(str)));
isCover = map.put(s, Collections.singletonList(str.length() == 0 ? TLocaleSendable.getEmpty() : TLocaleText.of(str))) != null;
}
if (isCover) {
updateNodes++;
}
});
}
int size() {
return map.size();
}
@Override
public String toString() {
return map.toString();
}
private static final Function<Object, TLocaleSendable> TO_SENDABLE = o -> {
if (o instanceof TLocaleSendable) {
return ((TLocaleSendable) o);
@ -80,7 +104,4 @@ class TLocaleInstance {
return TLocaleText.of(String.valueOf(o));
}
};
private final Map<String, List<TLocaleSendable>> map = new HashMap<>();
}

View File

@ -1,13 +1,14 @@
package com.ilummc.tlib.resources;
import com.ilummc.tlib.TLib;
import com.ilummc.tlib.resources.type.TLocaleActionBar;
import com.ilummc.tlib.resources.type.TLocaleJson;
import com.ilummc.tlib.resources.type.TLocaleText;
import com.ilummc.tlib.resources.type.TLocaleTitle;
import com.ilummc.tlib.annotations.TLocalePlugin;
import com.ilummc.tlib.logger.TLogger;
import com.ilummc.tlib.resources.type.*;
import com.ilummc.tlib.util.IO;
import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.fileutils.ConfigUtils;
import me.skymc.taboolib.other.NumberUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
@ -16,8 +17,9 @@ import org.bukkit.plugin.Plugin;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
@ -26,7 +28,15 @@ public class TLocaleLoader {
private static final Map<String, TLocaleInstance> map = new ConcurrentHashMap<>();
static void sendTo(Plugin plugin, String path, CommandSender sender, String... args) {
public static void init() {
ConfigurationSerialization.registerClass(TLocaleText.class, "TEXT");
ConfigurationSerialization.registerClass(TLocaleJson.class, "JSON");
ConfigurationSerialization.registerClass(TLocaleSound.class, "SOUND");
ConfigurationSerialization.registerClass(TLocaleTitle.class, "TITLE");
ConfigurationSerialization.registerClass(TLocaleActionBar.class, "ACTION");
}
public static void sendTo(Plugin plugin, String path, CommandSender sender, String... args) {
if (Bukkit.isPrimaryThread())
Optional.ofNullable(map.get(plugin.getName())).ifPresent(localeInstance -> localeInstance.sendTo(path, sender, args));
else synchronized (TLocaleLoader.class) {
@ -34,67 +44,121 @@ public class TLocaleLoader {
}
}
static String asString(Plugin plugin, String path, String... args) {
return map.get(plugin.getName()).asString(path, args);
}
public static void init() {
ConfigurationSerialization.registerClass(TLocaleText.class, "TEXT");
ConfigurationSerialization.registerClass(TLocaleTitle.class, "TITLE");
ConfigurationSerialization.registerClass(TLocaleJson.class, "JSON");
ConfigurationSerialization.registerClass(TLocaleActionBar.class, "ACTION");
}
public static void load(Plugin plugin, boolean ignoreLoaded) {
try {
if ((!ignoreLoaded || !map.containsKey(plugin.getName())) && (plugin == Main.getInst() || plugin.getDescription().getDepend().contains("TabooLib") || plugin.getDescription().getSoftDepend().contains("TabooLib"))) {
InputStream inputStream = null;
File file = null;
String lang = null;
for (String s : Main.getInst().getConfig().getStringList("LOCALE.PRIORITY")) {
lang = s;
file = new File(plugin.getDataFolder(), "/lang/" + s + ".yml");
if (file.exists()) {
inputStream = Files.newInputStream(file.toPath(), StandardOpenOption.READ);
break;
} else if ((inputStream = plugin.getClass().getResourceAsStream("/lang/" + s + ".yml")) != null) {
break;
}
}
if (inputStream == null) {
TLib.getTLib().getLogger().error(TLib.getTLib().getInternalLang().getString("LANG-LOAD-FAIL"));
return;
}
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
plugin.saveResource("lang/" + lang + ".yml", true);
}
TLib.getTLib().getLogger().info(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("TRY-LOADING-LANG"), plugin.getName(), lang));
{
YamlConfiguration configuration = ConfigUtils.loadYaml(plugin, file);
TLocaleInstance localeInstance = new TLocaleInstance(plugin);
localeInstance.load(configuration);
map.put(plugin.getName(), localeInstance);
TLib.getTLib().getLogger().info(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("SUCCESS-LOADING-LANG"),
plugin.getName(), lang, String.valueOf(localeInstance.size())));
}
File finalFile = file;
String finalLang = lang;
TLib.getTLib().getConfigWatcher().addListener(file, null, obj -> {
TLib.getTLib().getLogger().info(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("RELOADING-LANG"), plugin.getName()));
YamlConfiguration configuration = ConfigUtils.loadYaml(plugin, finalFile);
TLocaleInstance localeInstance = new TLocaleInstance(plugin);
localeInstance.load(configuration);
map.put(plugin.getName(), localeInstance);
TLib.getTLib().getLogger().info(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("SUCCESS-LOADING-LANG"),
plugin.getName(), finalLang, String.valueOf(localeInstance.size())));
});
}
} catch (Exception e) {
TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("ERROR-LOADING-LANG"),
plugin.getName(), e.toString() + "\n" + e.getStackTrace()[0].toString()));
public static String asString(Plugin plugin, String path, String... args) {
TLocaleInstance tLocaleInstance = map.get(plugin.getName());
if (tLocaleInstance != null) {
return tLocaleInstance.asString(path, args);
} else {
return "";
}
}
public static List<String> asStringList(Plugin plugin, String path, String... args) {
TLocaleInstance tLocaleInstance = map.get(plugin.getName());
if (tLocaleInstance != null) {
return tLocaleInstance.asStringList(path, args);
} else {
return Collections.emptyList();
}
}
/**
*
*
* @param plugin
* @param isCover
*/
public static void load(Plugin plugin, boolean isCover) {
try {
if ((isCover || !isLocaleLoaded(plugin)) && (plugin.equals(Main.getInst()) || isDependWithTabooLib(plugin))) {
// 获取文件
File localeFile = getLocaleFile(plugin);
if (localeFile == null) {
return;
}
// 加载文件
infoLogger("TRY-LOADING-LANG", plugin.getName(), localeFile.getName());
YamlConfiguration localeConfiguration = ConfigUtils.loadYaml(plugin, localeFile);
YamlConfiguration localeConfigurationAtStream = getLocaleAtStream(plugin, localeFile);
// 载入配置
loadPluginLocale(plugin, localeFile, localeConfiguration, localeConfigurationAtStream);
// 注册监听
TLib.getTLib().getConfigWatcher().removeListener(localeFile);
TLib.getTLib().getConfigWatcher().addListener(localeFile, null, obj -> {
infoLogger("RELOADING-LANG", plugin.getName());
loadPluginLocale(plugin, localeFile, ConfigUtils.loadYaml(plugin, localeFile), getLocaleAtStream(plugin, localeFile));
});
}
} catch (Exception e) {
errorLogger("ERROR-LOADING-LANG", plugin.getName(), e.toString() + "\n" + e.getStackTrace()[0].toString());
}
}
private static void infoLogger(String path, String... args) {
TLogger.getGlobalLogger().info(Strings.replaceWithOrder(TLib.getInternalLanguage().getString(path), args));
}
private static void errorLogger(String path, String... args) {
TLogger.getGlobalLogger().error(Strings.replaceWithOrder(TLib.getInternalLanguage().getString(path), args));
}
private static boolean isVersionOutOfDate(YamlConfiguration configuration, YamlConfiguration configurationAtSteam) {
return (configurationAtSteam != null && configurationAtSteam.contains("VERSION") && configuration.contains("VERSION")) && NumberUtils.getDouble(configurationAtSteam.get("VERSION").toString()) > NumberUtils.getDouble(configuration.get("VERSION").toString());
}
private static File getLocaleFile(Plugin plugin) {
releaseLocales(plugin);
return getLocalePriority().stream().map(localeName -> new File(plugin.getDataFolder(), "lang/" + localeName + ".yml")).filter(File::exists).findFirst().orElse(null);
}
private static void releaseLocales(Plugin plugin) {
getLocalePriority().stream().filter(localeName -> !new File(plugin.getDataFolder(), "lang/" + localeName + ".yml").exists() && plugin.getResource("lang/" + localeName + ".yml") != null).forEach(localeName -> plugin.saveResource("lang/" + localeName + ".yml", true));
}
public static boolean isLocaleLoaded(Plugin plugin) {
return map.containsKey(plugin.getName());
}
public static boolean isDependWithTabooLib(Plugin plugin) {
return plugin.getClass().getAnnotation(TLocalePlugin.class) != null || plugin.getDescription().getDepend().contains(Main.getInst().getName()) || plugin.getDescription().getSoftDepend().contains(Main.getInst().getName());
}
public static List<String> getLocalePriority() {
return Main.getInst().getConfig().contains("LOCALE.PRIORITY") ? Main.getInst().getConfig().getStringList("LOCALE.PRIORITY") : Collections.singletonList("zh_CN");
}
private static TLocaleInstance getLocaleInstance(Plugin plugin) {
TLocaleInstance instance = new TLocaleInstance(plugin);
map.put(plugin.getName(), instance);
return instance;
}
private static YamlConfiguration getLocaleAtStream(Plugin plugin, File localeFile) {
InputStream localeInputSteam = plugin.getClass().getResourceAsStream("/lang/" + localeFile.getName());
try {
String yamlText = new String(IO.readFully(localeInputSteam), Charset.forName("utf-8"));
YamlConfiguration yaml = new YamlConfiguration();
yaml.loadFromString(yamlText);
return yaml;
} catch (Exception ignored) {
return null;
}
}
private static void loadPluginLocale(Plugin plugin, File localeFile, YamlConfiguration localeConfiguration, YamlConfiguration localeConfigurationAtStream) {
TLocaleInstance localeInstance = getLocaleInstance(plugin);
boolean versionOutOfDate = isVersionOutOfDate(localeConfiguration, localeConfigurationAtStream);
if (versionOutOfDate) {
localeInstance.load(localeConfigurationAtStream);
}
localeInstance.load(localeConfiguration);
if (!versionOutOfDate || localeInstance.size() - localeInstance.getUpdateNodes() == 0) {
infoLogger("SUCCESS-LOADING-LANG-NORMAL", plugin.getName(), localeFile.getName().split("\\.")[0], String.valueOf(localeInstance.size()));
} else {
infoLogger("SUCCESS-LOADING-LANG-UPDATE", plugin.getName(), localeFile.getName().split("\\.")[0], String.valueOf(localeInstance.size()), String.valueOf(localeInstance.size() - localeInstance.getUpdateNodes()));
}
}
}

View File

@ -2,10 +2,20 @@ package com.ilummc.tlib.resources;
import org.bukkit.command.CommandSender;
import java.util.Collections;
import java.util.List;
public interface TLocaleSendable {
static TLocaleSendable getEmpty() {
return (sender, args) -> {
// Empty
};
}
static TLocaleSendable getEmpty(String path) {
return new TLocaleSendable() {
@Override
public void sendTo(CommandSender sender, String... args) {
sender.sendMessage("§4<" + path + "§4>");
@ -15,23 +25,21 @@ public interface TLocaleSendable {
public String asString(String... args) {
return "§4<" + path + "§4>";
}
};
}
static TLocaleSendable getEmpty() {
return new TLocaleSendable() {
@Override
public void sendTo(CommandSender sender, String... args) {
}
@Override
public String asString(String... args) {
return "";
public List<String> asStringList(String... args) {
return Collections.singletonList("§4<" + path + "§4>");
}
};
}
void sendTo(CommandSender sender, String... args);
String asString(String... args);
default String asString(String... args) {
return "";
}
default List<String> asStringList(String... args) {
return Collections.emptyList();
}
}

View File

@ -20,7 +20,6 @@ import java.util.Map;
public class TLocaleActionBar implements TLocaleSendable, ConfigurationSerializable {
private final String text;
private final boolean papi;
private TLocaleActionBar(String text, boolean papi) {
@ -54,8 +53,9 @@ public class TLocaleActionBar implements TLocaleSendable, ConfigurationSerializa
public Map<String, Object> serialize() {
Map<String, Object> map = Maps.newHashMap();
map.put("text", text);
if (papi)
if (papi) {
map.put("papi", true);
}
return map;
}

View File

@ -8,7 +8,9 @@ import com.ilummc.tlib.compat.PlaceholderHook;
import com.ilummc.tlib.resources.TLocaleSendable;
import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.jsonformatter.JSONFormatter;
import net.md_5.bungee.api.chat.*;
import net.md_5.bungee.chat.ComponentSerializer;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
@ -37,25 +39,17 @@ public class TLocaleJson implements TLocaleSendable, ConfigurationSerializable {
}
public static TLocaleJson valueOf(Map<String, Object> map) {
Object textObj = map.getOrDefault("text", "Empty Node");
List<String> textList = textObj instanceof String ? Lists.newArrayList(ChatColor.translateAlternateColorCodes('&', (String) textObj)) :
(textObj instanceof List && !((List) textObj).isEmpty()) ?
((List<?>) textObj).stream().map(Object::toString)
.map(s -> ChatColor.translateAlternateColorCodes('&', s))
.collect(Collectors.toList()) : Lists.newArrayList(String.valueOf(textObj));
boolean papi = (boolean) map.getOrDefault("papi", Main.getInst().getConfig().getBoolean("LOCALE.USE_PAPI", false));
List<String> textList = getTextList(map.getOrDefault("text", "Empty Node"));
Object argsObj = map.get("args");
if (argsObj instanceof Map) {
Map<String, Object> section = new HashMap<>(((Map<?, ?>) argsObj).size());
((Map<?, ?>) argsObj).forEach((k, v) -> section.put(String.valueOf(k), v));
List<BaseComponent[]> collect = textList.stream().map(s -> {
String[] template = pattern.split(s);
int index = 0;
String[] template = pattern.split(s);
Matcher matcher = pattern.matcher(s);
List<BaseComponent> builder;
if (template.length > index) {
builder = new ArrayList<>(Arrays.asList(TextComponent.fromLegacyText(template[index++])));
} else builder = new ArrayList<>();
List<BaseComponent> builder = template.length > index ? new ArrayList<>(Arrays.asList(TextComponent.fromLegacyText(template[index++]))) : new ArrayList<>();
while (matcher.find()) {
String replace = matcher.group();
if (replace.length() <= 2) continue;
@ -64,35 +58,22 @@ public class TLocaleJson implements TLocaleSendable, ConfigurationSerializable {
String text = split.length > 1 ? split[0] : "";
String node = split.length > 1 ? split[1] : split[0];
if (section.containsKey(node)) {
@SuppressWarnings("unchecked")
Map<String, Object> arg = (Map<String, Object>) section.get(node);
text = ChatColor.translateAlternateColorCodes('&', String.valueOf(arg.getOrDefault("text", text)));
BaseComponent[] component = TextComponent.fromLegacyText(text);
arg.forEach((key, value) -> {
switch (key) {
case "suggest":
for (BaseComponent baseComponent : component) {
baseComponent.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, String.valueOf(value)));
}
break;
case "command":
for (BaseComponent baseComponent : component) {
baseComponent.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, String.valueOf(value)));
}
break;
case "hover":
for (BaseComponent baseComponent : component) {
baseComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT,
new ComponentBuilder(ChatColor.translateAlternateColorCodes('&', String.valueOf(value))).create()));
}
break;
default:
if ("suggest".equalsIgnoreCase(key)) {
Arrays.stream(component).forEach(baseComponent -> baseComponent.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, String.valueOf(value))));
} else if ("command".equalsIgnoreCase(key) || "commands".equalsIgnoreCase(key)) {
Arrays.stream(component).forEach(baseComponent -> baseComponent.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, String.valueOf(value))));
} else if ("hover".equalsIgnoreCase(key)) {
Arrays.stream(component).forEach(baseComponent -> baseComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(ChatColor.translateAlternateColorCodes('&', String.valueOf(value))).create())));
}
});
builder.addAll(Arrays.asList(component));
} else {
builder.addAll(Arrays.asList(TextComponent.fromLegacyText(text)));
TLib.getTLib().getLogger().warn(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("MISSING-ARGUMENT"), node));
TLib.getTLib().getLogger().warn(Strings.replaceWithOrder(TLib.getTLib().getInternalLanguage().getString("MISSING-ARGUMENT"), node));
}
if (index < template.length) {
builder.addAll(Arrays.asList(TextComponent.fromLegacyText(template[index++])));
@ -105,10 +86,19 @@ public class TLocaleJson implements TLocaleSendable, ConfigurationSerializable {
return new TLocaleJson(textList.stream().map(TextComponent::fromLegacyText).collect(Collectors.toList()), papi, map);
}
private static List<String> getTextList(Object textObj) {
if (textObj instanceof List) {
return ((List<?>) textObj).stream().map(Object::toString).map(s -> ChatColor.translateAlternateColorCodes('&', s)).collect(Collectors.toList());
} else if (textObj instanceof String) {
return Lists.newArrayList(ChatColor.translateAlternateColorCodes('&', (String) textObj));
} else {
return Collections.emptyList();
}
}
@Override
public void sendTo(CommandSender sender, String... args) {
if (sender instanceof Player)
components.forEach(comp -> ((Player) sender).spigot().sendMessage(replace(comp, sender, args)));
components.forEach(comp -> sendRawMessage(sender, replace(comp, sender, args)));
}
@Override
@ -121,6 +111,14 @@ public class TLocaleJson implements TLocaleSendable, ConfigurationSerializable {
return Maps.newHashMap(map);
}
private void sendRawMessage(CommandSender sender, BaseComponent[] components) {
if (sender instanceof Player) {
JSONFormatter.sendRawMessage((Player) sender, ComponentSerializer.toString(components));
} else {
sender.sendMessage(TextComponent.toLegacyText(components));
}
}
private BaseComponent[] replace(BaseComponent[] component, CommandSender sender, String... args) {
BaseComponent[] components = new BaseComponent[component.length];
for (int i = 0; i < components.length; i++) {
@ -142,8 +140,9 @@ public class TLocaleJson implements TLocaleSendable, ConfigurationSerializable {
HoverEvent hoverEvent = new HoverEvent(component.getHoverEvent().getAction(), replace(component.getHoverEvent().getValue(), sender, args));
component.setHoverEvent(hoverEvent);
}
if (component.getExtra() != null)
if (component.getExtra() != null) {
component.setExtra(replace(component.getExtra(), sender, args));
}
if (component instanceof TextComponent) {
((TextComponent) component).setText(replace(sender, ((TextComponent) component).getText(), args));
}

View File

@ -22,7 +22,6 @@ import java.util.stream.Collectors;
public class TLocaleText implements TLocaleSendable, ConfigurationSerializable {
private final Object text;
private final boolean usePlaceholder;
private TLocaleText(Object text, boolean usePlaceholder) {
@ -78,9 +77,19 @@ public class TLocaleText implements TLocaleSendable, ConfigurationSerializable {
return Strings.replaceWithOrder(objectToString(text), args);
}
@Override
public List<String> asStringList(String... args) {
if (text instanceof String) {
return Collections.singletonList(((String) text));
} else {
return ((List<String>) text);
}
}
private String objectToString(Object text) {
if (text instanceof String) return ((String) text);
else {
if (text instanceof String) {
return ((String) text);
} else {
StringJoiner joiner = new StringJoiner("\n");
((List<String>) text).forEach(joiner::add);
return joiner.toString();

View File

@ -54,7 +54,7 @@ public class TLocaleTitle implements TLocaleSendable, ConfigurationSerializable
(int) map.getOrDefault("stay", 20),
(boolean) map.getOrDefault("papi", Main.getInst().getConfig().getBoolean("LOCALE.USE_PAPI", false)));
} catch (Exception e) {
title = new TLocaleTitle("§4Load failed!", "§c" + e.getMessage(), 10, 20, 10, false);
title = new TLocaleTitle("Empty Title message.", e.getMessage(), 10, 20, 10, false);
}
return title;
}

View File

@ -70,6 +70,10 @@ public class Ref {
return Optional.ofNullable(CallerClass.impl.getCallerClass(depth + 1));
}
public static Class<?> getCallerClassNotOptional(int depth) {
return CallerClass.impl.getCallerClass(depth);
}
public static String getSerializedName(Field field) {
return field.isAnnotationPresent(SerializedName.class) ? field.getAnnotation(SerializedName.class).value() : field.getName();
}

View File

@ -24,5 +24,4 @@ public class Strings {
}
return stringBuilder.toString();
}
}

View File

@ -1,11 +1,8 @@
package me.skymc.taboolib;
import com.ilummc.tlib.TLib;
import lombok.Getter;
import lombok.Setter;
import me.skymc.taboolib.anvil.AnvilContainerAPI;
import me.skymc.taboolib.bstats.Metrics;
import me.skymc.taboolib.client.LogClient;
import me.skymc.taboolib.commands.MainCommands;
import me.skymc.taboolib.commands.language.Language2Command;
import me.skymc.taboolib.commands.locale.TabooLibLocaleCommand;
@ -52,32 +49,70 @@ import java.util.Random;
@SuppressWarnings("deprecation")
public class Main extends JavaPlugin implements Listener {
@Getter
private static Plugin inst;
@Getter
private static String prefix = "§8[§3§lTabooLib§8] §7";
@Getter
@Setter
private static Economy Economy;
@Getter
private static File playerDataFolder;
@Getter
private static File serverDataFolder;
@Getter
private static StorageType storageType;
@Getter
private static boolean disable = false;
@Getter
private static MySQLConnection connection = null;
@Getter
private FileConfiguration config = null;
@Getter
private static LogClient client;
@Getter
private static Language2 exampleLangauge2;
@Getter
private static Language2 exampleLanguage2;
private static boolean started;
private FileConfiguration config = null;
public static Plugin getInst() {
return inst;
}
public static String getPrefix() {
return "§8[§3§lTabooLib§8] §7";
}
public static net.milkbowl.vault.economy.Economy getEconomy() {
return Economy;
}
public static void setEconomy(net.milkbowl.vault.economy.Economy economy) {
Economy = economy;
}
public static File getPlayerDataFolder() {
return playerDataFolder;
}
public static File getServerDataFolder() {
return serverDataFolder;
}
public static StorageType getStorageType() {
return storageType;
}
public static boolean isDisable() {
return disable;
}
public static MySQLConnection getConnection() {
return connection;
}
public static Language2 getExampleLanguage2() {
return exampleLanguage2;
}
public static boolean isStarted() {
return started;
}
public static Random getRandom() {
return NumberUtils.getRand();
}
@ -86,6 +121,11 @@ public class Main extends JavaPlugin implements Listener {
return inst.getConfig().getString("MYSQL.PREFIX");
}
@Override
public FileConfiguration getConfig() {
return config;
}
@Override
public void saveDefaultConfig() {
reloadConfig();
@ -179,7 +219,7 @@ public class Main extends JavaPlugin implements Listener {
// 启动脚本
JavaShell.javaShellSetup();
// 载入语言文件
exampleLangauge2 = new Language2("Language2", this);
exampleLanguage2 = new Language2("Language2", this);
// 注册脚本
SkriptHandler.getInst();
@ -304,13 +344,11 @@ public class Main extends JavaPlugin implements Listener {
getServer().getPluginManager().registerEvents(new ItemLibraryPatch(), this);
getServer().getPluginManager().registerEvents(new SoundsLibraryPatch(), this);
if (TabooLib.getVerint() > 10700) {
getServer().getPluginManager().registerEvents(new EntityUtils(), this);
getServer().getPluginManager().registerEvents(new SignUtils(), this);
}
// 如果 YUM 插件存在
if (Bukkit.getPluginManager().getPlugin("YUM") != null) {
getServer().getPluginManager().registerEvents(new ListenerNetWork(), this);
}

View File

@ -1,62 +1,60 @@
package me.skymc.taboolib;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import me.skymc.taboolib.playerdata.DataUtils;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import java.util.Arrays;
import java.util.UUID;
public class TabooLib {
public static void debug(Plugin plugin, String... args) {
if (Main.getInst().getConfig().getBoolean("DEBUG")) {
for (String var : args) {
Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_RED + "[TabooLib - DEBUG][" + plugin.getName() + "] " + ChatColor.RED + var);
}
}
}
public static double getPluginVersion() {
try {
return Double.valueOf(Main.getInst().getDescription().getVersion());
} catch (Exception e) {
return 0D;
}
}
public static String getVersion() {
return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
}
public static String getServerUID() {
if (!DataUtils.getPluginData("TabooLibrary", null).contains("serverUID")) {
DataUtils.getPluginData("TabooLibrary", null).set("serverUID", UUID.randomUUID().toString());
}
return DataUtils.getPluginData("TabooLibrary", null).getString("serverUID");
}
public static void resetServerUID() {
DataUtils.getPluginData("TabooLibrary", null).set("serverUID", UUID.randomUUID().toString());
}
public static int getVerint() {
if (getVersion().startsWith("v1_7")) {
return 10700;
} else if (getVersion().startsWith("v1_8")) {
return 10800;
} else if (getVersion().startsWith("v1_9")) {
return 10900;
} else if (getVersion().startsWith("v1_10")) {
return 11000;
} else if (getVersion().startsWith("v1_11")) {
return 11100;
} else if (getVersion().startsWith("v1_12")) {
return 11200;
} else if (getVersion().startsWith("v1_13")) {
return 11300;
}
return 0;
}
public static void debug(Plugin plugin, String... args) {
if (Main.getInst().getConfig().getBoolean("DEBUG")) {
Arrays.stream(args).forEach(var -> Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_RED + "[TabooLib - DEBUG][" + plugin.getName() + "] " + ChatColor.RED + var));
}
}
public static double getPluginVersion() {
try {
return Double.valueOf(Main.getInst().getDescription().getVersion());
} catch (Exception e) {
return 0D;
}
}
public static String getVersion() {
return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
}
public static String getServerUID() {
if (!DataUtils.getPluginData("TabooLibrary", null).contains("serverUID")) {
DataUtils.getPluginData("TabooLibrary", null).set("serverUID", UUID.randomUUID().toString());
}
return DataUtils.getPluginData("TabooLibrary", null).getString("serverUID");
}
public static void resetServerUID() {
DataUtils.getPluginData("TabooLibrary", null).set("serverUID", UUID.randomUUID().toString());
}
public static int getVerint() {
if (getVersion().startsWith("v1_7")) {
return 10700;
} else if (getVersion().startsWith("v1_8")) {
return 10800;
} else if (getVersion().startsWith("v1_9")) {
return 10900;
} else if (getVersion().startsWith("v1_10")) {
return 11000;
} else if (getVersion().startsWith("v1_11")) {
return 11100;
} else if (getVersion().startsWith("v1_12")) {
return 11200;
} else if (getVersion().startsWith("v1_13")) {
return 11300;
}
return 0;
}
}

View File

@ -1,9 +1,6 @@
package me.skymc.taboolib.anvil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import me.skymc.taboolib.anvil.versions.AnvilContainer_V1_9_4;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Sound;
@ -18,107 +15,91 @@ import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import me.skymc.taboolib.anvil.versions.AnvilContainer_V1_9_4;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class AnvilContainerAPI implements Listener{
public static List<String> list = new ArrayList<>();
public static ItemStack item = new ItemStack(Material.NAME_TAG);
public static HashMap<String, String> isOpen = new HashMap<>();
public static AnvilContainerAPIEvent event;
public static void send(Player p, String type, String str, List<String> lorelist)
{
isOpen.put(p.getName(), type);
AnvilContainer_V1_9_4.openAnvil(p);
ItemMeta meta = item.getItemMeta();
list.clear();
if (lorelist == null)
{
list.add("");
list.add("§7在上方文本框内输入信息");
list.add("§7随后点击右侧输出物品");
}
else
{
list = lorelist;
}
meta.setLore(list);
meta.setDisplayName(str);
item.setItemMeta(meta);
p.getOpenInventory().setItem(0, item);
p.playSound(p.getLocation(), Sound.BLOCK_ANVIL_PLACE, 1, 1);
}
@EventHandler
public void close(InventoryCloseEvent e)
{
if (isOpen.containsKey(e.getPlayer().getName()))
{
isOpen.remove(e.getPlayer().getName());
if (e.getInventory().getType() == InventoryType.ANVIL)
{
e.getInventory().clear();
}
}
}
@EventHandler
public void click(InventoryClickEvent e)
{
if (!isOpen.containsKey(e.getWhoClicked().getName()))
{
return;
}
if (e.getInventory().getType() != InventoryType.ANVIL)
{
return;
}
e.setCancelled(true);
int slot = e.getRawSlot();
if (slot != 2)
{
return;
}
Inventory inv = e.getInventory();
if (inv.getItem(2) == null)
{
return;
}
if (inv.getItem(2).getItemMeta().hasDisplayName())
{
event = new AnvilContainerAPIEvent(e, isOpen.get(e.getWhoClicked().getName()), inv.getItem(2).getItemMeta().getDisplayName());
e.getWhoClicked().closeInventory();
Bukkit.getPluginManager().callEvent(event);
}
}
@EventHandler
public void example(PlayerCommandPreprocessEvent e)
{
if (e.getMessage().equals("/anvilexample"))
{
if (e.getPlayer().hasPermission("taboolib.admin"))
{
e.setCancelled(true);
AnvilContainerAPI.send(e.getPlayer(), "EXAMPLE", "在这里输入文本", null);
}
}
}
@EventHandler
public void example2(AnvilContainerAPIEvent e)
{
if (e.type.equals("EXAMPLE"))
{
e.event.getWhoClicked().sendMessage(e.string);
}
}
public class AnvilContainerAPI implements Listener {
public static List<String> list = new ArrayList<>();
public static ItemStack item = new ItemStack(Material.NAME_TAG);
public static HashMap<String, String> isOpen = new HashMap<>();
public static AnvilContainerAPIEvent event;
public static void send(Player p, String type, String str, List<String> lorelist) {
isOpen.put(p.getName(), type);
AnvilContainer_V1_9_4.openAnvil(p);
ItemMeta meta = item.getItemMeta();
list.clear();
if (lorelist == null) {
list.add("");
list.add("§7在上方文本框内输入信息");
list.add("§7随后点击右侧输出物品");
} else {
list = lorelist;
}
meta.setLore(list);
meta.setDisplayName(str);
item.setItemMeta(meta);
p.getOpenInventory().setItem(0, item);
p.playSound(p.getLocation(), Sound.BLOCK_ANVIL_PLACE, 1, 1);
}
@EventHandler
public void close(InventoryCloseEvent e) {
if (isOpen.containsKey(e.getPlayer().getName())) {
isOpen.remove(e.getPlayer().getName());
if (e.getInventory().getType() == InventoryType.ANVIL) {
e.getInventory().clear();
}
}
}
@EventHandler
public void click(InventoryClickEvent e) {
if (!isOpen.containsKey(e.getWhoClicked().getName())) {
return;
}
if (e.getInventory().getType() != InventoryType.ANVIL) {
return;
}
e.setCancelled(true);
int slot = e.getRawSlot();
if (slot != 2) {
return;
}
Inventory inv = e.getInventory();
if (inv.getItem(2) == null) {
return;
}
if (inv.getItem(2).getItemMeta().hasDisplayName()) {
event = new AnvilContainerAPIEvent(e, isOpen.get(e.getWhoClicked().getName()), inv.getItem(2).getItemMeta().getDisplayName());
e.getWhoClicked().closeInventory();
Bukkit.getPluginManager().callEvent(event);
}
}
@EventHandler
public void example(PlayerCommandPreprocessEvent e) {
if (e.getMessage().equals("/anvilexample")) {
if (e.getPlayer().hasPermission("taboolib.admin")) {
e.setCancelled(true);
AnvilContainerAPI.send(e.getPlayer(), "EXAMPLE", "在这里输入文本", null);
}
}
}
@EventHandler
public void example2(AnvilContainerAPIEvent e) {
if (e.type.equals("EXAMPLE")) {
e.event.getWhoClicked().sendMessage(e.string);
}
}
}

View File

@ -4,28 +4,25 @@ import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.event.inventory.InventoryClickEvent;
public class AnvilContainerAPIEvent extends Event{
public static final HandlerList handlers = new HandlerList();
public InventoryClickEvent event;
public String string;
public String type;
public AnvilContainerAPIEvent(InventoryClickEvent e, String t, String s)
{
event = e;
string = s;
type = t;
}
public class AnvilContainerAPIEvent extends Event {
@Override
public HandlerList getHandlers()
{
return handlers;
}
public static HandlerList getHandlerList()
{
return handlers;
}
public static final HandlerList handlers = new HandlerList();
public InventoryClickEvent event;
public String string;
public String type;
public AnvilContainerAPIEvent(InventoryClickEvent e, String t, String s) {
event = e;
string = s;
type = t;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}

View File

@ -1,41 +1,32 @@
package me.skymc.taboolib.anvil.versions;
import net.minecraft.server.v1_11_R1.*;
import org.bukkit.craftbukkit.v1_11_R1.entity.CraftPlayer;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_11_R1.BlockPosition;
import net.minecraft.server.v1_11_R1.ChatMessage;
import net.minecraft.server.v1_11_R1.ContainerAnvil;
import net.minecraft.server.v1_11_R1.EntityHuman;
import net.minecraft.server.v1_11_R1.EntityPlayer;
import net.minecraft.server.v1_11_R1.PacketPlayOutOpenWindow;
public class AnvilContainer_V1_11_R1 extends ContainerAnvil {
public AnvilContainer_V1_11_R1(EntityHuman player)
{
super(player.inventory, player.world, new BlockPosition(0, 0, 0), player);
}
@Override
public boolean a(EntityHuman player)
{
return true;
}
/**
* @deprecated
*/
@Deprecated
public static void openAnvil(Player p)
{
EntityPlayer player = ((CraftPlayer)p).getHandle();
AnvilContainer_V1_11_R1 container = new AnvilContainer_V1_11_R1(player);
int c = player.nextContainerCounter();
public AnvilContainer_V1_11_R1(EntityHuman player) {
super(player.inventory, player.world, new BlockPosition(0, 0, 0), player);
}
@Override
public boolean a(EntityHuman player) {
return true;
}
/**
* @deprecated
*/
@Deprecated
public static void openAnvil(Player p) {
EntityPlayer player = ((CraftPlayer) p).getHandle();
AnvilContainer_V1_11_R1 container = new AnvilContainer_V1_11_R1(player);
int c = player.nextContainerCounter();
player.playerConnection.sendPacket(new PacketPlayOutOpenWindow(c, "minecraft:anvil", new ChatMessage("Repairing"), 0));
player.activeContainer = container;
player.activeContainer.windowId = c;
player.activeContainer.addSlotListener(player);
}
player.activeContainer = container;
player.activeContainer.windowId = c;
player.activeContainer.addSlotListener(player);
}
}

View File

@ -1,41 +1,32 @@
package me.skymc.taboolib.anvil.versions;
import net.minecraft.server.v1_8_R3.*;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_8_R3.BlockPosition;
import net.minecraft.server.v1_8_R3.ChatMessage;
import net.minecraft.server.v1_8_R3.ContainerAnvil;
import net.minecraft.server.v1_8_R3.EntityHuman;
import net.minecraft.server.v1_8_R3.EntityPlayer;
import net.minecraft.server.v1_8_R3.PacketPlayOutOpenWindow;
public class AnvilContainer_V1_8_R3 extends ContainerAnvil {
public AnvilContainer_V1_8_R3(EntityHuman player)
{
super(player.inventory, player.world, new BlockPosition(0, 0, 0), player);
}
@Override
public boolean a(EntityHuman player)
{
return true;
}
/**
* @deprecated
*/
@Deprecated
public static void openAnvil(Player p)
{
EntityPlayer player = ((CraftPlayer)p).getHandle();
AnvilContainer_V1_8_R3 container = new AnvilContainer_V1_8_R3(player);
int c = player.nextContainerCounter();
public AnvilContainer_V1_8_R3(EntityHuman player) {
super(player.inventory, player.world, new BlockPosition(0, 0, 0), player);
}
@Override
public boolean a(EntityHuman player) {
return true;
}
/**
* @deprecated
*/
@Deprecated
public static void openAnvil(Player p) {
EntityPlayer player = ((CraftPlayer) p).getHandle();
AnvilContainer_V1_8_R3 container = new AnvilContainer_V1_8_R3(player);
int c = player.nextContainerCounter();
player.playerConnection.sendPacket(new PacketPlayOutOpenWindow(c, "minecraft:anvil", new ChatMessage("Repairing"), 0));
player.activeContainer = container;
player.activeContainer.windowId = c;
player.activeContainer.addSlotListener(player);
}
player.activeContainer = container;
player.activeContainer.windowId = c;
player.activeContainer.addSlotListener(player);
}
}

View File

@ -1,41 +1,32 @@
package me.skymc.taboolib.anvil.versions;
import net.minecraft.server.v1_9_R2.*;
import org.bukkit.craftbukkit.v1_9_R2.entity.CraftPlayer;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_9_R2.BlockPosition;
import net.minecraft.server.v1_9_R2.ChatMessage;
import net.minecraft.server.v1_9_R2.ContainerAnvil;
import net.minecraft.server.v1_9_R2.EntityHuman;
import net.minecraft.server.v1_9_R2.EntityPlayer;
import net.minecraft.server.v1_9_R2.PacketPlayOutOpenWindow;
public class AnvilContainer_V1_9_4 extends ContainerAnvil {
public AnvilContainer_V1_9_4(EntityHuman player)
{
super(player.inventory, player.world, new BlockPosition(0, 0, 0), player);
}
@Override
public boolean a(EntityHuman player)
{
return true;
}
/**
* @deprecated
*/
@Deprecated
public static void openAnvil(Player p)
{
EntityPlayer player = ((CraftPlayer)p).getHandle();
AnvilContainer_V1_9_4 container = new AnvilContainer_V1_9_4(player);
int c = player.nextContainerCounter();
public AnvilContainer_V1_9_4(EntityHuman player) {
super(player.inventory, player.world, new BlockPosition(0, 0, 0), player);
}
@Override
public boolean a(EntityHuman player) {
return true;
}
/**
* @deprecated
*/
@Deprecated
public static void openAnvil(Player p) {
EntityPlayer player = ((CraftPlayer) p).getHandle();
AnvilContainer_V1_9_4 container = new AnvilContainer_V1_9_4(player);
int c = player.nextContainerCounter();
player.playerConnection.sendPacket(new PacketPlayOutOpenWindow(c, "minecraft:anvil", new ChatMessage("Repairing"), 0));
player.activeContainer = container;
player.activeContainer.windowId = c;
player.activeContainer.addSlotListener(player);
}
player.activeContainer = container;
player.activeContainer.windowId = c;
player.activeContainer.addSlotListener(player);
}
}

View File

@ -1,87 +1,55 @@
package me.skymc.taboolib.bookformatter;
import static org.bukkit.Achievement.ACQUIRE_IRON;
import static org.bukkit.Achievement.BAKE_CAKE;
import static org.bukkit.Achievement.BOOKCASE;
import static org.bukkit.Achievement.BREED_COW;
import static org.bukkit.Achievement.BREW_POTION;
import static org.bukkit.Achievement.BUILD_BETTER_PICKAXE;
import static org.bukkit.Achievement.BUILD_FURNACE;
import static org.bukkit.Achievement.BUILD_HOE;
import static org.bukkit.Achievement.BUILD_PICKAXE;
import static org.bukkit.Achievement.BUILD_SWORD;
import static org.bukkit.Achievement.BUILD_WORKBENCH;
import static org.bukkit.Achievement.COOK_FISH;
import static org.bukkit.Achievement.DIAMONDS_TO_YOU;
import static org.bukkit.Achievement.ENCHANTMENTS;
import static org.bukkit.Achievement.END_PORTAL;
import static org.bukkit.Achievement.EXPLORE_ALL_BIOMES;
import static org.bukkit.Achievement.FLY_PIG;
import static org.bukkit.Achievement.FULL_BEACON;
import static org.bukkit.Achievement.GET_BLAZE_ROD;
import static org.bukkit.Achievement.GET_DIAMONDS;
import static org.bukkit.Achievement.GHAST_RETURN;
import static org.bukkit.Achievement.KILL_COW;
import static org.bukkit.Achievement.KILL_ENEMY;
import static org.bukkit.Achievement.KILL_WITHER;
import static org.bukkit.Achievement.MAKE_BREAD;
import static org.bukkit.Achievement.MINE_WOOD;
import static org.bukkit.Achievement.NETHER_PORTAL;
import static org.bukkit.Achievement.ON_A_RAIL;
import static org.bukkit.Achievement.OPEN_INVENTORY;
import static org.bukkit.Achievement.OVERKILL;
import static org.bukkit.Achievement.OVERPOWERED;
import static org.bukkit.Achievement.SNIPE_SKELETON;
import static org.bukkit.Achievement.SPAWN_WITHER;
import static org.bukkit.Achievement.THE_END;
import java.util.HashMap;
import org.bukkit.Achievement;
import java.util.HashMap;
import static org.bukkit.Achievement.*;
public final class BookAchievement {
private static final HashMap<Achievement, String> achievements = new HashMap<>();
static {
achievements.put(OPEN_INVENTORY, "openInventory");
achievements.put(MINE_WOOD, "mineWood");
achievements.put(BUILD_WORKBENCH, "buildWorkBench");
achievements.put(BUILD_PICKAXE, "buildPickaxe");
achievements.put(BUILD_FURNACE, "buildFurnace");
achievements.put(ACQUIRE_IRON, "aquireIron");
achievements.put(BUILD_HOE, "buildHoe");
achievements.put(MAKE_BREAD, "makeBread");
achievements.put(BAKE_CAKE,"bakeCake");
achievements.put(BUILD_BETTER_PICKAXE,"buildBetterPickaxe");
achievements.put(COOK_FISH,"cookFish");
achievements.put(ON_A_RAIL,"onARail");
achievements.put(BUILD_SWORD,"buildSword");
achievements.put(KILL_ENEMY,"killEnemy");
achievements.put(KILL_COW,"killCow");
achievements.put(FLY_PIG,"flyPig");
achievements.put(SNIPE_SKELETON,"snipeSkeleton");
achievements.put(GET_DIAMONDS,"diamonds");
achievements.put(NETHER_PORTAL,"portal");
achievements.put(GHAST_RETURN,"ghast");
achievements.put(GET_BLAZE_ROD,"blazerod");
achievements.put(BREW_POTION,"potion");
achievements.put(END_PORTAL,"thEnd");
achievements.put(THE_END,"theEnd2");
achievements.put(ENCHANTMENTS,"enchantments");
achievements.put(OVERKILL,"overkill");
achievements.put(BOOKCASE,"bookacase");
achievements.put(EXPLORE_ALL_BIOMES,"exploreAllBiomes");
achievements.put(SPAWN_WITHER,"spawnWither");
achievements.put(KILL_WITHER,"killWither");
achievements.put(FULL_BEACON,"fullBeacon");
achievements.put(BREED_COW,"breedCow");
achievements.put(DIAMONDS_TO_YOU,"diamondsToYou");
private static final HashMap<Achievement, String> achievements = new HashMap<>();
static {
achievements.put(OPEN_INVENTORY, "openInventory");
achievements.put(MINE_WOOD, "mineWood");
achievements.put(BUILD_WORKBENCH, "buildWorkBench");
achievements.put(BUILD_PICKAXE, "buildPickaxe");
achievements.put(BUILD_FURNACE, "buildFurnace");
achievements.put(ACQUIRE_IRON, "aquireIron");
achievements.put(BUILD_HOE, "buildHoe");
achievements.put(MAKE_BREAD, "makeBread");
achievements.put(BAKE_CAKE, "bakeCake");
achievements.put(BUILD_BETTER_PICKAXE, "buildBetterPickaxe");
achievements.put(COOK_FISH, "cookFish");
achievements.put(ON_A_RAIL, "onARail");
achievements.put(BUILD_SWORD, "buildSword");
achievements.put(KILL_ENEMY, "killEnemy");
achievements.put(KILL_COW, "killCow");
achievements.put(FLY_PIG, "flyPig");
achievements.put(SNIPE_SKELETON, "snipeSkeleton");
achievements.put(GET_DIAMONDS, "diamonds");
achievements.put(NETHER_PORTAL, "portal");
achievements.put(GHAST_RETURN, "ghast");
achievements.put(GET_BLAZE_ROD, "blazerod");
achievements.put(BREW_POTION, "potion");
achievements.put(END_PORTAL, "thEnd");
achievements.put(THE_END, "theEnd2");
achievements.put(ENCHANTMENTS, "enchantments");
achievements.put(OVERKILL, "overkill");
achievements.put(BOOKCASE, "bookacase");
achievements.put(EXPLORE_ALL_BIOMES, "exploreAllBiomes");
achievements.put(SPAWN_WITHER, "spawnWither");
achievements.put(KILL_WITHER, "killWither");
achievements.put(FULL_BEACON, "fullBeacon");
achievements.put(BREED_COW, "breedCow");
achievements.put(DIAMONDS_TO_YOU, "diamondsToYou");
achievements.put(OVERPOWERED, "overpowered");
}
}
/**
* Gets the json id from the bukkit achievement passed as argument
*
* @param achievement the achievement
* @return the achievement's id or null if not found
*/
@ -89,7 +57,7 @@ public final class BookAchievement {
return achievements.get(achievement);
}
private BookAchievement(){
private BookAchievement() {
}
}

View File

@ -1,5 +1,13 @@
package me.skymc.taboolib.bookformatter;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.chat.ComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
@ -8,21 +16,11 @@ import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import lombok.Getter;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.chat.ComponentSerializer;
/**
* The NMS helper for all the Book-API
*/
public final class BookReflection {
private static final String version;
private static final boolean doubleHands;
@ -31,11 +29,11 @@ public final class BookReflection {
private static final Method chatSerializerA;
private static final Method craftPlayerGetHandle;
//This method takes an enum that represents the player's hand only in versions >= 1.9
//In the other versions it only takes the nms item
private static final Method entityPlayerOpenBook;
//only version >= 1.9
private static final Object[] hands;
@ -56,7 +54,7 @@ public final class BookReflection {
final int major, minor;
Pattern pattern = Pattern.compile("v([0-9]+)_([0-9]+)");
Matcher m = pattern.matcher(version);
if(m.find()) {
if (m.find()) {
major = Integer.parseInt(m.group(1));
minor = Integer.parseInt(m.group(2));
} else {
@ -68,7 +66,7 @@ public final class BookReflection {
craftMetaBookField = craftMetaBookClass.getDeclaredField("pages");
craftMetaBookField.setAccessible(true);
Class<?> chatSerializer = getNmsClass("IChatBaseComponent$ChatSerializer", false);
if(chatSerializer == null)
if (chatSerializer == null)
chatSerializer = getNmsClass("ChatSerializer");
chatSerializerA = chatSerializer.getDeclaredMethod("a", String.class);
@ -78,7 +76,7 @@ public final class BookReflection {
final Class<?> entityPlayerClass = getNmsClass("EntityPlayer");
final Class<?> itemStackClass = getNmsClass("ItemStack");
if(doubleHands) {
if (doubleHands) {
final Class<?> enumHandClass = getNmsClass("EnumHand");
entityPlayerOpenBook = entityPlayerClass.getMethod("a", itemStackClass, enumHandClass);
hands = enumHandClass.getEnumConstants();
@ -110,7 +108,8 @@ public final class BookReflection {
/**
* Sets the pages of the book to the components json equivalent
* @param meta the book meta to change
*
* @param meta the book meta to change
* @param components the pages of the book
*/
@SuppressWarnings("unchecked")//reflections = unchecked warnings
@ -118,7 +117,7 @@ public final class BookReflection {
try {
List<Object> pages = (List<Object>) craftMetaBookField.get(meta);
pages.clear();
for(BaseComponent[] c : components) {
for (BaseComponent[] c : components) {
final String json = ComponentSerializer.toString(c);
//System.out.println("page:" + json); //Debug
pages.add(chatSerializerA.invoke(null, json));
@ -127,17 +126,18 @@ public final class BookReflection {
throw new UnsupportedVersionException(e);
}
}
/**
* Append the pages of the book to the components json equivalent
* @param meta the book meta to change
*
* @param meta the book meta to change
* @param components the pages of the book
*/
@SuppressWarnings("unchecked")//reflections = unchecked warnings
public static void addPages(BookMeta meta, BaseComponent[][] components) {
try {
try {
List<Object> pages = (List<Object>) craftMetaBookField.get(meta);
for(BaseComponent[] c : components) {
for (BaseComponent[] c : components) {
final String json = ComponentSerializer.toString(c);
//System.out.println("page:" + json); //Debug
pages.add(chatSerializerA.invoke(null, json));
@ -149,8 +149,9 @@ public final class BookReflection {
/**
* Opens the book to a player (the player needs to have the book in one of his hands)
* @param player the player
* @param book the book to open
*
* @param player the player
* @param book the book to open
* @param offHand false if the book is in the right hand, true otherwise
*/
public static void openBook(Player player, ItemStack book, boolean offHand) {
@ -161,7 +162,7 @@ public final class BookReflection {
entityHumanPlayerConnection.get(toNms(player)),
createBookOpenPacket()
);*/
if(doubleHands) {
if (doubleHands) {
entityPlayerOpenBook.invoke(
toNms(player),
nmsCopy(book),
@ -193,24 +194,27 @@ public final class BookReflection {
/**
* Translates an ItemStack to his Chat-Component equivalent
*
* @param item the item to be converted
* @return a Chat-Component equivalent of the parameter
*/
public static BaseComponent[] itemToComponents(ItemStack item) {
return jsonToComponents(itemToJson(item));
return jsonToComponents(itemToJson(item));
}
/**
* Translates a json string to his Chat-Component equivalent
*
* @param json the json string to be converted
* @return a Chat-Component equivalent of the parameter
*/
public static BaseComponent[] jsonToComponents(String json) {
return new BaseComponent[] { new TextComponent(json) };
return new BaseComponent[]{new TextComponent(json)};
}
/**
* Translates an ItemStack to his json equivalent
*
* @param item the item to be converted
* @return a json equivalent of the parameter
*/
@ -234,16 +238,19 @@ public final class BookReflection {
*/
public static class UnsupportedVersionException extends RuntimeException {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 6835583513394319946L;
/**
* serialVersionUID
*/
private static final long serialVersionUID = 6835583513394319946L;
/**
* The current running version
*/
@Getter
private final String version = BookReflection.version;
public String getVersion() {
return version;
}
public UnsupportedVersionException(Exception e) {
super("Error while executing reflections, submit to developers the following log (version: " + BookReflection.version + ")", e);
}
@ -252,10 +259,11 @@ public final class BookReflection {
/**
* Gets the EntityPlayer handled by the argument
*
* @param player the Player handler
* @return the handled class
* @throws InvocationTargetException when some problems are found with the reflection
* @throws IllegalAccessException when some problems are found with the reflection
* @throws IllegalAccessException when some problems are found with the reflection
*/
public static Object toNms(Player player) throws InvocationTargetException, IllegalAccessException {
return craftPlayerGetHandle.invoke(player);
@ -263,10 +271,11 @@ public final class BookReflection {
/**
* Creates a NMS copy of the parameter
*
* @param item the ItemStack to be nms-copied
* @return a NMS-ItemStack that is the equivalent of the one passed as argument
* @throws InvocationTargetException when some problems are found with the reflection
* @throws IllegalAccessException when some problems are found with the reflection
* @throws IllegalAccessException when some problems are found with the reflection
*/
public static Object nmsCopy(ItemStack item) throws InvocationTargetException, IllegalAccessException {
return craftItemStackAsNMSCopy.invoke(null, item);
@ -275,8 +284,8 @@ public final class BookReflection {
public static Class<?> getNmsClass(String className, boolean log) {
try {
return Class.forName("net.minecraft.server." + version + "." + className);
} catch(ClassNotFoundException e) {
if(log)
} catch (ClassNotFoundException e) {
if (log)
e.printStackTrace();
return null;
}
@ -290,7 +299,7 @@ public final class BookReflection {
private static Class<?> getCraftClass(String path) {
try {
return Class.forName("org.bukkit.craftbukkit." + version + "." + path);
} catch(ClassNotFoundException e) {
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}

View File

@ -1,8 +1,5 @@
package me.skymc.taboolib.bookformatter.action;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.experimental.Accessors;
import net.md_5.bungee.api.chat.ClickEvent;
/**
@ -10,15 +7,17 @@ import net.md_5.bungee.api.chat.ClickEvent;
* @since 2018-03-08 22:38:04
*/
public interface ClickAction {
/**
* Get the Chat-Component action
*
* @return the Chat-Component action
*/
ClickEvent.Action action();
/**
* The value paired to the action
*
* @return the value paired tot the action
*/
String value();
@ -26,6 +25,7 @@ public interface ClickAction {
/**
* Creates a command action: when the player clicks, the command passed as parameter gets executed with the clicker as sender
*
* @param command the command to be executed
* @return a new ClickAction
*/
@ -35,6 +35,7 @@ public interface ClickAction {
/**
* Creates a suggest_command action: when the player clicks, the book closes and the chat opens with the parameter written into it
*
* @param command the command to be suggested
* @return a new ClickAction
*/
@ -44,11 +45,12 @@ public interface ClickAction {
/**
* Creates a open_utl action: when the player clicks the url passed as argument will open in the browser
*
* @param url the url to be opened
* @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
throw new IllegalArgumentException("Invalid url: \"" + url + "\", it should start with http:// or https://");
@ -56,6 +58,7 @@ public interface ClickAction {
/**
* Creates a change_page action: when the player clicks the book page will be set at the value passed as argument
*
* @param page the new page
* @return a new ClickAction
*/
@ -63,11 +66,32 @@ public interface ClickAction {
return new SimpleClickAction(ClickEvent.Action.CHANGE_PAGE, Integer.toString(page));
}
@Getter
@Accessors(fluent = true)
@RequiredArgsConstructor
class SimpleClickAction implements ClickAction {
private final ClickEvent.Action action;
private final String value;
public SimpleClickAction(ClickEvent.Action action, String value) {
this.action = action;
this.value = value;
}
public ClickEvent.Action getAction() {
return action;
}
public String getValue() {
return value;
}
@Override
public ClickEvent.Action action() {
return null;
}
@Override
public String value() {
return null;
}
}
}

View File

@ -1,18 +1,15 @@
package me.skymc.taboolib.bookformatter.action;
import java.util.UUID;
import org.bukkit.Achievement;
import org.bukkit.entity.Entity;
import org.bukkit.inventory.ItemStack;
import lombok.Getter;
import lombok.experimental.Accessors;
import me.skymc.taboolib.bookformatter.BookAchievement;
import me.skymc.taboolib.bookformatter.BookReflection;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Achievement;
import org.bukkit.entity.Entity;
import org.bukkit.inventory.ItemStack;
import java.util.UUID;
/**
* @author sky
@ -20,14 +17,17 @@ import net.md_5.bungee.api.chat.TextComponent;
*/
@SuppressWarnings("deprecation")
public interface HoverAction {
/**
* Get the Chat-Component action
*
* @return the Chat-Component action
*/
HoverEvent.Action action();
/**
* The value paired to the action
*
* @return the value paired tot the action
*/
BaseComponent[] value();
@ -35,6 +35,7 @@ public interface HoverAction {
/**
* Creates a show_text action: when the component is hovered the text used as parameter will be displayed
*
* @param text the text to display
* @return a new HoverAction instance
*/
@ -44,6 +45,7 @@ public interface HoverAction {
/**
* Creates a show_text action: when the component is hovered the text used as parameter will be displayed
*
* @param text the text to display
* @return a new HoverAction instance
*/
@ -53,6 +55,7 @@ public interface HoverAction {
/**
* Creates a show_item action: when the component is hovered some item information will be displayed
*
* @param item a component array representing item to display
* @return a new HoverAction instance
*/
@ -62,6 +65,7 @@ public interface HoverAction {
/**
* Creates a show_item action: when the component is hovered some item information will be displayed
*
* @param item the item to display
* @return a new HoverAction instance
*/
@ -71,6 +75,7 @@ public interface HoverAction {
/**
* Creates a show_entity action: when the component is hovered some entity information will be displayed
*
* @param entity a component array representing the item to display
* @return a new HoverAction instance
*/
@ -80,6 +85,7 @@ public interface HoverAction {
/**
* Creates a show_entity action: when the component is hovered some entity information will be displayed
*
* @param uuid the entity's UniqueId
* @param type the entity's type
* @param name the entity's name
@ -95,15 +101,17 @@ public interface HoverAction {
/**
* Creates a show_entity action: when the component is hovered some entity information will be displayed
*
* @param entity the item to display
* @return a new HoverAction instance
*/
static HoverAction showEntity(Entity entity) {
static HoverAction showEntity(Entity entity) {
return showEntity(entity.getUniqueId(), entity.getType().getName(), entity.getName());
}
/**
* Creates a show_achievement action: when the component is hovered the achievement information will be displayed
*
* @param achievementId the id of the achievement to display
* @return a new HoverAction instance
*/
@ -113,15 +121,17 @@ public interface HoverAction {
/**
* Creates a show_achievement action: when the component is hovered the achievement information will be displayed
*
* @param achievement the achievement to display
* @return a new HoverAction instance
*/
static HoverAction showAchievement(Achievement achievement) {
static HoverAction showAchievement(Achievement achievement) {
return showAchievement(BookAchievement.toId(achievement));
}
/**
* Creates a show_achievement action: when the component is hovered the statistic information will be displayed
*
* @param statisticId the id of the statistic to display
* @return a new HoverAction instance
*/
@ -129,8 +139,6 @@ public interface HoverAction {
return new SimpleHoverAction(HoverEvent.Action.SHOW_ACHIEVEMENT, new TextComponent("statistic." + statisticId));
}
@Getter
@Accessors(fluent = true)
class SimpleHoverAction implements HoverAction {
private final HoverEvent.Action action;
private final BaseComponent[] value;
@ -139,5 +147,23 @@ public interface HoverAction {
this.action = action;
this.value = value;
}
public HoverEvent.Action getAction() {
return action;
}
public BaseComponent[] getValue() {
return value;
}
@Override
public HoverEvent.Action action() {
return null;
}
@Override
public BaseComponent[] value() {
return new BaseComponent[0];
}
}
}

View File

@ -1,8 +1,5 @@
package me.skymc.taboolib.bookformatter.builder;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import me.skymc.taboolib.bookformatter.action.ClickAction;
import me.skymc.taboolib.bookformatter.action.HoverAction;
import net.md_5.bungee.api.chat.BaseComponent;
@ -14,31 +11,54 @@ import net.md_5.bungee.api.chat.TextComponent;
* @author sky
* @since 2018-03-08 22:37:27
*/
@Setter
@Getter
@Accessors(fluent = true, chain = true)
public class TextBuilder {
private String text = "";
private ClickAction onClick = null;
private HoverAction onHover = null;
public TextBuilder() {}
public String getText() {
return text;
}
public ClickAction getClick() {
return onClick;
}
public HoverAction getHover() {
return onHover;
}
public void text(String text) {
this.text = text;
}
public void onClick(ClickAction onClick) {
this.onClick = onClick;
}
public void onHover(HoverAction onHover) {
this.onHover = onHover;
}
public TextBuilder() {
}
public TextBuilder(String text) {
this.text = text;
this.text = text;
}
/**
* Creates the component representing the built text
*
* @return the component representing the built text
*/
public BaseComponent build() {
TextComponent res = new TextComponent(text);
if(onClick != null) {
if (onClick != null) {
res.setClickEvent(new ClickEvent(onClick.action(), onClick.value()));
}
if(onHover != null) {
if (onHover != null) {
res.setHoverEvent(new HoverEvent(onHover.action(), onHover.value()));
}
return res;
@ -46,10 +66,11 @@ public class TextBuilder {
/**
* Creates a new TextBuilder with the parameter as his initial text
*
* @param text initial text
* @return a new TextBuilder with the parameter as his initial text
*/
public static TextBuilder of(String text) {
return new TextBuilder().text(text);
return new TextBuilder(text);
}
}

View File

@ -1,100 +1,67 @@
package me.skymc.taboolib.commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import me.skymc.taboolib.commands.sub.AttributesCommand;
import me.skymc.taboolib.commands.sub.EnchantCommand;
import me.skymc.taboolib.commands.sub.FlagCommand;
import me.skymc.taboolib.commands.sub.HelpCommand;
import me.skymc.taboolib.commands.sub.ImportCommand;
import me.skymc.taboolib.commands.sub.InfoCommand;
import me.skymc.taboolib.commands.sub.ItemCommand;
import me.skymc.taboolib.commands.sub.PotionCommand;
import me.skymc.taboolib.commands.sub.SaveCommand;
import me.skymc.taboolib.commands.sub.SlotCommand;
import me.skymc.taboolib.commands.sub.TagDeleteCommand;
import me.skymc.taboolib.commands.sub.TagPrefixCommand;
import me.skymc.taboolib.commands.sub.TagSuffixCommand;
import me.skymc.taboolib.commands.sub.VariableGetCommand;
import me.skymc.taboolib.commands.sub.VariableSetCommand;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.commands.sub.*;
import me.skymc.taboolib.commands.sub.cycle.CycleCommand;
import me.skymc.taboolib.commands.sub.itemlist.ItemListCommand;
import me.skymc.taboolib.commands.sub.shell.ShellCommand;
import me.skymc.taboolib.commands.sub.sounds.SoundsCommand;
import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.message.MsgUtils;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
public class MainCommands implements CommandExecutor{
import java.lang.reflect.Parameter;
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (args.length == 0 || args[0].equalsIgnoreCase("help")) {
new HelpCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("itemreload") || args[0].equalsIgnoreCase("ireload")) {
ItemUtils.reloadItemCache();
ItemUtils.reloadItemName();
MsgUtils.send(sender, "重载成功");
}
else if (args[0].equalsIgnoreCase("save")) {
new SaveCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("enchants")) {
new EnchantCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("potions")) {
new PotionCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("flags")) {
new FlagCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("attributes")) {
new AttributesCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("slots")) {
new SlotCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("importdata")) {
new ImportCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("iteminfo")) {
new InfoCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("itemlist")) {
new ItemListCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("item") || args[0].equalsIgnoreCase("i")) {
new ItemCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("setvariable")) {
new VariableSetCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("getvariable")) {
new VariableGetCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("shell") || args[0].equalsIgnoreCase("s")) {
new ShellCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("cycle") || args[0].equalsIgnoreCase("c")) {
new CycleCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("sounds")) {
new SoundsCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("tagprefix")) {
new TagPrefixCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("tagsuffix")) {
new TagSuffixCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("tagdelete")) {
new TagDeleteCommand(sender, args);
}
else {
MsgUtils.send(sender, "&4指令错误");
}
return true;
}
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")) {
new SaveCommand(sender, args);
} else if (args[0].equalsIgnoreCase("enchants")) {
new EnchantCommand(sender, args);
} else if (args[0].equalsIgnoreCase("potions")) {
new PotionCommand(sender, args);
} else if (args[0].equalsIgnoreCase("flags")) {
new FlagCommand(sender, args);
} else if (args[0].equalsIgnoreCase("attributes")) {
new AttributesCommand(sender, args);
} else if (args[0].equalsIgnoreCase("slots")) {
new SlotCommand(sender, args);
} else if (args[0].equalsIgnoreCase("importdata")) {
new ImportCommand(sender, args);
} else if (args[0].equalsIgnoreCase("iteminfo")) {
new InfoCommand(sender, args);
} else if (args[0].equalsIgnoreCase("itemlist")) {
new ItemListCommand(sender, args);
} else if (args[0].equalsIgnoreCase("item") || args[0].equalsIgnoreCase("i")) {
new ItemCommand(sender, args);
} else if (args[0].equalsIgnoreCase("setvariable")) {
new VariableSetCommand(sender, args);
} else if (args[0].equalsIgnoreCase("getvariable")) {
new VariableGetCommand(sender, args);
} else if (args[0].equalsIgnoreCase("shell") || args[0].equalsIgnoreCase("s")) {
new ShellCommand(sender, args);
} else if (args[0].equalsIgnoreCase("cycle") || args[0].equalsIgnoreCase("c")) {
new CycleCommand(sender, args);
} else if (args[0].equalsIgnoreCase("sounds")) {
new SoundsCommand(sender, args);
} else if (args[0].equalsIgnoreCase("tagprefix")) {
new TagPrefixCommand(sender, args);
} else if (args[0].equalsIgnoreCase("tagsuffix")) {
new TagSuffixCommand(sender, args);
} else if (args[0].equalsIgnoreCase("tagdelete")) {
new TagDeleteCommand(sender, args);
} else if (args[0].equalsIgnoreCase("itemreload") || args[0].equalsIgnoreCase("ireload")) {
ItemUtils.reloadItemCache();
ItemUtils.reloadItemName();
TLocale.sendTo(sender, "COMMANDS.RELOAD.SUCCESS-NORMAL");
} else {
TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN");
}
return true;
}
}

View File

@ -3,36 +3,34 @@ package me.skymc.taboolib.commands;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public abstract class SubCommand {
public CommandSender sender;
public String[] args;
public boolean returnValue = false;
public SubCommand(CommandSender sender, String[] args) {
this.sender = sender;
this.args = args;
}
public boolean setReturn(boolean returnValue) {
return this.returnValue = returnValue;
}
public boolean isPlayer() {
return sender instanceof Player;
}
public boolean command() {
return returnValue;
}
public String getArgs(int size) {
StringBuilder sb = new StringBuilder();
for (int i = size ; i < args.length ; i++) {
sb.append(args[i]);
sb.append(" ");
}
return sb.toString().substring(0, sb.length() - 1);
}
public CommandSender sender;
public String[] args;
public boolean returnValue = false;
public SubCommand(CommandSender sender, String[] args) {
this.sender = sender;
this.args = args;
}
public boolean setReturn(boolean returnValue) {
return this.returnValue = returnValue;
}
public boolean isPlayer() {
return sender instanceof Player;
}
public boolean command() {
return returnValue;
}
public String getArgs(int size) {
return IntStream.range(size, args.length).mapToObj(i -> args[i] + " ").collect(Collectors.joining()).trim();
}
}

View File

@ -30,7 +30,7 @@ public class Language2Command implements CommandExecutor {
else if (args[0].equalsIgnoreCase("reload")) {
MsgUtils.send(sender, "§7重载中..");
long time = System.currentTimeMillis();
Main.getExampleLangauge2().reload();
Main.getExampleLanguage2().reload();
MsgUtils.send(sender, "§7重载完成! 耗时: &f" + (System.currentTimeMillis() - time) + "ms");
}
else if (args[0].equalsIgnoreCase("send")) {
@ -42,7 +42,7 @@ public class Language2Command implements CommandExecutor {
long time = System.currentTimeMillis();
// 获取语言文件
Language2Value value = Main.getExampleLangauge2().get(args[2]);
Language2Value value = Main.getExampleLanguage2().get(args[2]);
// 如果有变量参数
if (args.length > 3) {
int i = 0;

View File

@ -1,15 +1,16 @@
package me.skymc.taboolib.commands.locale;
import java.util.ArrayList;
import java.util.List;
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;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.ilummc.tlib.resources.TLocale;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
/**
* @author sky
@ -17,59 +18,59 @@ import com.ilummc.tlib.resources.TLocale;
*/
public class TabooLibLocaleCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command arg1, String label, String[] args) {
if (args.length == 0) {
TLocale.sendTo(sender, "commands-taboolocale-helps", label);
}
else if (args[0].equalsIgnoreCase("send")) {
send(sender, args);
}
else if (args[0].equalsIgnoreCase("reload")) {
reload(sender);
}
else {
TLocale.sendTo(sender, "commands-taboolocale-invalid");
}
return true;
}
void send(CommandSender sender, String[] args) {
if (args.length < 3) {
TLocale.sendTo(sender, "commands-taboolocale-send-empty");
return;
}
List<Player> target = new ArrayList<>();
if (args[1].equalsIgnoreCase("all")) {
target.addAll(Bukkit.getOnlinePlayers());
} else {
Player player = Bukkit.getPlayerExact(args[1]);
if (player == null) {
TLocale.sendTo(sender, "commands-taboolocale-send-offline", args[1]);
return;
}
target.add(player);
}
if (args.length > 3) {
String[] vars = new String[args.length - 3];
for (int i = 3 ; i < args.length ; i++) {
vars[i - 3] = args[i];
}
target.forEach(x -> TLocale.sendTo(x, args[2], vars));
} else {
target.forEach(x -> TLocale.sendTo(x, args[2]));
}
if (sender instanceof Player) {
TLocale.sendTo(sender, "commands-taboolocale-send-success");
}
}
void reload(CommandSender sender) {
TLocale.reload();
TLocale.sendTo(sender, "commands-taboolocale-reload");
}
@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")) {
send(sender, args);
} else if (args[0].equalsIgnoreCase("reload")) {
reload(sender);
} else {
MsgUtils.send(sender, "§4参数错误");
}
return true;
}
void send(CommandSender sender, String[] args) {
if (args.length < 3) {
MsgUtils.send(sender, "§4参数错误");
return;
}
List<Player> target = new ArrayList<>();
if (args[1].equalsIgnoreCase("all")) {
target.addAll(Bukkit.getOnlinePlayers());
} else {
Player player = Bukkit.getPlayerExact(args[1]);
if (player == null) {
MsgUtils.send(sender, "§4玩家不在线");
return;
}
target.add(player);
}
if (args.length > 3) {
String[] vars = new String[args.length - 3];
IntStream.range(3, args.length).forEach(i -> vars[i - 3] = args[i]);
target.forEach(x -> TLocale.sendTo(x, args[2], vars));
} else {
target.forEach(x -> TLocale.sendTo(x, args[2]));
}
if (sender instanceof Player) {
MsgUtils.send(sender, "§7信息已发送");
}
}
void reload(CommandSender sender) {
TLocale.reload();
MsgUtils.send(sender, "§7重载完成");
}
}

View File

@ -1,6 +1,8 @@
package me.skymc.taboolib.commands.sub;
import com.ilummc.tlib.resources.TLocale;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import me.skymc.taboolib.commands.SubCommand;
@ -8,28 +10,17 @@ import me.skymc.taboolib.jsonformatter.JSONFormatter;
import me.skymc.taboolib.jsonformatter.click.SuggestCommandEvent;
import me.skymc.taboolib.jsonformatter.hover.ShowTextEvent;
import java.util.Arrays;
public class AttributesCommand extends SubCommand {
public AttributesCommand(CommandSender sender, String[] args) {
super(sender, args);
sender.sendMessage("§f");
sender.sendMessage("§b§l----- §3§lItemStack Attributes §b§l-----");
sender.sendMessage("§f");
String[] attributes = new String[] { "damage", "speed", "attackspeed", "health", "knockback", "armor", "luck" };
for (String name : attributes) {
if (isPlayer()) {
JSONFormatter json = new JSONFormatter();
json.append(" §7- §f" + name);
json.appendHoverClick(" §8(点击复制)", new ShowTextEvent("§f点击复制"), new SuggestCommandEvent(name));
json.send((Player) sender);
}
else {
sender.sendMessage(" §7- §f" + name);
}
}
sender.sendMessage("§f");
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ATTRIBUTES.HEAD");
Arrays.stream(new String[] { "damage", "speed", "attackspeed", "health", "knockback", "armor", "luck" }).forEach(attribute -> TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ATTRIBUTES.BODY", attribute));
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ATTRIBUTES.FOOT");
}
}

View File

@ -1,35 +1,22 @@
package me.skymc.taboolib.commands.sub;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.commands.SubCommand;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import me.skymc.taboolib.commands.SubCommand;
import me.skymc.taboolib.jsonformatter.JSONFormatter;
import me.skymc.taboolib.jsonformatter.click.SuggestCommandEvent;
import me.skymc.taboolib.jsonformatter.hover.ShowTextEvent;
import java.util.Arrays;
public class EnchantCommand extends SubCommand {
@SuppressWarnings("deprecation")
public EnchantCommand(CommandSender sender, String[] args) {
super(sender, args);
sender.sendMessage("§f");
sender.sendMessage("§b§l----- §3§lItemStack Enchantments §b§l-----");
sender.sendMessage("§f");
for (Enchantment enchant : Enchantment.values()) {
if (isPlayer()) {
JSONFormatter json = new JSONFormatter();
json.append(" §7- §f" + enchant.getId() + ". " + enchant.getName());
json.appendHoverClick(" §8(点击复制)", new ShowTextEvent("§f点击复制"), new SuggestCommandEvent(enchant.getName()));
json.send((Player) sender);
}
else {
sender.sendMessage(" §7- §f" + enchant.getId() + ". " + enchant.getName());
}
}
sender.sendMessage("§f");
}
@SuppressWarnings("deprecation")
public EnchantCommand(CommandSender sender, String[] args) {
super(sender, args);
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ENCHANTS.HEAD");
Arrays.stream(Enchantment.values()).forEach(enchant -> TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ENCHANTS.BODY", String.valueOf(enchant.getId()), enchant.getName()));
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ENCHANTS.FOOT");
}
}

View File

@ -1,6 +1,8 @@
package me.skymc.taboolib.commands.sub;
import com.ilummc.tlib.resources.TLocale;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemFlag;
@ -9,26 +11,17 @@ import me.skymc.taboolib.jsonformatter.JSONFormatter;
import me.skymc.taboolib.jsonformatter.click.SuggestCommandEvent;
import me.skymc.taboolib.jsonformatter.hover.ShowTextEvent;
import java.util.Arrays;
public class FlagCommand extends SubCommand {
public FlagCommand(CommandSender sender, String[] args) {
super(sender, args);
sender.sendMessage("§f");
sender.sendMessage("§b§l----- §3§lItemStack Flags §b§l-----");
sender.sendMessage("§f");
for (ItemFlag flag : ItemFlag.values()) {
if (isPlayer()) {
JSONFormatter json = new JSONFormatter();
json.append(" §7- §f" + flag.name());
json.appendHoverClick(" §8(点击复制)", new ShowTextEvent("§f点击复制"), new SuggestCommandEvent(flag.name()));
json.send((Player) sender);
}
else {
sender.sendMessage(" §7- §f" + flag.name());
}
}
sender.sendMessage("§f");
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.FLAGS.HEAD");
Arrays.stream(ItemFlag.values()).forEach(itemFlag -> TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ENCHANTS.BODY", itemFlag.name()));
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.FLAGS.FOOT");
}
}

View File

@ -1,84 +0,0 @@
package me.skymc.taboolib.commands.sub;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import me.skymc.taboolib.TabooLib;
import me.skymc.taboolib.commands.SubCommand;
import me.skymc.taboolib.jsonformatter.JSONFormatter;
import me.skymc.taboolib.jsonformatter.click.SuggestCommandEvent;
import me.skymc.taboolib.jsonformatter.hover.ShowTextEvent;
public class HelpCommand extends SubCommand {
public HelpCommand(CommandSender sender, String[] args) {
super(sender, args);
HashMap<String, String> helps = new LinkedHashMap<>();
helps.put("/taboolib save §8[§7名称§8]", "§e保存手中物品");
helps.put("/taboolib item §8[§7名称§8] §8<§7玩家§8> §8<§7数量§8>", "§e给予玩家物品");
helps.put("/taboolib iteminfo", "§e查看物品信息");
helps.put("/taboolib itemlist", "§e查看所有物品");
helps.put("/taboolib itemreload", "§e重载物品缓存");
helps.put("§a", null);
helps.put("/taboolib attributes", "§e查看所有属性");
helps.put("/taboolib enchants", "§e查看所有附魔");
helps.put("/taboolib potions", "§e查看所有药水");
helps.put("/taboolib flags", "§e查看所有标签");
helps.put("/taboolib slots", "§e查看所有部位");
helps.put("/taboolib sounds", "§e查看所有音效");
helps.put("§b", null);
helps.put("/taboolib getvariable §8[§7-s|a§8] §8[§7键§8]", "§e查看变量");
helps.put("/taboolib setvariable §8[§7-s|a§8] §8[§7键§8] §8[§7值§8]", "§e更改变量");
helps.put("§c", null);
helps.put("/taboolib cycle list", "§e列出所有时间检查器");
helps.put("/taboolib cycle info §8[§7名称§8]", "§e查询检查器信息");
helps.put("/taboolib cycle reset §8[§7名称§8]", "§e初始化时间检查器");
helps.put("/taboolib cycle update §8[§7名称§8]", "§e更新时间检查器");
helps.put("§f", null);
helps.put("/taboolib shell load §8[§7名称§8]", "§e载入某个脚本");
helps.put("/taboolib shell unload §8[§7名称§8]", "§e卸载某个脚本");
helps.put("§g", null);
helps.put("/taboolib tagprefix §8[§7名称§8] §8[§7文本§8]", "§e设置玩家头顶前缀");
helps.put("/taboolib tagsuffix §8[§7名称§8] §8[§7文本§8]", "§e设置玩家头顶后缀");
helps.put("/taboolib tagdelete §8[§7名称§8]", "§e删除玩家称号数据");
helps.put("§e", null);
helps.put("/taboolib importdata", "§4向数据库导入本地数据 §8(该操作将会清空数据库)");
if (sender instanceof ConsoleCommandSender || TabooLib.getVerint() < 10900) {
sender.sendMessage("§f");
sender.sendMessage("§b§l----- §3§lTaooLib Commands §b§l-----");
sender.sendMessage("§f");
// 遍历命令
for (Entry<String, String> entry : helps.entrySet()) {
if (entry.getValue() == null) {
sender.sendMessage("§f");
} else {
sender.sendMessage("§f " + entry.getKey() + " §6- " + entry.getValue());
}
}
sender.sendMessage("§f");
}
else if (sender instanceof Player) {
JSONFormatter json = new JSONFormatter();
json.append("§f"); json.newLine();
json.append("§b§l----- §3§lTaooLib Commands §b§l-----"); json.newLine();
json.append("§f"); json.newLine();
// 遍历命令
for (Entry<String, String> entry : helps.entrySet()) {
if (entry.getValue() == null) {
json.append("§f"); json.newLine();
} else {
json.appendHoverClick("§f " + entry.getKey() + " §6- " + entry.getValue(), new ShowTextEvent("§f点击复制指令"), new SuggestCommandEvent(entry.getKey().split("§")[0])); json.newLine();
}
}
json.append("§f");
json.send((Player) sender);
}
}
}

View File

@ -1,7 +1,9 @@
package me.skymc.taboolib.commands.sub;
import java.io.File;
import java.util.Objects;
import com.ilummc.tlib.resources.TLocale;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
@ -18,28 +20,34 @@ public class ImportCommand extends SubCommand {
super(sender, args);
if (isPlayer()) {
MsgUtils.warn("改命令只能由控制台输入");
TLocale.sendTo(sender, "COMMANDS.GLOBAL.ONLY-PLAYER");
return;
}
else if (Main.getStorageType() == StorageType.LOCAL) {
MsgUtils.warn("只有启用数据库储存时才能这么做");
if (Main.getStorageType() == StorageType.LOCAL) {
TLocale.Logger.warn("COMMANDS.GLOBAL.ONLY-STORAGE-SQL");
return;
}
else {
MsgUtils.send("正在清空数据库...");
Main.getConnection().truncateTable(Main.getTablePrefix() + "_playerdata");
MsgUtils.send("开始导入玩家数据...");
int size = Main.getPlayerDataFolder().listFiles().length;
int loop = 1;
for (File file : Main.getPlayerDataFolder().listFiles()) {
FileConfiguration conf = YamlConfiguration.loadConfiguration(file);
Main.getConnection().intoValue(Main.getTablePrefix() + "_playerdata", file.getName().replace(".yml", ""), ConfigUtils.encodeYAML(conf));
MsgUtils.send("导入玩家: &f" + file.getName().replace(".yml", "") + " &7进度: &f" + loop + "/" + size);
loop++;
}
MsgUtils.send("导入完成!");
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.IMPORTDATA.CLEARING");
Main.getConnection().truncateTable(Main.getTablePrefix() + "_playerdata");
if (!Main.getPlayerDataFolder().exists()) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.IMPORTDATA.EMPTYDATA");
return;
}
int size = Objects.requireNonNull(Main.getPlayerDataFolder().listFiles()).length;
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.IMPORTDATA.IMPORTING-START", String.valueOf(size));
int loop = 1;
for (File file : Objects.requireNonNull(Main.getPlayerDataFolder().listFiles())) {
Main.getConnection().intoValue(Main.getTablePrefix() + "_playerdata", file.getName().replace(".yml", ""), ConfigUtils.encodeYAML(YamlConfiguration.loadConfiguration(file)));
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.IMPORTDATA.IMPORTING-PROGRESS", file.getName().replace(".yml", ""), String.valueOf(loop), String.valueOf(size));
loop++;
}
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.IMPORTDATA.SUCCESS");
}
}

View File

@ -1,51 +1,30 @@
package me.skymc.taboolib.commands.sub;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.commands.SubCommand;
import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.itemnbtapi.NBTItem;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import me.skymc.taboolib.commands.SubCommand;
import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.itemnbtapi.NBTItem;
import me.skymc.taboolib.jsonformatter.JSONFormatter;
import me.skymc.taboolib.jsonformatter.click.SuggestCommandEvent;
import me.skymc.taboolib.jsonformatter.hover.ShowItemEvent;
import me.skymc.taboolib.jsonformatter.hover.ShowTextEvent;
import me.skymc.taboolib.message.MsgUtils;
public class InfoCommand extends SubCommand {
@SuppressWarnings("deprecation")
public InfoCommand(CommandSender sender, String[] args) {
super(sender, args);
if (isPlayer()) {
Player player = (Player) sender;
if (player.getItemInHand().getType().equals(Material.AIR)) {
MsgUtils.send(player, "&7请手持正确物品");
}
else {
sender.sendMessage("§f");
sender.sendMessage("§b§l----- §3§lItemStack Info §b§l-----");
sender.sendMessage("§f");
JSONFormatter json = new JSONFormatter();
json.append("§7 - 物品材质: §f"); json.appendHoverClick("§f" + player.getItemInHand().getType().name(), new ShowTextEvent("§f点击复制"), new SuggestCommandEvent(player.getItemInHand().getType().name()));
json.newLine();
json.append("§7 - 物品名称: §f"); json.appendHoverClick("§f" + ItemUtils.getCustomName(player.getItemInHand()), new ShowTextEvent("§f点击复制"), new SuggestCommandEvent(ItemUtils.getCustomName(player.getItemInHand()).replace("§", "&")));
json.newLine();
json.append("§7 - 物品序号: §f" + player.getItemInHand().getTypeId() + ":" + player.getItemInHand().getDurability());
json.newLine();
json.append("§7 - 物品展示: §f"); json.appendHover(ItemUtils.getCustomName(player.getItemInHand()), new ShowItemEvent(player.getItemInHand()));
json.send(player);
NBTItem nbt = new NBTItem(((Player) sender).getItemInHand());
sender.sendMessage("§7 - 物品 NBT: §f");
sender.sendMessage("§f");
sender.sendMessage(nbt.toString());
sender.sendMessage("§f");
}
}
}
@SuppressWarnings("deprecation")
public InfoCommand(CommandSender sender, String[] args) {
super(sender, args);
if (isPlayer()) {
Player player = (Player) sender;
if (player.getItemInHand().getType().equals(Material.AIR)) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.INFO.INVALID-ITEM");
} else {
NBTItem nbt = new NBTItem(player.getItemInHand());
TLocale.sendTo(sender, "COMAMNDS.TABOOLIB.INFO.ITEM-INFO",
player.getItemInHand().getType().name(),
ItemUtils.getCustomName(player.getItemInHand()),
player.getItemInHand().getTypeId() + ":" + player.getItemInHand().getDurability(),
nbt.toString());
}
}
}
}

View File

@ -1,77 +1,64 @@
package me.skymc.taboolib.commands.sub;
import java.util.HashMap;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.commands.SubCommand;
import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.message.MsgUtils;
import me.skymc.taboolib.other.NumberUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import me.skymc.taboolib.commands.SubCommand;
import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.message.MsgUtils;
import me.skymc.taboolib.other.NumberUtils;
import java.util.HashMap;
public class ItemCommand extends SubCommand {
/**
* /TabooLib item
*
* @param sender
* @param args
*/
public ItemCommand(CommandSender sender, String[] args) {
super(sender, args);
if (args.length < 2) {
MsgUtils.send(sender, "请输入正确的物品名称");
setReturn(false);
}
else {
if (ItemUtils.getCacheItem(args[1]) == null) {
MsgUtils.send(sender, "物品 &f" + args[1] + "&7 不存在");
setReturn(false);
return;
}
Player player;
Integer amount = 1;
ItemStack item = ItemUtils.getCacheItem(args[1]).clone();
if (args.length > 2) {
player = Bukkit.getPlayerExact(args[2]);
if (player == null) {
MsgUtils.send(sender, "玩家 &f" + args[2] + "&7 不在线");
setReturn(false);
return;
}
}
else if (sender instanceof Player) {
player = (Player) sender;
}
else {
MsgUtils.send(sender, "后台不允许这么做");
setReturn(false);
return;
}
if (args.length > 3) {
amount = NumberUtils.getInteger(args[3]);
if (amount < 1) {
MsgUtils.send(sender, "数量必须大于0");
setReturn(false);
return;
}
}
item.setAmount(amount);
HashMap<Integer, ItemStack> map = player.getInventory().addItem(item);
if (map.size() > 0) {
player.getWorld().dropItem(player.getLocation(), item);
}
MsgUtils.send(sender, "物品已发送至玩家 &f" + player.getName() + " &7的背包中");
setReturn(true);
}
}
public ItemCommand(CommandSender sender, String[] args) {
super(sender, args);
if (args.length < 2) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEM.INVALID-NAME");
return;
}
if (ItemUtils.getCacheItem(args[1]) == null) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEM.INVALID-ITEM", args[1]);
return;
}
Player player;
Integer amount = 1;
ItemStack item = ItemUtils.getCacheItem(args[1]).clone();
if (args.length > 2) {
player = Bukkit.getPlayerExact(args[2]);
if (player == null) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEM.INVALID-PLAYER", args[2]);
return;
}
} else if (sender instanceof Player) {
player = (Player) sender;
} else {
TLocale.sendTo(sender, "COMMANDS.GLOBAL.ONLY-PLAYER");
return;
}
if (args.length > 3) {
amount = NumberUtils.getInteger(args[3]);
if (amount < 1) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEM.INVALID-NUMBER");
return;
}
}
item.setAmount(amount);
HashMap<Integer, ItemStack> map = player.getInventory().addItem(item);
if (map.size() > 0) {
player.getWorld().dropItem(player.getLocation(), item);
}
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEM.SUCCESS", player.getName());
setReturn(true);
}
}

View File

@ -1,6 +1,8 @@
package me.skymc.taboolib.commands.sub;
import com.ilummc.tlib.resources.TLocale;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType;
@ -9,29 +11,22 @@ import me.skymc.taboolib.jsonformatter.JSONFormatter;
import me.skymc.taboolib.jsonformatter.click.SuggestCommandEvent;
import me.skymc.taboolib.jsonformatter.hover.ShowTextEvent;
import java.util.Arrays;
public class PotionCommand extends SubCommand {
@SuppressWarnings("deprecation")
public PotionCommand(CommandSender sender, String[] args) {
super(sender, args);
sender.sendMessage("§f");
sender.sendMessage("§b§l----- §3§lPotionEffect Types §b§l-----");
sender.sendMessage("§f");
for (PotionEffectType type : PotionEffectType.values()) {
if (type != null) {
if (isPlayer()) {
JSONFormatter json = new JSONFormatter();
json.append(" §7- §f" + type.getId() + ". " + type.getName());
json.appendHoverClick(" §8(点击复制)", new ShowTextEvent("§f点击复制"), new SuggestCommandEvent(type.getName()));
json.send((Player) sender);
}
else {
sender.sendMessage(" §7- §f" + type.getId() + ". " + type.getName() + "");
}
}
}
sender.sendMessage("§f");
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.POTIONS.HEAD");
for (PotionEffectType potionEffectType : PotionEffectType.values()) {
if (potionEffectType != null) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.POTIONS.BODY", String.valueOf(potionEffectType.getId()), potionEffectType.getName());
}
}
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.POTIONS.FOOT");
}
}

View File

@ -1,11 +1,6 @@
package me.skymc.taboolib.commands.sub;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.commands.SubCommand;
import me.skymc.taboolib.fileutils.ConfigUtils;
@ -14,76 +9,78 @@ import me.skymc.taboolib.message.ChatCatcher;
import me.skymc.taboolib.message.ChatCatcher.Catcher;
import me.skymc.taboolib.message.MsgUtils;
import me.skymc.taboolib.playerdata.DataUtils;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class SaveCommand extends SubCommand {
public SaveCommand(CommandSender sender, String[] args) {
super(sender, args);
if (!(sender instanceof Player)) {
MsgUtils.send(sender, "&4后台无法这么做");
return;
}
if (args.length < 2) {
MsgUtils.send(sender, "&4请输入正确的名称");
return;
}
if (((Player) sender).getItemInHand().getType().equals(Material.AIR)) {
MsgUtils.send(sender, "&4你不能保存空气");
return;
}
if (ItemUtils.getItemCachesFinal().containsKey(args[1])) {
MsgUtils.send(sender, "&4该名称所对应的物品保存于固定物品库中, 无法覆盖");
return;
}
if (ItemUtils.getItemCaches().containsKey(args[1])) {
// 检查聊天引导
if (ChatCatcher.contains((Player) sender)) {
MsgUtils.send(sender, "&4你有一个正在进行的聊天引导, 请完成后在这么做");
return;
}
ChatCatcher.call((Player) sender, new ChatCatcher.Catcher() {
@Override
public void cancel() {
MsgUtils.send(sender, "&7退出引导");
}
@Override
public Catcher before() {
MsgUtils.send(sender, "物品 &f" + args[1] + "&7 已存在, 如果你想要覆盖它, 请在聊天框中输入 \"&f是&7\"");
return this;
}
@SuppressWarnings("deprecation")
@Override
public boolean after(String message) {
if (message.equals("是")) {
saveItem(args[1], ((Player) sender).getItemInHand());
MsgUtils.send(sender, "物品 &f" + args[1] + " &7已替换");
}
else {
MsgUtils.send(sender, "&7退出引导");
}
return false;
}
});
}
else {
saveItem(args[1], ((Player) sender).getItemInHand());
MsgUtils.send(sender, "物品 &f" + args[1] + " &7已保存");
}
}
public SaveCommand(CommandSender sender, String[] args) {
super(sender, args);
if (!(sender instanceof Player)) {
TLocale.sendTo(sender, "COMMANDS.GLOBAL.ONLY-PLAYER");
return;
}
private void saveItem(String name, ItemStack item) {
FileConfiguration conf = ConfigUtils.load(Main.getInst(), ItemUtils.getItemCacheFile());
conf.set(name + ".bukkit", item);
DataUtils.saveConfiguration(conf, ItemUtils.getItemCacheFile());
ItemUtils.reloadItemCache();
}
if (args.length < 2) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SAVE.INVALID-NAME");
return;
}
if (((Player) sender).getItemInHand().getType().equals(Material.AIR)) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SAVE.INVALID-ITEM");
return;
}
if (ItemUtils.getItemCachesFinal().containsKey(args[1])) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SAVE.INVALID-ITEM-FINAL-EXISTS");
return;
}
if (ItemUtils.getItemCaches().containsKey(args[1])) {
// 检查聊天引导
if (ChatCatcher.contains((Player) sender)) {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SAVE.GUIDE-EXISTS");
return;
}
ChatCatcher.call((Player) sender, new ChatCatcher.Catcher() {
@Override
public void cancel() {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SAVE.GUIDE-QUIT");
}
@Override
public Catcher before() {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SAVE.GUIDE-BEFORE", args[1]);
return this;
}
@SuppressWarnings("deprecation")
@Override
public boolean after(String message) {
if (message.equalsIgnoreCase("yes")) {
saveItem(args[1], ((Player) sender).getItemInHand());
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SAVE.SUCCESS", args[1]);
} else {
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SAVE.GUIDE-QUIT");
}
return false;
}
});
} else {
saveItem(args[1], ((Player) sender).getItemInHand());
MsgUtils.send(sender, "物品 &f" + args[1] + " &7已保存");
}
}
private void saveItem(String name, ItemStack item) {
FileConfiguration conf = ConfigUtils.load(Main.getInst(), ItemUtils.getItemCacheFile());
conf.set(name + ".bukkit", item);
DataUtils.saveConfiguration(conf, ItemUtils.getItemCacheFile());
ItemUtils.reloadItemCache();
}
}

View File

@ -1,5 +1,6 @@
package me.skymc.taboolib.commands.sub;
import com.ilummc.tlib.resources.TLocale;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@ -8,28 +9,17 @@ import me.skymc.taboolib.jsonformatter.JSONFormatter;
import me.skymc.taboolib.jsonformatter.click.SuggestCommandEvent;
import me.skymc.taboolib.jsonformatter.hover.ShowTextEvent;
import java.util.Arrays;
public class SlotCommand extends SubCommand {
public SlotCommand(CommandSender sender, String[] args) {
super(sender, args);
sender.sendMessage("§f");
sender.sendMessage("§b§l----- §3§lAttribute Slots §b§l-----");
sender.sendMessage("§f");
String[] attributes = new String[] { "mainhand", "offhand", "feet", "legs", "chest", "head", "all" };
for (String name : attributes) {
if (isPlayer()) {
JSONFormatter json = new JSONFormatter();
json.append(" §7- §f" + name);
json.appendHoverClick(" §8(点击复制)", new ShowTextEvent("§f点击复制"), new SuggestCommandEvent(name));
json.send((Player) sender);
}
else {
sender.sendMessage(" §7- §f" + name);
}
}
sender.sendMessage("§f");
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SLOTS.HEAD");
Arrays.stream(new String[] { "mainhand", "offhand", "feet", "legs", "chest", "head", "all" }).forEach(slots -> TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SLOTS.BODY", slots));
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.SLOTS.FOOT");
}
}

View File

@ -1,5 +1,6 @@
package me.skymc.taboolib.commands.sub;
import com.ilummc.tlib.resources.TLocale;
import org.bukkit.command.CommandSender;
import me.skymc.taboolib.commands.SubCommand;
@ -12,10 +13,13 @@ public class VariableGetCommand extends SubCommand {
super(sender, args);
if (args.length < 3) {
MsgUtils.send(sender, "&4请输入正确的指令 ");
TLocale.sendTo(sender, "COAMMNDS.PARAMETER.INSUFFICIENT");
return;
}
else if (!(args[1].equals("-a") || args[1].equals("-s"))) {
MsgUtils.send(sender, "&4请输入正确的读取方式");
if (!(args[1].equals("-a") || args[1].equals("-s"))) {
TLocale.sendTo(sender, "COAMMNDS.TABOOLIB.VARIABLE.READ-ERROR-TYPE");
return;
}
Long time = System.currentTimeMillis();
@ -27,14 +31,8 @@ public class VariableGetCommand extends SubCommand {
else if (args[1].equals("-a")) {
value = GlobalDataManager.getVariableAsynchronous(args[2], null);
}
if (value == null) {
MsgUtils.send(sender, "读取完成, 耗时: &f" + (System.currentTimeMillis() - time) + " &7(ms)");
MsgUtils.send(sender, "变量 &f" + args[2] + " &7不存在");
}
else {
MsgUtils.send(sender, "读取完成, 耗时: &f" + (System.currentTimeMillis() - time) + " &7(ms)");
MsgUtils.send(sender, "变量 &f" + args[2] + " &7的值为 &f" + value);
}
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);
}
}

View File

@ -1,5 +1,6 @@
package me.skymc.taboolib.commands.sub;
import com.ilummc.tlib.resources.TLocale;
import org.bukkit.command.CommandSender;
import me.skymc.taboolib.commands.SubCommand;
@ -12,10 +13,13 @@ public class VariableSetCommand extends SubCommand {
super(sender, args);
if (args.length < 4) {
MsgUtils.send(sender, "&4请输入正确的指令 ");
TLocale.sendTo(sender, "COAMMNDS.PARAMETER.INSUFFICIENT");
return;
}
else if (!(args[1].equals("-a") || args[1].equals("-s"))) {
MsgUtils.send(sender, "&4请输入正确的写入方式");
if (!(args[1].equals("-a") || args[1].equals("-s"))) {
TLocale.sendTo(sender, "COAMMNDS.TABOOLIB.VARIABLE.WRITE-ERROR-TYPE");
return;
}
Long time = System.currentTimeMillis();
@ -27,8 +31,8 @@ public class VariableSetCommand extends SubCommand {
else if (args[1].equals("-a")) {
GlobalDataManager.setVariableAsynchronous(args[2], value);
}
MsgUtils.send(sender, "写入完成, 耗时: &f" + (System.currentTimeMillis() - time) + " &7(ms)");
TLocale.sendTo(sender, "COAMMNDS.TABOOLIB.VARIABLE.WRITE-SUCCESS", String.valueOf(System.currentTimeMillis() - time));
setReturn(true);
}
}

View File

@ -1,36 +1,31 @@
package me.skymc.taboolib.commands.sub.cycle;
import org.bukkit.command.CommandSender;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.commands.SubCommand;
import me.skymc.taboolib.message.MsgUtils;
import org.bukkit.command.CommandSender;
public class CycleCommand extends SubCommand {
public CycleCommand(CommandSender sender, String[] args) {
super(sender, args);
if (args.length > 1) {
if (args[1].equalsIgnoreCase("list")) {
new CycleListCommand(sender, args);
}
else if (args[1].equalsIgnoreCase("info")) {
new CycleInfoCommand(sender, args);
}
else if (args[1].equalsIgnoreCase("reset")) {
new CycleResetCommand(sender, args);
}
else if (args[1].equalsIgnoreCase("update")) {
new CycleUpdateCommand(sender, args);
}
}
else {
MsgUtils.send(sender, "&4指令错误");
}
}
public CycleCommand(CommandSender sender, String[] args) {
super(sender, args);
if (args.length > 1) {
if (args[1].equalsIgnoreCase("list")) {
new CycleListCommand(sender, args);
} else if (args[1].equalsIgnoreCase("info")) {
new CycleInfoCommand(sender, args);
} else if (args[1].equalsIgnoreCase("reset")) {
new CycleResetCommand(sender, args);
} else if (args[1].equalsIgnoreCase("update")) {
new CycleUpdateCommand(sender, args);
}
} else {
TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN");
}
}
@Override
public boolean command() {
return true;
}
@Override
public boolean command() {
return true;
}
}

View File

@ -1,11 +1,10 @@
package me.skymc.taboolib.commands.sub.itemlist;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import me.skymc.taboolib.commands.SubCommand;
import me.skymc.taboolib.commands.sub.itemlist.listener.ItemLibraryPatch;
import me.skymc.taboolib.other.NumberUtils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
* @author sky
@ -13,19 +12,14 @@ import me.skymc.taboolib.other.NumberUtils;
*/
public class ItemListCommand extends SubCommand {
/**
* @param sender
* @param args
*/
public ItemListCommand(CommandSender sender, String[] args) {
super(sender, args);
if (isPlayer()) {
if (args.length == 1) {
ItemLibraryPatch.openInventory((Player) sender, 1);
}
else {
ItemLibraryPatch.openInventory((Player) sender, NumberUtils.getInteger(args[1]));
}
}
}
public ItemListCommand(CommandSender sender, String[] args) {
super(sender, args);
if (isPlayer()) {
if (args.length == 1) {
ItemLibraryPatch.openInventory((Player) sender, 1);
} else {
ItemLibraryPatch.openInventory((Player) sender, NumberUtils.getInteger(args[1]));
}
}
}
}

View File

@ -1,10 +1,8 @@
package me.skymc.taboolib.commands.sub.itemlist.listener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.inventory.InventoryUtil;
import me.skymc.taboolib.inventory.ItemUtils;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
@ -16,97 +14,96 @@ import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import me.skymc.taboolib.inventory.InventoryUtil;
import me.skymc.taboolib.inventory.ItemUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
/**
* @author sky
* @since 201824 4:35:00
*/
public class ItemLibraryPatch implements Listener {
/**
*
*
* @param player
* @param page
*/
public static void openInventory(Player player, int page) {
ItemLibraryHolder holder = new ItemLibraryHolder(page);
Inventory inventory = Bukkit.createInventory(holder, 54, "物品库");
LinkedHashMap<String, ItemStack> map = new LinkedHashMap<>();
map.putAll(ItemUtils.getItemCachesFinal());
map.putAll(ItemUtils.getItemCaches());
/**
*
*
* @param player
* @param page
*/
public static void openInventory(Player player, int page) {
ItemLibraryHolder holder = new ItemLibraryHolder(page);
Inventory inventory = Bukkit.createInventory(holder, 54, TLocale.asString("COMMANDS.TABOOLIB.ITEMLIST.MENU.TITLE", String.valueOf(page)));
int loop = 0;
for (String name : map.keySet()) {
if (loop >= (page - 1) * 28) {
if (loop < page * 28) {
int slot = InventoryUtil.SLOT_OF_CENTENTS.get(loop - ((page - 1) * 28));
ItemStack item = map.get(name).clone();
{
ItemMeta meta = item.getItemMeta();
List<String> lore = meta.hasLore() ? meta.getLore() : new ArrayList<>();
lore.add("§f");
lore.add("§f§m ");
lore.add("§f序列号: §8" + name);
meta.setLore(lore);
item.setItemMeta(meta);
inventory.setItem(slot, item);
}
holder.ITEMS_DATA.put(slot, name);
} else {
break;
}
}
loop++;
}
LinkedHashMap<String, ItemStack> map = new LinkedHashMap<>();
map.putAll(ItemUtils.getItemCachesFinal());
map.putAll(ItemUtils.getItemCaches());
if (page > 1) {
inventory.setItem(47, ItemUtils.setName(new ItemStack(Material.ARROW), "§f上一页"));
}
if (((int) Math.ceil(map.size() / 28D)) > page) {
inventory.setItem(51, ItemUtils.setName(new ItemStack(Material.ARROW), "§f下一页"));
}
player.openInventory(inventory);
}
int loop = 0;
for (String name : map.keySet()) {
if (loop >= (page - 1) * 28) {
if (loop < page * 28) {
int slot = InventoryUtil.SLOT_OF_CENTENTS.get(loop - ((page - 1) * 28));
inventory.setItem(slot, getItem(map, name));
holder.ITEMS_DATA.put(slot, name);
} else {
break;
}
}
loop++;
}
@EventHandler
public void inventoryClick(InventoryClickEvent e) {
if (e.getInventory().getHolder() instanceof ItemLibraryHolder) {
e.setCancelled(true);
if (page > 1) {
inventory.setItem(47, ItemUtils.setName(new ItemStack(Material.ARROW), TLocale.asString("COMMANDS.TABOOLIB.ITEMLIST.MENU.BACK")));
}
if (((int) Math.ceil(map.size() / 28D)) > page) {
inventory.setItem(51, ItemUtils.setName(new ItemStack(Material.ARROW), TLocale.asString("COMMANDS.TABOOLIB.ITEMLIST.MENU.NEXT")));
}
player.openInventory(inventory);
}
if (e.getCurrentItem() == null || e.getCurrentItem().getType().equals(Material.AIR) || e.getRawSlot() >= e.getInventory().getSize()) {
return;
}
@EventHandler
public void inventoryClick(InventoryClickEvent e) {
if (e.getInventory().getHolder() instanceof ItemLibraryHolder) {
e.setCancelled(true);
switch (e.getRawSlot()) {
case 47:
openInventory((Player) e.getWhoClicked(), ((ItemLibraryHolder) e.getInventory().getHolder()).PAGE - 1);
break;
case 51:
openInventory((Player) e.getWhoClicked(), ((ItemLibraryHolder) e.getInventory().getHolder()).PAGE + 1);
break;
default:
e.getWhoClicked().getInventory().addItem(ItemUtils.getCacheItem(((ItemLibraryHolder) e.getInventory().getHolder()).ITEMS_DATA.get(e.getRawSlot())));
break;
}
}
}
public static class ItemLibraryHolder implements InventoryHolder {
if (e.getCurrentItem() == null || e.getCurrentItem().getType().equals(Material.AIR) || e.getRawSlot() >= e.getInventory().getSize()) {
return;
}
public final int PAGE;
public final HashMap<Integer, String> ITEMS_DATA = new HashMap<>();
public ItemLibraryHolder(int page) {
this.PAGE = page;
}
@Override
public Inventory getInventory() {
return null;
}
}
int i = e.getRawSlot();
if (i == 47) {
openInventory((Player) e.getWhoClicked(), ((ItemLibraryHolder) e.getInventory().getHolder()).PAGE - 1);
} else if (i == 51) {
openInventory((Player) e.getWhoClicked(), ((ItemLibraryHolder) e.getInventory().getHolder()).PAGE + 1);
} else {
e.getWhoClicked().getInventory().addItem(ItemUtils.getCacheItem(((ItemLibraryHolder) e.getInventory().getHolder()).ITEMS_DATA.get(e.getRawSlot())));
}
}
}
private static ItemStack getItem(HashMap<String, ItemStack> map, String name) {
ItemStack item = map.get(name).clone();
ItemMeta meta = item.getItemMeta();
List<String> lore = meta.hasLore() ? meta.getLore() : new ArrayList<>();
lore.addAll(TLocale.asStringList("COMMANDS.TABOOLIB.ITEMLIST.MENU.LORE", name));
meta.setLore(lore);
item.setItemMeta(meta);
return item;
}
public static class ItemLibraryHolder implements InventoryHolder {
public final int PAGE;
public final HashMap<Integer, String> ITEMS_DATA = new HashMap<>();
public ItemLibraryHolder(int page) {
this.PAGE = page;
}
@Override
public Inventory getInventory() {
return null;
}
}
}

View File

@ -1,30 +1,28 @@
package me.skymc.taboolib.commands.sub.shell;
import org.bukkit.command.CommandSender;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.commands.SubCommand;
import me.skymc.taboolib.message.MsgUtils;
import org.bukkit.command.CommandSender;
public class ShellCommand extends SubCommand {
public ShellCommand(CommandSender sender, String[] args) {
super(sender, args);
if (args.length > 1) {
if (args[1].equalsIgnoreCase("load")) {
new ShellLoadCommand(sender, args);
}
else if (args[1].equalsIgnoreCase("unload")) {
new ShellUnloadCommand(sender, args);
}
}
else {
MsgUtils.send(sender, "&4指令错误");
}
}
public ShellCommand(CommandSender sender, String[] args) {
super(sender, args);
if (args.length > 1) {
if (args[1].equalsIgnoreCase("load")) {
new ShellLoadCommand(sender, args);
} else if (args[1].equalsIgnoreCase("unload")) {
new ShellUnloadCommand(sender, args);
}
} else {
TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN");
}
}
@Override
public boolean command() {
return true;
}
@Override
public boolean command() {
return true;
}
}

View File

@ -2,6 +2,7 @@ package me.skymc.taboolib.commands.sub.shell;
import java.io.File;
import com.ilummc.tlib.resources.TLocale;
import org.bukkit.command.CommandSender;
import me.skymc.taboolib.commands.SubCommand;
@ -13,18 +14,18 @@ public class ShellLoadCommand extends SubCommand {
public ShellLoadCommand(CommandSender sender, String[] args) {
super(sender, args);
if (args.length < 3) {
MsgUtils.send(sender, "&c请输入正确的脚本名称");
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.JAVASHELL.INVALID-NAME");
return;
}
File file = new File(JavaShell.getScriptFolder(), args[2].contains(".java") ? args[2] : args[2] + ".java");
if (!file.exists()) {
MsgUtils.send(sender, "&c脚本 &4" + args[2] + "&c 不存在");
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.JAVASHELL.INVALID-SHELL", args[2]);
return;
}
if (JavaShell.reloadShell(args[2])) {
MsgUtils.send(sender, "脚本 " + args[2] + " 已载入");
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.JAVASHELL.SUCCESS-LOAD", args[2]);
}
}

View File

@ -2,6 +2,7 @@ package me.skymc.taboolib.commands.sub.shell;
import java.io.File;
import com.ilummc.tlib.resources.TLocale;
import org.bukkit.command.CommandSender;
import me.skymc.taboolib.commands.SubCommand;
@ -13,18 +14,18 @@ public class ShellUnloadCommand extends SubCommand {
public ShellUnloadCommand(CommandSender sender, String[] args) {
super(sender, args);
if (args.length < 3) {
MsgUtils.send(sender, "&c请输入正确的脚本名称");
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.JAVASHELL.INVALID-NAME");
return;
}
File file = new File(JavaShell.getScriptFolder(), args[2].contains(".java") ? args[2] : args[2] + ".java");
if (!file.exists()) {
MsgUtils.send(sender, "&c脚本 &4" + args[2] + "&c 不存在");
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.JAVASHELL.INVALID-SHELL", args[2]);
return;
}
JavaShell.unloadShell(args[2]);
MsgUtils.send(sender, "脚本 " + args[2] + " 已卸载");
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.JAVASHELL.SUCCESS-UNLOAD", args[2]);
}
@Override

View File

@ -1,31 +1,27 @@
package me.skymc.taboolib.commands.sub.sounds;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import me.skymc.taboolib.commands.SubCommand;
import me.skymc.taboolib.commands.sub.sounds.listener.SoundsLibraryPatch;
import me.skymc.taboolib.other.NumberUtils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
* @author sky
* @since 2018-03-18 21:02:26
*/
public class SoundsCommand extends SubCommand {
/**
* @param sender
* @param args
*/
public SoundsCommand(CommandSender sender, String[] args) {
super(sender, args);
if (isPlayer()) {
if (args.length == 1) {
SoundsLibraryPatch.openInventory((Player) sender, 1);
}
else {
SoundsLibraryPatch.openInventory((Player) sender, NumberUtils.getInteger(args[1]));
}
}
}
public SoundsCommand(CommandSender sender, String[] args) {
super(sender, args);
if (isPlayer()) {
if (args.length == 1) {
SoundsLibraryPatch.openInventory((Player) sender, 1, null);
} else if (args.length == 2) {
SoundsLibraryPatch.openInventory((Player) sender, NumberUtils.getInteger(args[1]), null);
} else {
SoundsLibraryPatch.openInventory((Player) sender, NumberUtils.getInteger(args[1]), args[2]);
}
}
}
}

View File

@ -1,8 +1,11 @@
package me.skymc.taboolib.commands.sub.sounds.listener;
import java.util.Arrays;
import java.util.HashMap;
import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.resources.type.TLocaleJson;
import me.skymc.taboolib.inventory.InventoryUtil;
import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.jsonformatter.JSONFormatter;
import me.skymc.taboolib.message.MsgUtils;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Sound;
@ -15,95 +18,105 @@ import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import me.skymc.taboolib.inventory.InventoryUtil;
import me.skymc.taboolib.inventory.ItemUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author sky
* @since 201824 4:35:00
*/
public class SoundsLibraryPatch implements Listener {
/**
*
*
* @param player
* @param page
*/
public static void openInventory(Player player, int page) {
SoundLibraryHolder holder = new SoundLibraryHolder(page);
Inventory inventory = Bukkit.createInventory(holder, 54, "音效库 " + page);
int loop = 0;
for (Sound sound : Arrays.asList(Sound.values())) {
if (loop >= (page - 1) * 28) {
if (loop < page * 28) {
int slot = InventoryUtil.SLOT_OF_CENTENTS.get(loop - ((page - 1) * 28));
ItemStack item = new ItemStack(Material.MAP);
{
ItemMeta meta = item.getItemMeta();
meta.setDisplayName("§f" + sound.name());
meta.setLore(Arrays.asList("", "§f左键: §71 音调", "§f左键: §72 音调"));
item.setItemMeta(meta);
inventory.setItem(slot, item);
}
holder.SOUNDS_DATA.put(slot, sound);
} else {
break;
}
}
loop++;
}
public static void openInventory(Player player, int page, String search) {
if (page < 1) {
page = 1;
}
if (page > 1) {
inventory.setItem(47, ItemUtils.setName(new ItemStack(Material.ARROW), "§f上一页"));
}
if (((int) Math.ceil(Sound.values().length / 28D)) > page) {
inventory.setItem(51, ItemUtils.setName(new ItemStack(Material.ARROW), "§f下一页"));
}
player.openInventory(inventory);
}
SoundLibraryHolder holder = new SoundLibraryHolder(page, search);
Inventory inventory = Bukkit.createInventory(holder, 54, TLocale.asString("COMMANDS.TABOOLIB.SOUNDS.MENU.TITLE", String.valueOf(page)));
List<Sound> soundFilter = Arrays.stream(Sound.values()).filter(sound -> search == null || sound.name().contains(search.toUpperCase())).collect(Collectors.toList());
@EventHandler
public void inventoryClick(InventoryClickEvent e) {
if (e.getInventory().getHolder() instanceof SoundLibraryHolder) {
e.setCancelled(true);
int loop = 0;
for (Sound sound : soundFilter) {
if (loop >= (page - 1) * 28) {
if (loop < page * 28) {
int slot = InventoryUtil.SLOT_OF_CENTENTS.get(loop - ((page - 1) * 28));
inventory.setItem(slot, getSoundItem(sound.name()));
holder.SOUNDS_DATA.put(slot, sound);
} else {
break;
}
}
loop++;
}
if (e.getCurrentItem() == null || e.getCurrentItem().getType().equals(Material.AIR) || e.getRawSlot() >= e.getInventory().getSize()) {
return;
}
if (page > 1) {
inventory.setItem(47, ItemUtils.setName(new ItemStack(Material.ARROW), TLocale.asString("COMMANDS.TABOOLIB.SOUNDS.MENU.BACK")));
}
if (((int) Math.ceil(Sound.values().length / 28D)) > page) {
inventory.setItem(51, ItemUtils.setName(new ItemStack(Material.ARROW), TLocale.asString("COMMANDS.TABOOLIB.SOUNDS.MENU.NEXT")));
}
switch (e.getRawSlot()) {
case 47:
openInventory((Player) e.getWhoClicked(), ((SoundLibraryHolder) e.getInventory().getHolder()).PAGE - 1);
break;
case 51:
openInventory((Player) e.getWhoClicked(), ((SoundLibraryHolder) e.getInventory().getHolder()).PAGE + 1);
break;
default:
Sound sound = ((SoundLibraryHolder) e.getInventory().getHolder()).SOUNDS_DATA.get(e.getRawSlot());
if (e.getClick().isLeftClick()) {
((Player) e.getWhoClicked()).playSound(e.getWhoClicked().getLocation(), sound, 1f, 1f);
} else {
((Player) e.getWhoClicked()).playSound(e.getWhoClicked().getLocation(), sound, 1f, 2f);
}
break;
}
}
}
public static class SoundLibraryHolder implements InventoryHolder {
if (!(player.getOpenInventory().getTopInventory().getHolder() instanceof SoundLibraryHolder)) {
TLocale.sendTo(player, "COMMANDS.TABOOLIB.SOUNDS.RESULT.SEARCH", (search == null ? "*" : search), String.valueOf(soundFilter.size()));
}
player.openInventory(inventory);
}
public final int PAGE;
public final HashMap<Integer, Sound> SOUNDS_DATA = new HashMap<>();
public SoundLibraryHolder(int page) {
this.PAGE = page;
}
@Override
public Inventory getInventory() {
return null;
}
}
@EventHandler
public void inventoryClick(InventoryClickEvent e) {
if (e.getInventory().getHolder() instanceof SoundLibraryHolder) {
e.setCancelled(true);
if (e.getCurrentItem() == null || e.getCurrentItem().getType().equals(Material.AIR) || e.getRawSlot() >= e.getInventory().getSize()) {
return;
}
SoundLibraryHolder soundLibraryHolder = ((SoundLibraryHolder) e.getInventory().getHolder());
int i = e.getRawSlot();
if (i == 47) {
openInventory((Player) e.getWhoClicked(), soundLibraryHolder.PAGE - 1, soundLibraryHolder.SEARCH);
} else if (i == 51) {
openInventory((Player) e.getWhoClicked(), soundLibraryHolder.PAGE + 1, soundLibraryHolder.SEARCH);
} else {
Sound sound = soundLibraryHolder.SOUNDS_DATA.get(e.getRawSlot());
if (e.getClick().isLeftClick()) {
((Player) e.getWhoClicked()).playSound(e.getWhoClicked().getLocation(), sound, 1f, 1f);
} else if (e.getClick().isRightClick()) {
((Player) e.getWhoClicked()).playSound(e.getWhoClicked().getLocation(), sound, 1f, 2f);
} else if (e.getClick().isCreativeAction()) {
TLocale.sendTo(e.getWhoClicked(), "COMMANDS.TABOOLIB.SOUNDS.RESULT.COPY", sound.name());
}
}
}
}
private static ItemStack getSoundItem(String sound) {
ItemStack item = new ItemStack(Material.MAP);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName("§f§n" + sound);
meta.setLore(TLocale.asStringList("COMMANDS.TABOOLIB.SOUNDS.MENU.LORE"));
item.setItemMeta(meta);
return item;
}
public static class SoundLibraryHolder implements InventoryHolder {
public final int PAGE;
public final String SEARCH;
public final HashMap<Integer, Sound> SOUNDS_DATA = new HashMap<>();
public SoundLibraryHolder(int page, String search) {
this.PAGE = page;
this.SEARCH = search;
}
@Override
public Inventory getInventory() {
return null;
}
}
}

View File

@ -1,20 +1,12 @@
package me.skymc.taboolib.csvutils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.*;
import java.nio.charset.Charset;
import java.text.NumberFormat;
import java.util.HashMap;
public class CsvReader
{
public class CsvReader {
private Reader inputStream;
private String fileName;
private UserSettings userSettings;
@ -38,7 +30,7 @@ public class CsvReader
private boolean closed;
public static final int ESCAPE_MODE_DOUBLED = 1;
public static final int ESCAPE_MODE_BACKSLASH = 2;
public CsvReader(final String fileName, final char delimiter, final Charset charset) throws FileNotFoundException {
this.inputStream = null;
this.fileName = null;
@ -75,15 +67,15 @@ public class CsvReader
this.charset = charset;
this.isQualified = new boolean[this.values.length];
}
public CsvReader(final String s, final char c) throws FileNotFoundException {
this(s, c, Charset.forName("ISO-8859-1"));
}
public CsvReader(final String s) throws FileNotFoundException {
this(s, ',');
}
public CsvReader(final Reader inputStream, final char delimiter) {
this.inputStream = null;
this.fileName = null;
@ -114,132 +106,132 @@ public class CsvReader
this.initialized = true;
this.isQualified = new boolean[this.values.length];
}
public CsvReader(final Reader reader) {
this(reader, ',');
}
public CsvReader(final InputStream inputStream, final char c, final Charset charset) {
this(new InputStreamReader(inputStream, charset), c);
}
public CsvReader(final InputStream inputStream, final Charset charset) {
this(new InputStreamReader(inputStream, charset));
}
public boolean getCaptureRawRecord() {
return this.userSettings.CaptureRawRecord;
}
public void setCaptureRawRecord(final boolean captureRawRecord) {
this.userSettings.CaptureRawRecord = captureRawRecord;
}
public String getRawRecord() {
return this.rawRecord;
}
public boolean getTrimWhitespace() {
return this.userSettings.TrimWhitespace;
}
public void setTrimWhitespace(final boolean trimWhitespace) {
this.userSettings.TrimWhitespace = trimWhitespace;
}
public char getDelimiter() {
return this.userSettings.Delimiter;
}
public void setDelimiter(final char delimiter) {
this.userSettings.Delimiter = delimiter;
}
public char getRecordDelimiter() {
return this.userSettings.RecordDelimiter;
}
public void setRecordDelimiter(final char recordDelimiter) {
this.useCustomRecordDelimiter = true;
this.userSettings.RecordDelimiter = recordDelimiter;
}
public char getTextQualifier() {
return this.userSettings.TextQualifier;
}
public void setTextQualifier(final char textQualifier) {
this.userSettings.TextQualifier = textQualifier;
}
public boolean getUseTextQualifier() {
return this.userSettings.UseTextQualifier;
}
public void setUseTextQualifier(final boolean useTextQualifier) {
this.userSettings.UseTextQualifier = useTextQualifier;
}
public char getComment() {
return this.userSettings.Comment;
}
public void setComment(final char comment) {
this.userSettings.Comment = comment;
}
public boolean getUseComments() {
return this.userSettings.UseComments;
}
public void setUseComments(final boolean useComments) {
this.userSettings.UseComments = useComments;
}
public int getEscapeMode() {
return this.userSettings.EscapeMode;
}
public void setEscapeMode(final int escapeMode) throws IllegalArgumentException {
if (escapeMode != 1 && escapeMode != 2) {
throw new IllegalArgumentException("Parameter escapeMode must be a valid value.");
}
this.userSettings.EscapeMode = escapeMode;
}
public boolean getSkipEmptyRecords() {
return this.userSettings.SkipEmptyRecords;
}
public void setSkipEmptyRecords(final boolean skipEmptyRecords) {
this.userSettings.SkipEmptyRecords = skipEmptyRecords;
}
public boolean getSafetySwitch() {
return this.userSettings.SafetySwitch;
}
public void setSafetySwitch(final boolean safetySwitch) {
this.userSettings.SafetySwitch = safetySwitch;
}
public int getColumnCount() {
return this.columnsCount;
}
public long getCurrentRecord() {
return this.currentRecord - 1L;
}
// TODO 2017-11-29 18:38:13 UPDATED
public long setCurrentRecord(long currentRecord) {
return this.currentRecord = currentRecord;
}
public int getHeaderCount() {
return this.headersHolder.Length;
}
public String[] getHeaders() throws IOException {
this.checkClosed();
if (this.headersHolder.Headers == null) {
@ -249,28 +241,27 @@ public class CsvReader
System.arraycopy(this.headersHolder.Headers, 0, array, 0, this.headersHolder.Length);
return array;
}
public void setHeaders(final String[] headers) {
this.headersHolder.Headers = headers;
this.headersHolder.IndexByName.clear();
if (headers != null) {
this.headersHolder.Length = headers.length;
}
else {
} else {
this.headersHolder.Length = 0;
}
for (int i = 0; i < this.headersHolder.Length; ++i) {
this.headersHolder.IndexByName.put(headers[i], i);
}
}
public String[] getValues() throws IOException {
this.checkClosed();
final String[] array = new String[this.columnsCount];
System.arraycopy(this.values, 0, array, 0, this.columnsCount);
return array;
}
public String get(final int n) throws IOException {
this.checkClosed();
if (n > -1 && n < this.columnsCount) {
@ -278,19 +269,19 @@ public class CsvReader
}
return "";
}
public String get(final String s) throws IOException {
this.checkClosed();
return this.get(this.getIndex(s));
}
public static CsvReader parse(final String s) {
if (s == null) {
throw new IllegalArgumentException("Parameter data can not be null.");
}
return new CsvReader(new StringReader(s));
}
public boolean readRecord() throws IOException {
this.checkClosed();
this.columnsCount = 0;
@ -301,8 +292,7 @@ public class CsvReader
do {
if (this.dataBuffer.Position == this.dataBuffer.Count) {
this.checkDataLength();
}
else {
} else {
this.startedWithQualifier = false;
char c = this.dataBuffer.Buffer[this.dataBuffer.Position];
if (this.userSettings.UseTextQualifier && c == this.userSettings.TextQualifier) {
@ -326,24 +316,21 @@ public class CsvReader
do {
if (this.dataBuffer.Position == this.dataBuffer.Count) {
this.checkDataLength();
}
else {
} else {
final char lastLetter = this.dataBuffer.Buffer[this.dataBuffer.Position];
if (n2 != 0) {
this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1;
if (lastLetter == this.userSettings.Delimiter) {
this.endColumn();
}
else if ((!this.useCustomRecordDelimiter && (lastLetter == '\r' || lastLetter == '\n')) || (this.useCustomRecordDelimiter && lastLetter == this.userSettings.RecordDelimiter)) {
} else if ((!this.useCustomRecordDelimiter && (lastLetter == '\r' || lastLetter == '\n')) || (this.useCustomRecordDelimiter && lastLetter == this.userSettings.RecordDelimiter)) {
this.endColumn();
this.endRecord();
}
}
else if (n4 != 0) {
} else if (n4 != 0) {
++n6;
switch (n5) {
case 1: {
c2 = (char)((char)(c2 * '\u0010') + hexToDec(lastLetter));
c2 = (char) ((char) (c2 * '\u0010') + hexToDec(lastLetter));
if (n6 == 4) {
n4 = 0;
break;
@ -351,7 +338,7 @@ public class CsvReader
break;
}
case 2: {
c2 = (char)((char)(c2 * '\b') + (char)(lastLetter - '0'));
c2 = (char) ((char) (c2 * '\b') + (char) (lastLetter - '0'));
if (n6 == 3) {
n4 = 0;
break;
@ -359,7 +346,7 @@ public class CsvReader
break;
}
case 3: {
c2 = (char)((char)(c2 * '\n') + (char)(lastLetter - '0'));
c2 = (char) ((char) (c2 * '\n') + (char) (lastLetter - '0'));
if (n6 == 3) {
n4 = 0;
break;
@ -367,7 +354,7 @@ public class CsvReader
break;
}
case 4: {
c2 = (char)((char)(c2 * '\u0010') + hexToDec(lastLetter));
c2 = (char) ((char) (c2 * '\u0010') + hexToDec(lastLetter));
if (n6 == 2) {
n4 = 0;
break;
@ -377,25 +364,21 @@ public class CsvReader
}
if (n4 == 0) {
this.appendLetter(c2);
}
else {
} else {
this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1;
}
}
else if (lastLetter == this.userSettings.TextQualifier) {
} else if (lastLetter == this.userSettings.TextQualifier) {
if (n3 != 0) {
n3 = 0;
n = 0;
}
else {
} else {
this.updateCurrentValue();
if (this.userSettings.EscapeMode == 1) {
n3 = 1;
}
n = 1;
}
}
else if (this.userSettings.EscapeMode == 2 && n3 != 0) {
} else if (this.userSettings.EscapeMode == 2 && n3 != 0) {
switch (lastLetter) {
case 'n': {
this.appendLetter('\n');
@ -440,7 +423,7 @@ public class CsvReader
n5 = 2;
n4 = 1;
n6 = 1;
c2 = (char)(lastLetter - '0');
c2 = (char) (lastLetter - '0');
this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1;
break;
}
@ -482,20 +465,16 @@ public class CsvReader
}
}
n3 = 0;
}
else if (lastLetter == textQualifier) {
} else if (lastLetter == textQualifier) {
this.updateCurrentValue();
n3 = 1;
}
else if (n != 0) {
} else if (n != 0) {
if (lastLetter == this.userSettings.Delimiter) {
this.endColumn();
}
else if ((!this.useCustomRecordDelimiter && (lastLetter == '\r' || lastLetter == '\n')) || (this.useCustomRecordDelimiter && lastLetter == this.userSettings.RecordDelimiter)) {
} else if ((!this.useCustomRecordDelimiter && (lastLetter == '\r' || lastLetter == '\n')) || (this.useCustomRecordDelimiter && lastLetter == this.userSettings.RecordDelimiter)) {
this.endColumn();
this.endRecord();
}
else {
} else {
this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1;
n2 = 1;
}
@ -513,40 +492,32 @@ public class CsvReader
}
}
} while (this.hasMoreData && this.startedColumn);
}
else if (c == this.userSettings.Delimiter) {
} else if (c == this.userSettings.Delimiter) {
this.lastLetter = c;
this.endColumn();
}
else if (this.useCustomRecordDelimiter && c == this.userSettings.RecordDelimiter) {
} else if (this.useCustomRecordDelimiter && c == this.userSettings.RecordDelimiter) {
if (this.startedColumn || this.columnsCount > 0 || !this.userSettings.SkipEmptyRecords) {
this.endColumn();
this.endRecord();
}
else {
} else {
this.dataBuffer.LineStart = this.dataBuffer.Position + 1;
}
this.lastLetter = c;
}
else if (!this.useCustomRecordDelimiter && (c == '\r' || c == '\n')) {
} else if (!this.useCustomRecordDelimiter && (c == '\r' || c == '\n')) {
if (this.startedColumn || this.columnsCount > 0 || (!this.userSettings.SkipEmptyRecords && (c == '\r' || this.lastLetter != '\r'))) {
this.endColumn();
this.endRecord();
}
else {
} else {
this.dataBuffer.LineStart = this.dataBuffer.Position + 1;
}
this.lastLetter = c;
}
else if (this.userSettings.UseComments && this.columnsCount == 0 && c == this.userSettings.Comment) {
} else if (this.userSettings.UseComments && this.columnsCount == 0 && c == this.userSettings.Comment) {
this.lastLetter = c;
this.skipLine();
}
else if (this.userSettings.TrimWhitespace && (c == ' ' || c == '\t')) {
} else if (this.userSettings.TrimWhitespace && (c == ' ' || c == '\t')) {
this.startedColumn = true;
this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1;
}
else {
} else {
this.startedColumn = true;
this.dataBuffer.ColumnStart = this.dataBuffer.Position;
int n7 = 0;
@ -558,25 +529,22 @@ public class CsvReader
do {
if (n11 == 0 && this.dataBuffer.Position == this.dataBuffer.Count) {
this.checkDataLength();
}
else {
} else {
if (n11 == 0) {
c = this.dataBuffer.Buffer[this.dataBuffer.Position];
}
if (!this.userSettings.UseTextQualifier && this.userSettings.EscapeMode == 2 && c == '\\') {
if (n7 != 0) {
n7 = 0;
}
else {
} else {
this.updateCurrentValue();
n7 = 1;
}
}
else if (n8 != 0) {
} else if (n8 != 0) {
++n10;
switch (n9) {
case 1: {
c3 = (char)((char)(c3 * '\u0010') + hexToDec(c));
c3 = (char) ((char) (c3 * '\u0010') + hexToDec(c));
if (n10 == 4) {
n8 = 0;
break;
@ -584,7 +552,7 @@ public class CsvReader
break;
}
case 2: {
c3 = (char)((char)(c3 * '\b') + (char)(c - '0'));
c3 = (char) ((char) (c3 * '\b') + (char) (c - '0'));
if (n10 == 3) {
n8 = 0;
break;
@ -592,7 +560,7 @@ public class CsvReader
break;
}
case 3: {
c3 = (char)((char)(c3 * '\n') + (char)(c - '0'));
c3 = (char) ((char) (c3 * '\n') + (char) (c - '0'));
if (n10 == 3) {
n8 = 0;
break;
@ -600,7 +568,7 @@ public class CsvReader
break;
}
case 4: {
c3 = (char)((char)(c3 * '\u0010') + hexToDec(c));
c3 = (char) ((char) (c3 * '\u0010') + hexToDec(c));
if (n10 == 2) {
n8 = 0;
break;
@ -610,12 +578,10 @@ public class CsvReader
}
if (n8 == 0) {
this.appendLetter(c3);
}
else {
} else {
this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1;
}
}
else if (this.userSettings.EscapeMode == 2 && n7 != 0) {
} else if (this.userSettings.EscapeMode == 2 && n7 != 0) {
switch (c) {
case 'n': {
this.appendLetter('\n');
@ -660,7 +626,7 @@ public class CsvReader
n9 = 2;
n8 = 1;
n10 = 1;
c3 = (char)(c - '0');
c3 = (char) (c - '0');
this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1;
break;
}
@ -702,11 +668,9 @@ public class CsvReader
}
}
n7 = 0;
}
else if (c == this.userSettings.Delimiter) {
} else if (c == this.userSettings.Delimiter) {
this.endColumn();
}
else if ((!this.useCustomRecordDelimiter && (c == '\r' || c == '\n')) || (this.useCustomRecordDelimiter && c == this.userSettings.RecordDelimiter)) {
} else if ((!this.useCustomRecordDelimiter && (c == '\r' || c == '\n')) || (this.useCustomRecordDelimiter && c == this.userSettings.RecordDelimiter)) {
this.endColumn();
this.endRecord();
}
@ -740,21 +704,18 @@ public class CsvReader
if (this.hasMoreData) {
if (this.rawBuffer.Position == 0) {
this.rawRecord = new String(this.dataBuffer.Buffer, this.dataBuffer.LineStart, this.dataBuffer.Position - this.dataBuffer.LineStart - 1);
}
else {
} else {
this.rawRecord = new String(this.rawBuffer.Buffer, 0, this.rawBuffer.Position) + new String(this.dataBuffer.Buffer, this.dataBuffer.LineStart, this.dataBuffer.Position - this.dataBuffer.LineStart - 1);
}
}
else {
} else {
this.rawRecord = new String(this.rawBuffer.Buffer, 0, this.rawBuffer.Position);
}
}
else {
} else {
this.rawRecord = "";
}
return this.hasReadNextLine;
}
private void checkDataLength() throws IOException {
if (!this.initialized) {
if (this.fileName != null) {
@ -776,8 +737,7 @@ public class CsvReader
}
try {
this.dataBuffer.Count = this.inputStream.read(this.dataBuffer.Buffer, 0, this.dataBuffer.Buffer.length);
}
catch (IOException ex) {
} catch (IOException ex) {
this.close();
throw ex;
}
@ -788,7 +748,7 @@ public class CsvReader
this.dataBuffer.LineStart = 0;
this.dataBuffer.ColumnStart = 0;
}
public boolean readHeaders() throws IOException {
final boolean record = this.readRecord();
this.headersHolder.Length = this.columnsCount;
@ -804,7 +764,7 @@ public class CsvReader
this.columnsCount = 0;
return record;
}
public String getHeader(final int n) throws IOException {
this.checkClosed();
if (n > -1 && n < this.headersHolder.Length) {
@ -812,12 +772,12 @@ public class CsvReader
}
return "";
}
public boolean isQualified(final int n) throws IOException {
this.checkClosed();
return n < this.columnsCount && n > -1 && this.isQualified[n];
}
public void endColumn() throws IOException {
String s = "";
if (this.startedColumn) {
@ -831,8 +791,7 @@ public class CsvReader
}
s = new String(this.dataBuffer.Buffer, this.dataBuffer.ColumnStart, n - this.dataBuffer.ColumnStart + 1);
}
}
else {
} else {
this.updateCurrentValue();
int n2 = this.columnBuffer.Position - 1;
if (this.userSettings.TrimWhitespace && !this.startedWithQualifier) {
@ -862,7 +821,7 @@ public class CsvReader
this.isQualified[this.columnsCount] = this.startedWithQualifier;
++this.columnsCount;
}
private void appendLetter(final char c) {
if (this.columnBuffer.Position == this.columnBuffer.Buffer.length) {
final char[] buffer = new char[this.columnBuffer.Buffer.length * 2];
@ -872,7 +831,7 @@ public class CsvReader
this.columnBuffer.Buffer[this.columnBuffer.Position++] = c;
this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1;
}
private void updateCurrentValue() {
if (this.startedColumn && this.dataBuffer.ColumnStart < this.dataBuffer.Position) {
if (this.columnBuffer.Buffer.length - this.columnBuffer.Position < this.dataBuffer.Position - this.dataBuffer.ColumnStart) {
@ -891,7 +850,7 @@ public class CsvReader
this.hasReadNextLine = true;
++this.currentRecord;
}
public int getIndex(final String s) throws IOException {
this.checkClosed();
final Integer value = this.headersHolder.IndexByName.get(s);
@ -900,7 +859,7 @@ public class CsvReader
}
return -1;
}
public boolean skipRecord() throws IOException {
this.checkClosed();
boolean record = false;
@ -912,7 +871,7 @@ public class CsvReader
}
return record;
}
public boolean skipLine() throws IOException {
this.checkClosed();
this.columnsCount = 0;
@ -922,8 +881,7 @@ public class CsvReader
do {
if (this.dataBuffer.Position == this.dataBuffer.Count) {
this.checkDataLength();
}
else {
} else {
b = true;
final char lastLetter = this.dataBuffer.Buffer[this.dataBuffer.Position];
if (lastLetter == '\r' || lastLetter == '\n') {
@ -944,14 +902,14 @@ public class CsvReader
this.rawRecord = "";
return b;
}
public void close() {
if (!this.closed) {
this.close(true);
this.closed = true;
}
}
private void close(final boolean b) {
if (!this.closed) {
if (b) {
@ -972,55 +930,50 @@ public class CsvReader
this.closed = true;
}
}
private void checkClosed() throws IOException {
if (this.closed) {
throw new IOException("This instance of the CsvReader class has already been closed.");
}
}
@Override
protected void finalize() {
protected void finalize() {
this.close(false);
}
private static char hexToDec(final char c) {
char c2;
if (c >= 'a') {
c2 = (char)(c - 'a' + '\n');
}
else if (c >= 'A') {
c2 = (char)(c - 'A' + '\n');
}
else {
c2 = (char)(c - '0');
c2 = (char) (c - 'a' + '\n');
} else if (c >= 'A') {
c2 = (char) (c - 'A' + '\n');
} else {
c2 = (char) (c - '0');
}
return c2;
}
private class StaticSettings
{
private class StaticSettings {
public static final int MAX_BUFFER_SIZE = 1024;
public static final int MAX_FILE_BUFFER_SIZE = 4096;
public static final int INITIAL_COLUMN_COUNT = 10;
public static final int INITIAL_COLUMN_BUFFER_SIZE = 50;
}
private class HeadersHolder
{
private class HeadersHolder {
public String[] Headers;
public int Length;
public HashMap<String, Integer> IndexByName;
public HeadersHolder() {
this.Headers = null;
this.Length = 0;
this.IndexByName = new HashMap<>();
}
}
private class UserSettings
{
private class UserSettings {
public boolean CaseSensitive;
public char TextQualifier;
public boolean TrimWhitespace;
@ -1033,7 +986,7 @@ public class CsvReader
public boolean SafetySwitch;
public boolean SkipEmptyRecords;
public boolean CaptureRawRecord;
public UserSettings() {
this.CaseSensitive = true;
this.TextQualifier = '\"';
@ -1049,9 +1002,8 @@ public class CsvReader
this.CaptureRawRecord = true;
}
}
private class Letters
{
private class Letters {
public static final char LF = '\n';
public static final char CR = '\r';
public static final char QUOTE = '\"';
@ -1067,37 +1019,34 @@ public class CsvReader
public static final char VERTICAL_TAB = '\u000b';
public static final char ALERT = '\u0007';
}
private class RawRecordBuffer
{
private class RawRecordBuffer {
public char[] Buffer;
public int Position;
public RawRecordBuffer() {
this.Buffer = new char[500];
this.Position = 0;
}
}
private class ColumnBuffer
{
private class ColumnBuffer {
public char[] Buffer;
public int Position;
public ColumnBuffer() {
this.Buffer = new char[50];
this.Position = 0;
}
}
private class DataBuffer
{
private class DataBuffer {
public char[] Buffer;
public int Position;
public int Count;
public int ColumnStart;
public int LineStart;
public DataBuffer() {
this.Buffer = new char[1024];
this.Position = 0;
@ -1106,9 +1055,8 @@ public class CsvReader
this.LineStart = 0;
}
}
private class ComplexEscape
{
private class ComplexEscape {
private static final int UNICODE = 1;
private static final int OCTAL = 2;
private static final int DECIMAL = 3;

View File

@ -1,15 +1,10 @@
package me.skymc.taboolib.csvutils;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.io.*;
import java.nio.charset.Charset;
public class CsvWriter
{
public class CsvWriter {
private Writer outputStream;
private String fileName;
private boolean firstColumn;
@ -21,7 +16,7 @@ public class CsvWriter
private String systemRecordDelimiter;
public static final int ESCAPE_MODE_DOUBLED = 1;
public static final int ESCAPE_MODE_BACKSLASH = 2;
public CsvWriter(final String fileName, final char delimiter, final Charset charset) {
this.outputStream = null;
this.fileName = null;
@ -42,11 +37,11 @@ public class CsvWriter
this.userSettings.Delimiter = delimiter;
this.charset = charset;
}
public CsvWriter(final String s) {
this(s, ',', Charset.forName("ISO-8859-1"));
}
public CsvWriter(final Writer outputStream, final char delimiter) {
this.outputStream = null;
this.fileName = null;
@ -64,68 +59,68 @@ public class CsvWriter
this.userSettings.Delimiter = delimiter;
this.initialized = true;
}
public CsvWriter(final OutputStream outputStream, final char c, final Charset charset) {
this(new OutputStreamWriter(outputStream, charset), c);
}
public char getDelimiter() {
return this.userSettings.Delimiter;
}
public void setDelimiter(final char delimiter) {
this.userSettings.Delimiter = delimiter;
}
public char getRecordDelimiter() {
return this.userSettings.RecordDelimiter;
}
public void setRecordDelimiter(final char recordDelimiter) {
this.useCustomRecordDelimiter = true;
this.userSettings.RecordDelimiter = recordDelimiter;
}
public char getTextQualifier() {
return this.userSettings.TextQualifier;
}
public void setTextQualifier(final char textQualifier) {
this.userSettings.TextQualifier = textQualifier;
}
public boolean getUseTextQualifier() {
return this.userSettings.UseTextQualifier;
}
public void setUseTextQualifier(final boolean useTextQualifier) {
this.userSettings.UseTextQualifier = useTextQualifier;
}
public int getEscapeMode() {
return this.userSettings.EscapeMode;
}
public void setEscapeMode(final int escapeMode) {
this.userSettings.EscapeMode = escapeMode;
}
public void setComment(final char comment) {
this.userSettings.Comment = comment;
}
public char getComment() {
return this.userSettings.Comment;
}
public boolean getForceQualifier() {
return this.userSettings.ForceQualifier;
}
public void setForceQualifier(final boolean forceQualifier) {
this.userSettings.ForceQualifier = forceQualifier;
}
public void write(String s, final boolean b) throws IOException {
this.checkClosed();
this.checkInit();
@ -159,26 +154,22 @@ public class CsvWriter
if (this.userSettings.EscapeMode == 2) {
s = replace(s, "\\", "\\\\");
s = replace(s, "" + this.userSettings.TextQualifier, "\\" + this.userSettings.TextQualifier);
}
else {
} else {
s = replace(s, "" + this.userSettings.TextQualifier, "" + this.userSettings.TextQualifier + this.userSettings.TextQualifier);
}
}
else if (this.userSettings.EscapeMode == 2) {
} else if (this.userSettings.EscapeMode == 2) {
s = replace(s, "\\", "\\\\");
s = replace(s, "" + this.userSettings.Delimiter, "\\" + this.userSettings.Delimiter);
if (this.useCustomRecordDelimiter) {
s = replace(s, "" + this.userSettings.RecordDelimiter, "\\" + this.userSettings.RecordDelimiter);
}
else {
} else {
s = replace(s, "\r", "\\\r");
s = replace(s, "\n", "\\\n");
}
if (this.firstColumn && s.length() > 0 && s.charAt(0) == this.userSettings.Comment) {
if (s.length() > 1) {
s = "\\" + this.userSettings.Comment + s.substring(1);
}
else {
} else {
s = "\\" + this.userSettings.Comment;
}
}
@ -189,11 +180,11 @@ public class CsvWriter
}
this.firstColumn = false;
}
public void write(final String s) throws IOException {
this.write(s, false);
}
public void writeComment(final String s) throws IOException {
this.checkClosed();
this.checkInit();
@ -201,8 +192,7 @@ public class CsvWriter
this.outputStream.write(s);
if (this.useCustomRecordDelimiter) {
this.outputStream.write(this.userSettings.RecordDelimiter);
}
else {
} else {
this.outputStream.write(this.systemRecordDelimiter);
}
this.firstColumn = true;
@ -224,23 +214,22 @@ public class CsvWriter
}
return s;
}
public void writeRecord(final String[] array) throws IOException {
this.writeRecord(array, false);
}
public void endRecord() throws IOException {
this.checkClosed();
this.checkInit();
if (this.useCustomRecordDelimiter) {
this.outputStream.write(this.userSettings.RecordDelimiter);
}
else {
} else {
this.outputStream.write(this.systemRecordDelimiter);
}
this.firstColumn = true;
}
private void checkInit() throws IOException {
if (!this.initialized) {
if (this.fileName != null) {
@ -249,11 +238,11 @@ public class CsvWriter
this.initialized = true;
}
}
public void flush() throws IOException {
this.outputStream.flush();
}
public void close() {
if (!this.closed) {
this.close(true);
@ -277,10 +266,10 @@ public class CsvWriter
}
@Override
protected void finalize() {
protected void finalize() {
this.close(false);
}
private void close(final boolean b) {
if (!this.closed) {
if (b) {
@ -296,9 +285,8 @@ public class CsvWriter
this.closed = true;
}
}
private class UserSettings
{
private class UserSettings {
public char TextQualifier;
public boolean UseTextQualifier;
public char Delimiter;
@ -306,7 +294,7 @@ public class CsvWriter
public char Comment;
public int EscapeMode;
public boolean ForceQualifier;
public UserSettings() {
this.TextQualifier = '\"';
this.UseTextQualifier = true;
@ -317,9 +305,8 @@ public class CsvWriter
this.ForceQualifier = false;
}
}
private class Letters
{
private class Letters {
public static final char LF = '\n';
public static final char CR = '\r';
public static final char QUOTE = '\"';

View File

@ -1,71 +1,58 @@
package me.skymc.taboolib.damage;
import java.lang.reflect.InvocationTargetException;
import me.skymc.taboolib.TabooLib;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import me.skymc.taboolib.TabooLib;
import java.lang.reflect.InvocationTargetException;
public class DamageUtils {
public static void damage(Player damager, LivingEntity victim, double damage)
{
dmg(damager, victim, damage);
}
public static void damage(Player damager, Entity victim, double damage)
{
if (victim instanceof LivingEntity) {
dmg(damager, (LivingEntity) victim, damage);
}
}
public static void dmg(LivingEntity paramLivingEntity1, LivingEntity paramLivingEntity2, double paramDouble)
{
if ((paramLivingEntity2.hasMetadata("NPC")) || (paramLivingEntity1.hasMetadata("NPC"))) {
return;
}
Object localObject1 = null;
try
{
localObject1 = paramLivingEntity1.getClass().getDeclaredMethod("getHandle", new Class[0]).invoke(paramLivingEntity1);
}
catch (IllegalAccessException|IllegalArgumentException|InvocationTargetException|NoSuchMethodException|SecurityException localIllegalAccessException1)
{
return;
}
Object localObject2 = null;
try
{
localObject2 = paramLivingEntity2.getClass().getDeclaredMethod("getHandle", new Class[0]).invoke(paramLivingEntity2);
}
catch (IllegalAccessException|IllegalArgumentException|InvocationTargetException|NoSuchMethodException|SecurityException localIllegalAccessException2)
{
return;
}
try
{
Class<?> DamageSource = nmsClass("DamageSource");
Object localObject3 = DamageSource.getDeclaredMethod("playerAttack", new Class[]{nmsClass("EntityHuman")}).invoke(DamageSource, localObject1);
localObject2.getClass().getDeclaredMethod("damageEntity", new Class[]{DamageSource, Float.TYPE}).invoke(localObject2, localObject3, (float) paramDouble);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException ignored)
{
}
}
private static Class<?> nmsClass(String paramString)
{
String str = "net.minecraft.server." + TabooLib.getVersion() + "." + paramString;
try {
return Class.forName(str);
} catch (ClassNotFoundException e) {
return null;
}
}
public static void damage(Player player, LivingEntity victim, double damage) {
dmg(player, victim, damage);
}
public static void damage(Player player, Entity victim, double damage) {
if (victim instanceof LivingEntity) {
dmg(player, (LivingEntity) victim, damage);
}
}
public static void dmg(LivingEntity paramLivingEntity1, LivingEntity paramLivingEntity2, double paramDouble) {
if ((paramLivingEntity2.hasMetadata("NPC")) || (paramLivingEntity1.hasMetadata("NPC"))) {
return;
}
Object localObject1;
try {
localObject1 = paramLivingEntity1.getClass().getDeclaredMethod("getHandle").invoke(paramLivingEntity1);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException localIllegalAccessException1) {
return;
}
Object localObject2;
try {
localObject2 = paramLivingEntity2.getClass().getDeclaredMethod("getHandle").invoke(paramLivingEntity2);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException localIllegalAccessException2) {
return;
}
try {
Class<?> DamageSource = nmsClass("DamageSource");
Object localObject3 = DamageSource.getDeclaredMethod("playerAttack", nmsClass("EntityHuman")).invoke(DamageSource, localObject1);
localObject2.getClass().getDeclaredMethod("damageEntity", new Class[]{DamageSource, Float.TYPE}).invoke(localObject2, localObject3, (float) paramDouble);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException ignored) {
}
}
private static Class<?> nmsClass(String paramString) {
String str = "net.minecraft.server." + TabooLib.getVersion() + "." + paramString;
try {
return Class.forName(str);
} catch (ClassNotFoundException e) {
return null;
}
}
}

View File

@ -5,19 +5,18 @@ import org.bukkit.entity.Projectile;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
public class GetDamager {
public static Player get(EntityDamageByEntityEvent e) {
Player p = null;
if (e.getDamager() instanceof Projectile) {
Projectile arrow = (Projectile) e.getDamager();
if (arrow.getShooter() instanceof Player) {
p = (Player) arrow.getShooter();
}
}
else if (e.getDamager() instanceof Player) {
p = (Player) e.getDamager();
}
return p;
}
public static Player get(EntityDamageByEntityEvent e) {
Player p = null;
if (e.getDamager() instanceof Projectile) {
Projectile arrow = (Projectile) e.getDamager();
if (arrow.getShooter() instanceof Player) {
p = (Player) arrow.getShooter();
}
} else if (e.getDamager() instanceof Player) {
p = (Player) e.getDamager();
}
return p;
}
}

View File

@ -5,19 +5,18 @@ import org.bukkit.entity.Projectile;
import org.bukkit.event.entity.EntityDeathEvent;
public class GetKiller {
public static Player get(EntityDeathEvent e) {
Player p = null;
if (e.getEntity().getKiller() instanceof Projectile) {
Projectile arrow = (Projectile) e.getEntity().getKiller();
if (arrow.getShooter() instanceof Player) {
p = (Player) arrow.getShooter();
}
}
else if (e.getEntity().getKiller() instanceof Player) {
p = e.getEntity().getKiller();
}
return p;
}
public static Player get(EntityDeathEvent e) {
Player p = null;
if (e.getEntity().getKiller() instanceof Projectile) {
Projectile arrow = (Projectile) e.getEntity().getKiller();
if (arrow.getShooter() instanceof Player) {
p = (Player) arrow.getShooter();
}
} else if (e.getEntity().getKiller() != null) {
p = e.getEntity().getKiller();
}
return p;
}
}

View File

@ -1,9 +1,12 @@
package me.skymc.taboolib.database;
import java.io.File;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.Main.StorageType;
import me.skymc.taboolib.events.PlayerLoadedEvent;
import me.skymc.taboolib.exception.PlayerOfflineException;
import me.skymc.taboolib.fileutils.ConfigUtils;
import me.skymc.taboolib.fileutils.FileUtils;
import me.skymc.taboolib.message.MsgUtils;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.file.FileConfiguration;
@ -15,256 +18,243 @@ import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.scheduler.BukkitRunnable;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.Main.StorageType;
import me.skymc.taboolib.events.PlayerLoadedEvent;
import me.skymc.taboolib.exception.PlayerOfflineException;
import me.skymc.taboolib.fileutils.ConfigUtils;
import me.skymc.taboolib.fileutils.FileUtils;
import me.skymc.taboolib.message.MsgUtils;
import java.io.File;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public class PlayerDataManager implements Listener {
private static final ConcurrentHashMap<String, FileConfiguration> PLAYER_DATA = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<String, FileConfiguration> PLAYER_DATA = new ConcurrentHashMap<>();
public enum UsernameType {
UUID, USERNAME
}
/**
*
*
* @return
*/
public static UsernameType getUsernameType() {
return Main.getInst().getConfig().getBoolean("ENABLE-UUID") ? UsernameType.UUID : UsernameType.USERNAME;
}
/**
*
*
* @param player
* @return
* @throws PlayerOfflineException
*/
public static FileConfiguration getPlayerData(Player player) {
if (getUsernameType() == UsernameType.UUID) {
return getPlayerData(player.getUniqueId().toString(), false);
}
else {
return getPlayerData(player.getName(), false);
}
}
/**
*
*
* @param player
* @return
*/
public static FileConfiguration getPlayerData(OfflinePlayer player) {
if (!player.isOnline()) {
return null;
}
if (getUsernameType() == UsernameType.UUID) {
return getPlayerData(player.getUniqueId().toString(), false);
}
else {
return getPlayerData(player.getName(), false);
}
}
/**
*
*
* @param username
* @return
* @throws PlayerOfflineException
*/
public static FileConfiguration getPlayerData(String username, boolean offline) {
if (PLAYER_DATA.containsKey(username)) {
return PLAYER_DATA.get(username);
}
else if (offline) {
if (Main.getStorageType() == StorageType.SQL) {
throw new PlayerOfflineException("不允许在储存模式为数据库的情况下获取离线玩家数据");
}
return loadPlayerData(username);
}
return null;
}
/**
*
*
* @param username
* @return
*/
public static FileConfiguration loadPlayerData(String username) {
// 本地储存
if (Main.getStorageType() == StorageType.LOCAL) {
// 读取文件
File file = FileUtils.file(Main.getPlayerDataFolder(), username + ".yml");
// 载入配置
PLAYER_DATA.put(username, YamlConfiguration.loadConfiguration(file));
}
else {
// 数据是否存在
if (Main.getConnection().isExists(Main.getTablePrefix() + "_playerdata", "username", username)) {
// 获取数据
String code = Main.getConnection().getValue(Main.getTablePrefix() + "_playerdata", "username", username, "configuration").toString();
try {
// 载入配置
PLAYER_DATA.put(username, ConfigUtils.decodeYAML(code));
}
catch (Exception e) {
// 创建空数据
PLAYER_DATA.put(username, new YamlConfiguration());
// 反馈信息
MsgUtils.warn("玩家 &4" + username + " &c的数据载入出现异常: &4" + e.getMessage());
}
}
else {
// 创建空数据
PLAYER_DATA.put(username, new YamlConfiguration());
}
}
return PLAYER_DATA.get(username);
}
/**
*
*
* @param username
* @param remove
*/
public static void savePlayerData(String username, boolean remove) {
// 没有数据
if (!PLAYER_DATA.containsKey(username)) {
return;
}
// 本地储存
if (Main.getStorageType() == StorageType.LOCAL) {
// 读取文件
File file = FileUtils.file(Main.getPlayerDataFolder(), username + ".yml");
// 保存配置
try {
PLAYER_DATA.get(username).save(file);
}
catch (Exception e) {
// TODO: handle exception
}
}
// 如果是数据库储存且有数据
else if (PLAYER_DATA.get(username).getConfigurationSection("").getKeys(false).size() > 0) {
// 数据是否存在
if (Main.getConnection().isExists(Main.getTablePrefix() + "_playerdata", "username", username)) {
// 写入数据
Main.getConnection().setValue(Main.getTablePrefix() + "_playerdata", "username", username, "configuration", ConfigUtils.encodeYAML(PLAYER_DATA.get(username)));
}
else {
// 插入数据
Main.getConnection().intoValue(Main.getTablePrefix() + "_playerdata", username, ConfigUtils.encodeYAML(PLAYER_DATA.get(username)));
}
}
// 获取这个属性对应的玩家
Player player;
if (getUsernameType() == UsernameType.UUID) {
player = Bukkit.getPlayer(UUID.fromString(username));
}
else {
player = Bukkit.getPlayerExact(username);
}
// 如果移除数据 或 玩家不在线
if (remove || player == null) {
PLAYER_DATA.remove(username);
}
}
/**
*
*
* @param sync
* @param remove
*/
public static void saveAllCaches(boolean sync, boolean remove) {
BukkitRunnable runnable = new BukkitRunnable() {
@Override
public void run() {
long time = System.currentTimeMillis();
// 保存
for (String name : PLAYER_DATA.keySet()) {
savePlayerData(name, false);
}
// 提示
if (!Main.getInst().getConfig().getBoolean("HIDE-NOTIFY")) {
MsgUtils.send("保存 &f" + PLAYER_DATA.size() + " &7条玩家数据, 耗时: &f" + (System.currentTimeMillis() - time) + " &7(ms)");
}
}
};
// 如果异步
if (sync) {
runnable.runTaskAsynchronously(Main.getInst());
}
// 如果同步
else {
runnable.run();
}
}
/**
*
*
* @param sync
* @param remove
*/
public static void saveAllPlayers(boolean sync, boolean remove) {
// 创建任务
BukkitRunnable runnable = new BukkitRunnable() {
@Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
savePlayerData(Main.getInst().getConfig().getBoolean("ENABLE-UUID") ? player.getUniqueId().toString() : player.getName(), remove);
}
}
};
// 如果异步
if (sync) {
runnable.runTaskAsynchronously(Main.getInst());
}
// 如果同步
else {
runnable.run();
}
}
@EventHandler
public void join(PlayerJoinEvent e) {
new BukkitRunnable() {
@Override
public void run() {
// 载入数据
loadPlayerData(Main.getInst().getConfig().getBoolean("ENABLE-UUID") ? e.getPlayer().getUniqueId().toString() : e.getPlayer().getName());
// 载入完成
Bukkit.getPluginManager().callEvent(new PlayerLoadedEvent(e.getPlayer()));
}
}.runTaskAsynchronously(Main.getInst());
}
@EventHandler
public void quit(PlayerQuitEvent e) {
if (!Main.isDisable()) {
new BukkitRunnable() {
@Override
public void run() {
// 保存数据
savePlayerData(Main.getInst().getConfig().getBoolean("ENABLE-UUID") ? e.getPlayer().getUniqueId().toString() : e.getPlayer().getName(), true);
}
}.runTaskAsynchronously(Main.getInst());
}
}
}
/**
*
*
* @return
*/
public static UsernameType getUsernameType() {
return Main.getInst().getConfig().getBoolean("ENABLE-UUID") ? UsernameType.UUID : UsernameType.USERNAME;
}
/**
*
*
* @param player
* @return
* @throws PlayerOfflineException
*/
public static FileConfiguration getPlayerData(Player player) {
if (getUsernameType() == UsernameType.UUID) {
return getPlayerData(player.getUniqueId().toString(), false);
} else {
return getPlayerData(player.getName(), false);
}
}
/**
*
*
* @param player
* @return
*/
public static FileConfiguration getPlayerData(OfflinePlayer player) {
if (!player.isOnline()) {
return null;
}
if (getUsernameType() == UsernameType.UUID) {
return getPlayerData(player.getUniqueId().toString(), false);
} else {
return getPlayerData(player.getName(), false);
}
}
/**
*
*
* @param username
* @return
* @throws PlayerOfflineException
*/
public static FileConfiguration getPlayerData(String username, boolean offline) {
if (PLAYER_DATA.containsKey(username)) {
return PLAYER_DATA.get(username);
} else if (offline) {
if (Main.getStorageType() == StorageType.SQL) {
throw new PlayerOfflineException("不允许在储存模式为数据库的情况下获取离线玩家数据");
}
return loadPlayerData(username);
}
return null;
}
/**
*
*
* @param username
* @return
*/
public static FileConfiguration loadPlayerData(String username) {
// 本地储存
if (Main.getStorageType() == StorageType.LOCAL) {
// 读取文件
File file = FileUtils.file(Main.getPlayerDataFolder(), username + ".yml");
// 载入配置
PLAYER_DATA.put(username, YamlConfiguration.loadConfiguration(file));
} else {
// 数据是否存在
if (Main.getConnection().isExists(Main.getTablePrefix() + "_playerdata", "username", username)) {
// 获取数据
String code = Main.getConnection().getValue(Main.getTablePrefix() + "_playerdata", "username", username, "configuration").toString();
try {
// 载入配置
PLAYER_DATA.put(username, ConfigUtils.decodeYAML(code));
} catch (Exception e) {
// 创建空数据
PLAYER_DATA.put(username, new YamlConfiguration());
// 反馈信息
MsgUtils.warn("玩家 &4" + username + " &c的数据载入出现异常: &4" + e.getMessage());
}
} else {
// 创建空数据
PLAYER_DATA.put(username, new YamlConfiguration());
}
}
return PLAYER_DATA.get(username);
}
/**
*
*
* @param username
* @param remove
*/
public static void savePlayerData(String username, boolean remove) {
// 没有数据
if (!PLAYER_DATA.containsKey(username)) {
return;
}
// 本地储存
if (Main.getStorageType() == StorageType.LOCAL) {
// 读取文件
File file = FileUtils.file(Main.getPlayerDataFolder(), username + ".yml");
// 保存配置
try {
PLAYER_DATA.get(username).save(file);
} catch (Exception e) {
// TODO: handle exception
}
}
// 如果是数据库储存且有数据
else if (PLAYER_DATA.get(username).getConfigurationSection("").getKeys(false).size() > 0) {
// 数据是否存在
if (Main.getConnection().isExists(Main.getTablePrefix() + "_playerdata", "username", username)) {
// 写入数据
Main.getConnection().setValue(Main.getTablePrefix() + "_playerdata", "username", username, "configuration", ConfigUtils.encodeYAML(PLAYER_DATA.get(username)));
} else {
// 插入数据
Main.getConnection().intoValue(Main.getTablePrefix() + "_playerdata", username, ConfigUtils.encodeYAML(PLAYER_DATA.get(username)));
}
}
// 获取这个属性对应的玩家
Player player;
if (getUsernameType() == UsernameType.UUID) {
player = Bukkit.getPlayer(UUID.fromString(username));
} else {
player = Bukkit.getPlayerExact(username);
}
// 如果移除数据 或 玩家不在线
if (remove || player == null) {
PLAYER_DATA.remove(username);
}
}
/**
*
*
* @param sync
* @param remove
*/
public static void saveAllCaches(boolean sync, boolean remove) {
BukkitRunnable runnable = new BukkitRunnable() {
@Override
public void run() {
long time = System.currentTimeMillis();
// 保存
for (String name : PLAYER_DATA.keySet()) {
savePlayerData(name, false);
}
// 提示
if (!Main.getInst().getConfig().getBoolean("HIDE-NOTIFY")) {
MsgUtils.send("保存 &f" + PLAYER_DATA.size() + " &7条玩家数据, 耗时: &f" + (System.currentTimeMillis() - time) + " &7(ms)");
}
}
};
// 如果异步
if (sync) {
runnable.runTaskAsynchronously(Main.getInst());
}
// 如果同步
else {
runnable.run();
}
}
/**
*
*
* @param sync
* @param remove
*/
public static void saveAllPlayers(boolean sync, boolean remove) {
// 创建任务
BukkitRunnable runnable = new BukkitRunnable() {
@Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
savePlayerData(Main.getInst().getConfig().getBoolean("ENABLE-UUID") ? player.getUniqueId().toString() : player.getName(), remove);
}
}
};
// 如果异步
if (sync) {
runnable.runTaskAsynchronously(Main.getInst());
}
// 如果同步
else {
runnable.run();
}
}
@EventHandler
public void join(PlayerJoinEvent e) {
new BukkitRunnable() {
@Override
public void run() {
// 载入数据
loadPlayerData(Main.getInst().getConfig().getBoolean("ENABLE-UUID") ? e.getPlayer().getUniqueId().toString() : e.getPlayer().getName());
// 载入完成
Bukkit.getPluginManager().callEvent(new PlayerLoadedEvent(e.getPlayer()));
}
}.runTaskAsynchronously(Main.getInst());
}
@EventHandler
public void quit(PlayerQuitEvent e) {
if (!Main.isDisable()) {
new BukkitRunnable() {
@Override
public void run() {
// 保存数据
savePlayerData(Main.getInst().getConfig().getBoolean("ENABLE-UUID") ? e.getPlayer().getUniqueId().toString() : e.getPlayer().getName(), true);
}
}.runTaskAsynchronously(Main.getInst());
}
}
}

View File

@ -1,34 +1,33 @@
package me.skymc.taboolib.economy;
import me.skymc.taboolib.Main;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.plugin.RegisteredServiceProvider;
import me.skymc.taboolib.Main;
import net.milkbowl.vault.economy.Economy;
public class EcoUtils {
public static void setupEconomy() {
RegisteredServiceProvider<Economy> l = Bukkit.getServer().getServicesManager().getRegistration(Economy.class);
if (l != null) {
Main.setEconomy(l.getProvider());
}
}
public static void remove(OfflinePlayer p, double d) {
Main.getEconomy().withdrawPlayer(p, d);
}
public static void add(OfflinePlayer p, double d) {
Main.getEconomy().depositPlayer(p, d);
}
public static double get(OfflinePlayer p) {
return Main.getEconomy().getBalance(p);
}
public static void create(OfflinePlayer p) {
Main.getEconomy().createPlayerAccount(p);
}
public static void setupEconomy() {
RegisteredServiceProvider<Economy> l = Bukkit.getServer().getServicesManager().getRegistration(Economy.class);
if (l != null) {
Main.setEconomy(l.getProvider());
}
}
public static void remove(OfflinePlayer p, double d) {
Main.getEconomy().withdrawPlayer(p, d);
}
public static void add(OfflinePlayer p, double d) {
Main.getEconomy().depositPlayer(p, d);
}
public static double get(OfflinePlayer p) {
return Main.getEconomy().getBalance(p);
}
public static void create(OfflinePlayer p) {
Main.getEconomy().createPlayerAccount(p);
}
}

View File

@ -1,272 +1,271 @@
package me.skymc.taboolib.entity;
import me.skymc.taboolib.Main;
import org.bukkit.entity.Entity;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.entity.Entity;
import org.bukkit.scheduler.BukkitRunnable;
import me.skymc.taboolib.Main;
/**
* - MetaData
*
*
* @author sky
* @since 2018-03-11 11:43:41
*/
public class EntityTag {
private static EntityTag inst;
private static ConcurrentHashMap<UUID, ConcurrentHashMap<String, Object>> entityData = new ConcurrentHashMap<>();
private EntityTag() {
new BukkitRunnable() {
@Override
public void run() {
for (UUID uuid : entityData.keySet()) {
if (EntityUtils.getEntityWithUUID(uuid) == null) {
entityData.remove(uuid);
}
}
}
}.runTaskTimerAsynchronously(Main.getInst(), 20 * 180, 20 * 180);
}
public static EntityTag getInst() {
if (inst == null) {
synchronized (EntityTag.class) {
if (inst == null) {
inst = new EntityTag();
}
}
}
return inst;
}
/**
*
*
* @param entity
* @param key
* @param value
*/
public void set(String key, Object value, Entity entity) {
if (contains(entity)) {
entityData.get(entity.getUniqueId()).put(key, value);
} else {
ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();
map.put(key, value);
entityData.put(entity.getUniqueId(), map);
}
}
/**
*
*
* @param key
* @param value
private static EntityTag inst;
private static ConcurrentHashMap<UUID, ConcurrentHashMap<String, Object>> entityData = new ConcurrentHashMap<>();
private EntityTag() {
new BukkitRunnable() {
@Override
public void run() {
for (UUID uuid : entityData.keySet()) {
if (EntityUtils.getEntityWithUUID(uuid) == null) {
entityData.remove(uuid);
}
}
}
}.runTaskTimerAsynchronously(Main.getInst(), 20 * 180, 20 * 180);
}
public static EntityTag getInst() {
if (inst == null) {
synchronized (EntityTag.class) {
if (inst == null) {
inst = new EntityTag();
}
}
}
return inst;
}
/**
*
*
* @param entity
* @param key
* @param value
*/
public void set(String key, Object value, Entity... entities) {
for (Entity entity : entities) set(key, value, entity);
}
/**
*
*
* @param key
* @param value
public void set(String key, Object value, Entity entity) {
if (contains(entity)) {
entityData.get(entity.getUniqueId()).put(key, value);
} else {
ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();
map.put(key, value);
entityData.put(entity.getUniqueId(), map);
}
}
/**
*
*
* @param key
* @param value
*/
public void set(String key, Object value, List<Entity> entities) {
for (Entity entity : entities) set(key, value, entity);
}
/**
*
*
* @param key
* @param entity
*/
public Object remove(String key, Entity entity) {
if (contains(entity)) {
entityData.get(entity.getUniqueId()).remove(key);
if (entityData.get(entity.getUniqueId()).size() == 0) {
return entityData.remove(entity.getUniqueId());
}
}
return null;
}
/**
*
*
* @param key
* @param entities
*/
public void remove(String key, Entity... entities) {
for (Entity entity : entities) remove(key, entity);
}
/**
*
*
* @param key
* @param entities
*/
public void remove(String key, List<Entity> entities) {
for (Entity entity : entities) remove(key, entity);
}
/**
*
*
* @param entity
* @return boolean
*/
public boolean contains(Entity entity) {
return entityData.containsKey(entity.getUniqueId());
}
/**
*
*
* @param key
* @param entity
* @return boolean
*/
public boolean hasKey(String key, Entity entity) {
public void set(String key, Object value, Entity... entities) {
for (Entity entity : entities) set(key, value, entity);
}
/**
*
*
* @param key
* @param value
*/
public void set(String key, Object value, List<Entity> entities) {
for (Entity entity : entities) set(key, value, entity);
}
/**
*
*
* @param key
* @param entity
*/
public Object remove(String key, Entity entity) {
if (contains(entity)) {
entityData.get(entity.getUniqueId()).remove(key);
if (entityData.get(entity.getUniqueId()).size() == 0) {
return entityData.remove(entity.getUniqueId());
}
}
return null;
}
/**
*
*
* @param key
* @param entities
*/
public void remove(String key, Entity... entities) {
for (Entity entity : entities) remove(key, entity);
}
/**
*
*
* @param key
* @param entities
*/
public void remove(String key, List<Entity> entities) {
for (Entity entity : entities) remove(key, entity);
}
/**
*
*
* @param entity
* @return boolean
*/
public boolean contains(Entity entity) {
return entityData.containsKey(entity.getUniqueId());
}
/**
*
*
* @param key
* @param entity
* @return boolean
*/
public boolean hasKey(String key, Entity entity) {
return contains(entity) && entityData.get(entity.getUniqueId()).containsKey(key);
}
/**
*
*
* @param key
* @param entity
* @return Object
*/
public Object get(String key, Entity entity) {
if (contains(entity)) {
return entityData.get(entity.getUniqueId()).get(key);
}
return null;
}
/**
*
*
* @param key
* @param entity
* @return String
*/
public String getString(String key, Entity entity) {
Object object = get(key, entity);
if (object instanceof String) {
return (String) object;
}
return null;
}
/**
*
*
* @param key
* @param entity
* @return int
*/
public int getInteger(String key, Entity entity) {
Object object = get(key, entity);
if (object != null) {
return (int) object;
}
return 0;
}
/**
*
*
* @param key
* @param entity
* @return long
*/
public long getLong(String key, Entity entity) {
Object object = get(key, entity);
if (object != null) {
return (long) object;
}
return 0L;
}
/**
*
*
* @param key
* @param entity
* @return boolean
*/
public boolean getBoolean(String key, Entity entity) {
/**
*
*
* @param key
* @param entity
* @return Object
*/
public Object get(String key, Entity entity) {
if (contains(entity)) {
return entityData.get(entity.getUniqueId()).get(key);
}
return null;
}
/**
*
*
* @param key
* @param entity
* @return String
*/
public String getString(String key, Entity entity) {
Object object = get(key, entity);
if (object instanceof String) {
return (String) object;
}
return null;
}
/**
*
*
* @param key
* @param entity
* @return int
*/
public int getInteger(String key, Entity entity) {
Object object = get(key, entity);
if (object != null) {
return (int) object;
}
return 0;
}
/**
*
*
* @param key
* @param entity
* @return long
*/
public long getLong(String key, Entity entity) {
Object object = get(key, entity);
if (object != null) {
return (long) object;
}
return 0L;
}
/**
*
*
* @param key
* @param entity
* @return boolean
*/
public boolean getBoolean(String key, Entity entity) {
Object object = get(key, entity);
return object != null && (boolean) object;
}
/**
*
*
* @param key
* @param entity
* @return double
*/
public double getDouble(String key, Entity entity) {
Object object = get(key, entity);
if (object != null) {
return (double) object;
}
return 0D;
}
/**
*
*
* @param key
* @param entity
* @return float
*/
public double getFloat(String key, Entity entity) {
Object object = get(key, entity);
if (object != null) {
return (float) object;
}
return 0F;
}
/**
*
*
* @param key
* @param entity
* @return short
*/
public short getShort(String key, Entity entity) {
Object object = get(key, entity);
if (object != null) {
return (short) object;
}
return (short) 0;
}
/**
*
*
* @param key
* @param entity
* @return byte
*/
public byte getByte(String key, Entity entity) {
Object object = get(key, entity);
if (object != null) {
return (byte) object;
}
return (byte) 0;
}
/**
*
*
* @param key
* @param entity
* @return double
*/
public double getDouble(String key, Entity entity) {
Object object = get(key, entity);
if (object != null) {
return (double) object;
}
return 0D;
}
/**
*
*
* @param key
* @param entity
* @return float
*/
public double getFloat(String key, Entity entity) {
Object object = get(key, entity);
if (object != null) {
return (float) object;
}
return 0F;
}
/**
*
*
* @param key
* @param entity
* @return short
*/
public short getShort(String key, Entity entity) {
Object object = get(key, entity);
if (object != null) {
return (short) object;
}
return (short) 0;
}
/**
*
*
* @param key
* @param entity
* @return byte
*/
public byte getByte(String key, Entity entity) {
Object object = get(key, entity);
if (object != null) {
return (byte) object;
}
return (byte) 0;
}
}

View File

@ -1,8 +1,10 @@
package me.skymc.taboolib.entity;
import java.lang.reflect.InvocationTargetException;
import java.util.UUID;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.wrappers.WrappedDataWatcher;
import me.skymc.taboolib.exception.PluginNotFoundException;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.Entity;
@ -11,72 +13,69 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntitySpawnEvent;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.wrappers.WrappedDataWatcher;
import lombok.Getter;
import me.skymc.taboolib.exception.PluginNotFoundException;
import java.lang.reflect.InvocationTargetException;
import java.util.UUID;
public class EntityUtils implements Listener {
@Getter
private static Entity lastSpawnedEntity = null;
@EventHandler
public void spawn(EntitySpawnEvent e) {
lastSpawnedEntity = e.getEntity();
}
/**
* UUID
*
* @param u
* @return
*/
public static Entity getEntityWithUUID(UUID u) {
for (World w : Bukkit.getWorlds()) {
for (Entity e : w.getLivingEntities()) {
if (e.getUniqueId().equals(u)) {
return e;
}
}
}
return null;
}
/**
* UUID
*
* @param u
* @param world
* @return
*/
public static Entity getEntityWithUUID_World(UUID u, World world) {
for (Entity e : world.getLivingEntities()) {
if (e.getUniqueId().equals(u)) {
return e;
}
}
return null;
}
/**
* ProcotolLib
*
* @param player
* @param entity
*/
public static void addGlow(Player player,Entity entity) {
if (Bukkit.getPluginManager().getPlugin("ProtocolLib") == null) {
try {
throw new PluginNotFoundException("缺少前置插件 ProtocolLib");
}
catch (Exception e) {
//
}
}
private static Entity lastSpawnedEntity = null;
public static Entity getLastSpawnedEntity() {
return lastSpawnedEntity;
}
@EventHandler
public void spawn(EntitySpawnEvent e) {
lastSpawnedEntity = e.getEntity();
}
/**
* UUID
*
* @param u
* @return
*/
public static Entity getEntityWithUUID(UUID u) {
for (World w : Bukkit.getWorlds()) {
for (Entity e : w.getLivingEntities()) {
if (e.getUniqueId().equals(u)) {
return e;
}
}
}
return null;
}
/**
* UUID
*
* @param u
* @param world
* @return
*/
public static Entity getEntityWithUUID_World(UUID u, World world) {
for (Entity e : world.getLivingEntities()) {
if (e.getUniqueId().equals(u)) {
return e;
}
}
return null;
}
/**
* ProcotolLib
*
* @param player
* @param entity
*/
public static void addGlow(Player player, Entity entity) {
if (Bukkit.getPluginManager().getPlugin("ProtocolLib") == null) {
try {
throw new PluginNotFoundException("缺少前置插件 ProtocolLib");
} catch (Exception e) {
//
}
}
PacketContainer packet = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA);
packet.getIntegers().write(0, entity.getEntityId());
WrappedDataWatcher watcher = new WrappedDataWatcher();
@ -85,26 +84,26 @@ public class EntityUtils implements Listener {
watcher.setObject(0, serializer, (byte) (0x40));
packet.getWatchableCollectionModifier().write(0, watcher.getWatchableObjects());
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet);
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
/**
* ProcotolLib
*
* @param player
* @param entity
*/
public static void delGlow(Player player,Entity entity) {
if (Bukkit.getPluginManager().getPlugin("ProtocolLib") == null) {
try {
throw new PluginNotFoundException("缺少前置插件 ProtocolLib");
} catch (Exception e) {
//
}
}
/**
* ProcotolLib
*
* @param player
* @param entity
*/
public static void delGlow(Player player, Entity entity) {
if (Bukkit.getPluginManager().getPlugin("ProtocolLib") == null) {
try {
throw new PluginNotFoundException("缺少前置插件 ProtocolLib");
} catch (Exception e) {
//
}
}
PacketContainer packet = ProtocolLibrary.getProtocolManager().createPacket(PacketType.Play.Server.ENTITY_METADATA);
packet.getIntegers().write(0, entity.getEntityId());
WrappedDataWatcher watcher = new WrappedDataWatcher();
@ -113,7 +112,7 @@ public class EntityUtils implements Listener {
watcher.setObject(0, serializer, (byte) (0x0));
packet.getWatchableCollectionModifier().write(0, watcher.getWatchableObjects());
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet);
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet);
} catch (InvocationTargetException e) {
e.printStackTrace();
}

View File

@ -6,51 +6,71 @@ import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.inventory.ItemStack;
import lombok.Getter;
import lombok.Setter;
/**
* The event called when a book is opened trough this Util
*/
public class CustomBookOpenEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
@Getter
@Setter
private boolean cancelled;
/**
* The player
*/
@Getter
private final Player player;
/**
* The hand used to open the book (the previous item will be restored after the opening)
*/
@Getter
@Setter
private Hand hand;
/**
* The actual book to be opened
*/
@Getter
@Setter
private ItemStack book;
public Player getPlayer() {
return player;
}
public Hand getHand() {
return hand;
}
public ItemStack getBook() {
return book;
}
public void setHand(Hand hand) {
this.hand = hand;
}
public void setBook(ItemStack book) {
this.book = book;
}
public CustomBookOpenEvent(Player player, ItemStack book, boolean offHand) {
this.player = player;
this.book = book;
this.hand = offHand ? Hand.OFF_HAND : Hand.MAIN_HAND;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public static HandlerList getHandlerList() {
return handlers;
}

View File

@ -5,49 +5,47 @@ import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
public class DefaultEvent2 extends PlayerEvent
{
public class DefaultEvent2 extends PlayerEvent {
private static final HandlerList handlers;
static {
handlers = new HandlerList();
}
private DefaultEvent2(final Player who) {
super(who);
}
public static HandlerList getHandlerList() {
return DefaultEvent2.handlers;
}
@Override
public HandlerList getHandlers() {
public HandlerList getHandlers() {
return DefaultEvent2.handlers;
}
public static class Pre extends DefaultEvent2 implements Cancellable
{
public static class Pre extends DefaultEvent2 implements Cancellable {
private boolean cancelled;
public Pre(Player who) {
super(who);
this.cancelled = false;
}
@Override
public boolean isCancelled() {
public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(final boolean cancelled) {
public void setCancelled(final boolean cancelled) {
this.cancelled = cancelled;
}
}
public static class Post extends DefaultEvent2
{
public static class Post extends DefaultEvent2 {
public Post(Player who) {
super(who);
}

View File

@ -5,45 +5,37 @@ import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public class PlayerJumpEvent
extends Event
implements Cancellable
{
private static final HandlerList handlers = new HandlerList();
private boolean isCancelled;
private Player player;
public PlayerJumpEvent(boolean b, Player player)
{
this.isCancelled = false;
this.player = player;
}
public Player getPlayer()
{
return this.player;
}
@Override
public boolean isCancelled()
{
return this.isCancelled;
}
@Override
public void setCancelled(boolean e)
{
this.isCancelled = e;
}
@Override
public HandlerList getHandlers()
{
return handlers;
}
public static HandlerList getHandlerList()
{
return handlers;
}
public class PlayerJumpEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private boolean isCancelled;
private Player player;
public PlayerJumpEvent(boolean b, Player player) {
this.isCancelled = false;
this.player = player;
}
public Player getPlayer() {
return this.player;
}
@Override
public boolean isCancelled() {
return this.isCancelled;
}
@Override
public void setCancelled(boolean e) {
this.isCancelled = e;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}

View File

@ -5,25 +5,25 @@ import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public class PlayerLoadedEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private Player player;
public PlayerLoadedEvent(Player player) {
super(true);
this.player = player;
}
public Player getPlayer() {
return this.player;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
private static final HandlerList handlers = new HandlerList();
private Player player;
public PlayerLoadedEvent(Player player) {
super(true);
this.player = player;
}
public Player getPlayer() {
return this.player;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}

View File

@ -1,123 +1,116 @@
package me.skymc.taboolib.fileutils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
public class EncodeUtils {
/**
*
*
* @param fileName
* @param fromCharsetName
* @param toCharsetName
* @throws Exception
*/
public static void convert(String fileName, String fromCharsetName, String toCharsetName) throws Exception {
convert(new File(fileName), fromCharsetName, toCharsetName, null);
}
/**
*
*
* @param fileName
* @param fromCharsetName
* @param toCharsetName
* @throws Exception
*/
public static void convert(String fileName, String fromCharsetName, String toCharsetName) throws Exception {
convert(new File(fileName), fromCharsetName, toCharsetName, null);
}
/**
*
*
* @param file
* @param fromCharsetName
* @param toCharsetName
* @throws Exception
*/
public static void convert(File file, String fromCharsetName, String toCharsetName) throws Exception {
convert(file, fromCharsetName, toCharsetName, null);
}
/**
*
*
* @param file
* @param fromCharsetName
* @param toCharsetName
* @throws Exception
*/
public static void convert(File file, String fromCharsetName, String toCharsetName) throws Exception {
convert(file, fromCharsetName, toCharsetName, null);
}
/**
*
*
* @param fromCharsetName
* @param toCharsetName
* @param filter
* @throws Exception
*/
public static void convert(String fileName, String fromCharsetName, String toCharsetName, FilenameFilter filter) throws Exception {
convert(new File(fileName), fromCharsetName, toCharsetName, filter);
}
/**
*
*
* @param fromCharsetName
* @param toCharsetName
* @param filter
* @throws Exception
*/
public static void convert(String fileName, String fromCharsetName, String toCharsetName, FilenameFilter filter) throws Exception {
convert(new File(fileName), fromCharsetName, toCharsetName, filter);
}
/**
*
*
* @param file
* @param fromCharsetName
* @param toCharsetName
* @param filter
* @throws Exception
*/
public static void convert(File file, String fromCharsetName, String toCharsetName, FilenameFilter filter) throws Exception {
if (file.isDirectory()) {
File[] fileList = null;
if (filter == null) {
fileList = file.listFiles();
} else {
fileList = file.listFiles(filter);
}
for (File f : fileList) {
convert(f, fromCharsetName, toCharsetName, filter);
}
} else {
if (filter == null
|| filter.accept(file.getParentFile(), file.getName())) {
String fileContent = getFileContentFromCharset(file,
fromCharsetName);
saveFile2Charset(file, toCharsetName, fileContent);
}
}
}
/**
*
*
* @param file
* @param fromCharsetName
* @param toCharsetName
* @param filter
* @throws Exception
*/
public static void convert(File file, String fromCharsetName, String toCharsetName, FilenameFilter filter) throws Exception {
if (file.isDirectory()) {
File[] fileList = null;
if (filter == null) {
fileList = file.listFiles();
} else {
fileList = file.listFiles(filter);
}
for (File f : fileList) {
convert(f, fromCharsetName, toCharsetName, filter);
}
} else {
if (filter == null
|| filter.accept(file.getParentFile(), file.getName())) {
String fileContent = getFileContentFromCharset(file,
fromCharsetName);
saveFile2Charset(file, toCharsetName, fileContent);
}
}
}
/**
*
*
* @param file
* @param fromCharsetName
* @return
* @throws Exception
*/
public static String getFileContentFromCharset(File file, String fromCharsetName) throws Exception {
if (!Charset.isSupported(fromCharsetName)) {
throw new UnsupportedCharsetException(fromCharsetName);
}
InputStream inputStream = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(inputStream,
fromCharsetName);
char[] chs = new char[(int) file.length()];
reader.read(chs);
String str = new String(chs).trim();
reader.close();
return str;
}
/**
*
*
* @param file
* @param fromCharsetName
* @return
* @throws Exception
*/
public static String getFileContentFromCharset(File file, String fromCharsetName) throws Exception {
if (!Charset.isSupported(fromCharsetName)) {
throw new UnsupportedCharsetException(fromCharsetName);
}
InputStream inputStream = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(inputStream,
fromCharsetName);
char[] chs = new char[(int) file.length()];
reader.read(chs);
String str = new String(chs).trim();
reader.close();
return str;
}
/**
*
*
* @param file
* @param toCharsetName
* @param content
* @throws Exception
*/
public static void saveFile2Charset(File file, String toCharsetName, String content) throws Exception {
if (!Charset.isSupported(toCharsetName)) {
throw new UnsupportedCharsetException(toCharsetName);
}
OutputStream outputStream = new FileOutputStream(file);
OutputStreamWriter outWrite = new OutputStreamWriter(outputStream, toCharsetName);
outWrite.write(content);
outWrite.close();
System.out.println("[Encodeing...] 更改文件: " + file.getPath());
}
/**
*
*
* @param file
* @param toCharsetName
* @param content
* @throws Exception
*/
public static void saveFile2Charset(File file, String toCharsetName, String content) throws Exception {
if (!Charset.isSupported(toCharsetName)) {
throw new UnsupportedCharsetException(toCharsetName);
}
OutputStream outputStream = new FileOutputStream(file);
OutputStreamWriter outWrite = new OutputStreamWriter(outputStream, toCharsetName);
outWrite.write(content);
outWrite.close();
System.out.println("[Encodeing...] 更改文件: " + file.getPath());
}
}

View File

@ -10,304 +10,301 @@ import java.net.URLConnection;
import java.nio.channels.FileChannel;
public class FileUtils {
public static String ip() {
try {
InputStream ins = null;
URL url = new URL("http://1212.ip138.com/ic.asp");
URLConnection con = url.openConnection();
ins = con.getInputStream();
public static String ip() {
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);
StringBuilder webContent = new StringBuilder();
String str = null;
while ((str = bReader.readLine()) != null) {
webContent.append(str);
}
int start = webContent.indexOf("[") + 1;
int end = webContent.indexOf("]");
String str = null;
while ((str = bReader.readLine()) != null) {
webContent.append(str);
}
int start = webContent.indexOf("[") + 1;
int end = webContent.indexOf("]");
ins.close();
return webContent.substring(start, end);
}
catch (Exception e) {
// TODO: handle exception
}
return webContent.substring(start, end);
} catch (Exception e) {
// TODO: handle exception
}
return "[IP ERROR]";
}
/**
*
*
* @param filePath
* @return
*/
public static File file(String filePath) {
File file = new File(filePath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
return file;
}
/**
*
*
* @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;
}
/**
*
*
* @param file
*/
public void deleteAllFile(File file) {
if (!file.exists()) {
return;
}
if (file.isFile()) {
file.delete();
return;
}
/**
*
*
* @param filePath
* @return
*/
public static File file(String filePath) {
File file = new File(filePath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
return file;
}
/**
*
*
* @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;
}
/**
*
*
* @param file
*/
public void deleteAllFile(File file) {
if (!file.exists()) {
return;
}
if (file.isFile()) {
file.delete();
return;
}
File[] files = file.listFiles();
for (File file1 : files) {
deleteAllFile(file1);
}
file.delete();
}
/**
*
*
file.delete();
}
/**
*
*
* @param file1 1
* @param file2 2
* @throws Exception
*/
* @throws Exception
*/
public void copyAllFile(String file1, String file2) throws Exception {
File _file1 = new File(file1);
File _file2 = new File(file2);
if (!_file2.exists()) {
if (!_file1.isDirectory()) {
_file2.createNewFile();
} else {
_file2.mkdirs();
}
if (!_file1.isDirectory()) {
_file2.createNewFile();
} else {
_file2.mkdirs();
}
}
if (_file1.isDirectory()) {
for (File file : _file1.listFiles()) {
if (file.isDirectory()) {
copyAllFile(file.getAbsolutePath(), file2 + "/" + file.getName());
} else {
fileChannelCopy(file, new File(file2 + "/" + file.getName()));
}
}
for (File file : _file1.listFiles()) {
if (file.isDirectory()) {
copyAllFile(file.getAbsolutePath(), file2 + "/" + file.getName());
} else {
fileChannelCopy(file, new File(file2 + "/" + file.getName()));
}
}
} else {
fileChannelCopy(_file1, _file2);
fileChannelCopy(_file1, _file2);
}
}
/**
*
*
*
* @param file1 1
* @param file2 2
*/
public void fileChannelCopy(File file1, File file2) {
FileInputStream fileIn = null;
FileOutputStream fileOut = null;
FileChannel channelIn = null;
FileChannel channelOut = null;
try {
fileIn = new FileInputStream(file1);
fileOut = new FileOutputStream(file2);
public void fileChannelCopy(File file1, File file2) {
FileInputStream fileIn = null;
FileOutputStream fileOut = null;
FileChannel channelIn = null;
FileChannel channelOut = null;
try {
fileIn = new FileInputStream(file1);
fileOut = new FileOutputStream(file2);
channelIn = fileIn.getChannel();
channelOut = fileOut.getChannel();
channelIn.transferTo(0, channelIn.size(), channelOut);
} catch (Exception e) {
} catch (Exception e) {
//
} finally {
try {
fileIn.close();
channelIn.close();
fileOut.close();
channelOut.close();
} catch (Exception e) {
} finally {
try {
fileIn.close();
channelIn.close();
fileOut.close();
channelOut.close();
} catch (Exception e) {
//
}
}
}
/**
*
*
* @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 = 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;
}
}
}
}
/**
*
*
* @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 = 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;
}
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) {
}
}
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) {
}
}
}

View File

@ -1,58 +1,47 @@
package me.skymc.taboolib.fileutils;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.other.DateUtils;
import org.bukkit.plugin.Plugin;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import org.bukkit.plugin.Plugin;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.other.DateUtils;
@Deprecated
public class LogUtils {
public static void Log(String s, String s2)
{
try
{
File file = new File(Main.getInst().getDataFolder(), s2+".txt");
if(!file.exists())
{
public static void Log(String s, String s2) {
try {
File file = new File(Main.getInst().getDataFolder(), s2 + ".txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file, true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(s);
bufferWritter.newLine();
bufferWritter.close();
}
catch (Exception e)
{
Main.getInst().getLogger().warning(s2+":"+s);
} catch (Exception e) {
Main.getInst().getLogger().warning(s2 + ":" + s);
}
}
public static void newLog(Plugin main, String s, String s2)
{
try
{
File file = new File(main.getDataFolder(), s2+".txt");
if(!file.exists())
{
public static void newLog(Plugin main, String s, String s2) {
try {
File file = new File(main.getDataFolder(), s2 + ".txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file, true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write("["+DateUtils.CH_ALL.format(System.currentTimeMillis())+"]"+s);
bufferWritter.write("[" + DateUtils.CH_ALL.format(System.currentTimeMillis()) + "]" + s);
bufferWritter.newLine();
bufferWritter.close();
}
catch (Exception e)
{
Main.getInst().getLogger().warning(s2+":"+s);
} catch (Exception e) {
Main.getInst().getLogger().warning(s2 + ":" + s);
}
}

View File

@ -1,48 +1,46 @@
package me.skymc.taboolib.inventory;
import me.skymc.taboolib.other.NumberUtils;
import org.bukkit.Location;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
import me.skymc.taboolib.other.NumberUtils;
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);
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;
if (bulletSpread > 0) {
double[] spread = { 1.0D, 1.0D, 1.0D };
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);
spread[t] = ((NumberUtils.getRand().nextDouble() - NumberUtils.getRand().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];
}
else {
x = Math.cos(pitch) * Math.cos(yaw);
} else {
x = Math.cos(pitch) * Math.cos(yaw);
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;
}
}
}

View File

@ -1,119 +1,117 @@
package me.skymc.taboolib.inventory;
import java.util.Arrays;
import java.util.LinkedList;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.Arrays;
import java.util.LinkedList;
public class InventoryUtil {
public final static LinkedList<Integer> SLOT_OF_CENTENTS = new LinkedList<>(Arrays.asList(
10, 11, 12, 13, 14, 15, 16,
19, 20, 21, 22, 23, 24, 25,
28, 29, 30, 31, 32, 33, 34,
37, 38, 39, 40, 41, 42, 43));
@Deprecated
public static boolean isEmpey(Player p) {
public final static LinkedList<Integer> SLOT_OF_CENTENTS = new LinkedList<>(Arrays.asList(
10, 11, 12, 13, 14, 15, 16,
19, 20, 21, 22, 23, 24, 25,
28, 29, 30, 31, 32, 33, 34,
37, 38, 39, 40, 41, 42, 43));
@Deprecated
public static boolean isEmpey(Player p) {
return isEmpty(p, 0);
}
/**
*
*
* @param p
* @param i
*/
public static boolean isEmpty(Player p, int i) {
/**
*
*
* @param p
* @param i
*/
public static boolean isEmpty(Player p, int i) {
while (i < 35) {
if (p.getInventory().getItem(i) == null) {
return true;
return true;
}
i++;
}
return false;
}
/**
*
*
* @param player
* @param item
* @param amount
* @param remove
*/
public static boolean hasItem(Player player, ItemStack item, int amount, boolean remove) {
int hasAmount = 0;
for (ItemStack _item : player.getInventory()) {
if (item.isSimilar(_item)) {
hasAmount += _item.getAmount();
}
}
if (hasAmount < amount) {
return false;
}
int requireAmount = amount;
for (int i = 0; i < player.getInventory().getSize() && remove; i++) {
ItemStack _item = player.getInventory().getItem(i);
if (_item != null && _item.isSimilar(item)) {
if (_item.getAmount() < requireAmount) {
player.getInventory().setItem(i, null);
requireAmount -= _item.getAmount();
/**
*
*
* @param player
* @param item
* @param amount
* @param remove
*/
public static boolean hasItem(Player player, ItemStack item, int amount, boolean remove) {
int hasAmount = 0;
for (ItemStack _item : player.getInventory()) {
if (item.isSimilar(_item)) {
hasAmount += _item.getAmount();
}
}
if (hasAmount < amount) {
return false;
}
int requireAmount = amount;
for (int i = 0; i < player.getInventory().getSize() && remove; i++) {
ItemStack _item = player.getInventory().getItem(i);
if (_item != null && _item.isSimilar(item)) {
if (_item.getAmount() < requireAmount) {
player.getInventory().setItem(i, null);
requireAmount -= _item.getAmount();
} else if (_item.getAmount() == requireAmount) {
player.getInventory().setItem(i, null);
return true;
player.getInventory().setItem(i, null);
return true;
} else {
_item.setAmount(_item.getAmount() - requireAmount);
return true;
}
}
}
return true;
}
@Deprecated
public static boolean hasItem(Inventory targetInventory, ItemStack targetItem, Integer amount) {
int inventoryAmount = 0;
for (ItemStack item : targetInventory) {
if (item != null) {
if (item.isSimilar(targetItem)) {
inventoryAmount += item.getAmount();
}
}
}
_item.setAmount(_item.getAmount() - requireAmount);
return true;
}
}
}
return true;
}
@Deprecated
public static boolean hasItem(Inventory targetInventory, ItemStack targetItem, Integer amount) {
int inventoryAmount = 0;
for (ItemStack item : targetInventory) {
if (item != null) {
if (item.isSimilar(targetItem)) {
inventoryAmount += item.getAmount();
}
}
}
return inventoryAmount >= amount;
}
@Deprecated
public static boolean takeItem2(Inventory inv, ItemStack takeitem, Integer amount) {
for (int i = 0; i < inv.getSize(); ++i) {
if (amount <= 0) {
return true;
}
ItemStack item = inv.getItem(i);
if (item == null) {
continue;
}
if (!item.isSimilar(takeitem)) {
continue;
}
if (item.getAmount() >= amount) {
if (item.getAmount() - amount == 0) {
inv.setItem(i, null);
}
else {
item.setAmount(item.getAmount() - amount);
}
return true;
}
else {
amount -= item.getAmount();
inv.setItem(i, null);
}
}
return false;
}
@Deprecated
public static boolean takeItem2(Inventory inv, ItemStack takeitem, Integer amount) {
for (int i = 0; i < inv.getSize(); ++i) {
if (amount <= 0) {
return true;
}
ItemStack item = inv.getItem(i);
if (item == null) {
continue;
}
if (!item.isSimilar(takeitem)) {
continue;
}
if (item.getAmount() >= amount) {
if (item.getAmount() - amount == 0) {
inv.setItem(i, null);
} else {
item.setAmount(item.getAmount() - amount);
}
return true;
} else {
amount -= item.getAmount();
inv.setItem(i, null);
}
}
return false;
}
}

View File

@ -1,10 +1,16 @@
package me.skymc.taboolib.inventory;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import me.clip.placeholderapi.PlaceholderAPI;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.TabooLib;
import me.skymc.taboolib.fileutils.ConfigUtils;
import me.skymc.taboolib.itemnbtapi.NBTItem;
import me.skymc.taboolib.itemnbtapi.NBTList;
import me.skymc.taboolib.itemnbtapi.NBTListCompound;
import me.skymc.taboolib.itemnbtapi.NBTType;
import me.skymc.taboolib.message.MsgUtils;
import me.skymc.taboolib.other.NumberUtils;
import me.skymc.taboolib.string.Language;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
@ -21,235 +27,237 @@ import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import lombok.Getter;
import me.clip.placeholderapi.PlaceholderAPI;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.TabooLib;
import me.skymc.taboolib.fileutils.ConfigUtils;
import me.skymc.taboolib.itemnbtapi.NBTItem;
import me.skymc.taboolib.itemnbtapi.NBTList;
import me.skymc.taboolib.itemnbtapi.NBTListCompound;
import me.skymc.taboolib.itemnbtapi.NBTType;
import me.skymc.taboolib.message.MsgUtils;
import me.skymc.taboolib.other.NumberUtils;
import me.skymc.taboolib.string.Language;
import java.io.File;
import java.util.*;
import java.util.stream.IntStream;
public class ItemUtils {
@Getter
private static FileConfiguration itemdir = null;
@Getter
private static FileConfiguration itemCache = null;
@Getter
private static File finalItemsFolder;
@Getter
private static LinkedHashMap<String, String> itemlib = new LinkedHashMap<>();
@Getter
private static LinkedHashMap<String, ItemStack> itemCaches = new LinkedHashMap<>();
@Getter
private static LinkedHashMap<String, ItemStack> itemCachesFinal = new LinkedHashMap<>();
/**
*
*
* 1.
* 2.
*
* @param name
* @return
*/
public static ItemStack getCacheItem(String name) {
// 检测固定物品库是否存在该物品
if (itemCachesFinal.containsKey(name)) {
return itemCachesFinal.get(name);
}
// 返回动态物品库
return itemCaches.get(name);
}
public static boolean isExists(String name) {
return itemCachesFinal.containsKey(name) || itemCaches.containsKey(name);
}
public static void LoadLib() {
try {
reloadItemName();
reloadItemCache();
itemdir = YamlConfiguration.loadConfiguration(new File(Main.getInst().getConfig().getString("DATAURL.ITEMDIR")));
} catch (Exception e) {
MsgUtils.warn("物品库载入失败: &4" + e.getMessage());
}
}
public static void loadItemsFile(File file, boolean finalFile) {
FileConfiguration conf = ConfigUtils.load(Main.getInst(), file);
for (String name : conf.getConfigurationSection("").getKeys(false)) {
if (isExists(name)) {
MsgUtils.warn("无法载入载入物品 &4" + name + "&c, 因为它已经存在了");
} else if (finalFile) {
itemCachesFinal.put(name, loadItem(conf, name));
} else {
itemCaches.put(name, loadItem(conf, name));
}
}
}
public static void reloadItemCache() {
itemCaches.clear();
itemCachesFinal.clear();
loadItemsFile(getItemCacheFile(), false);
// 创建固定物品库
finalItemsFolder = new File(Main.getInst().getDataFolder(), "FinalItems");
if (!finalItemsFolder.exists()) {
finalItemsFolder.mkdir();
}
// 检查固定物品库中的物品
for (File file : finalItemsFolder.listFiles()) {
loadItemsFile(file, true);
}
MsgUtils.send("载入 " + (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() + " 项物品名称");
}
public static File getItemCacheFile() {
File itemCacheFile = new File(Main.getInst().getDataFolder(), "items.yml");
if (!itemCacheFile.exists()) {
Main.getInst().saveResource("items.yml", true);
}
return itemCacheFile;
}
public static String getCustomName(ItemStack item) {
if (item == null || item.getType().equals(Material.AIR)) {
return "空";
}
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);
}
public static ItemStack getItemFromDir(String name) {
if (itemdir != null) {
return itemdir.getItemStack("item." + name);
}
return null;
}
@SuppressWarnings("deprecation")
private static FileConfiguration itemdir = null;
private static FileConfiguration itemCache = null;
private static File finalItemsFolder;
private static LinkedHashMap<String, String> itemlib = new LinkedHashMap<>();
private static LinkedHashMap<String, ItemStack> itemCaches = new LinkedHashMap<>();
private static LinkedHashMap<String, ItemStack> itemCachesFinal = new LinkedHashMap<>();
public static FileConfiguration getItemdir() {
return itemdir;
}
public static FileConfiguration getItemCache() {
return itemCache;
}
public static File getFinalItemsFolder() {
return finalItemsFolder;
}
public static LinkedHashMap<String, String> getItemlib() {
return itemlib;
}
public static LinkedHashMap<String, ItemStack> getItemCaches() {
return itemCaches;
}
public static LinkedHashMap<String, ItemStack> getItemCachesFinal() {
return itemCachesFinal;
}
/**
*
*
* 1.
* 2.
*
* @param name
* @return
*/
public static ItemStack getCacheItem(String name) {
// 检测固定物品库是否存在该物品
if (itemCachesFinal.containsKey(name)) {
return itemCachesFinal.get(name);
}
// 返回动态物品库
return itemCaches.get(name);
}
public static boolean isExists(String name) {
return itemCachesFinal.containsKey(name) || itemCaches.containsKey(name);
}
public static void LoadLib() {
try {
reloadItemName();
reloadItemCache();
itemdir = YamlConfiguration.loadConfiguration(new File(Main.getInst().getConfig().getString("DATAURL.ITEMDIR")));
} catch (Exception e) {
MsgUtils.warn("物品库载入失败: &4" + e.getMessage());
}
}
public static void loadItemsFile(File file, boolean finalFile) {
FileConfiguration conf = ConfigUtils.load(Main.getInst(), file);
for (String name : conf.getConfigurationSection("").getKeys(false)) {
if (isExists(name)) {
MsgUtils.warn("无法载入载入物品 &4" + name + "&c, 因为它已经存在了");
} else if (finalFile) {
itemCachesFinal.put(name, loadItem(conf, name));
} else {
itemCaches.put(name, loadItem(conf, name));
}
}
}
public static void reloadItemCache() {
itemCaches.clear();
itemCachesFinal.clear();
loadItemsFile(getItemCacheFile(), false);
// 创建固定物品库
finalItemsFolder = new File(Main.getInst().getDataFolder(), "FinalItems");
if (!finalItemsFolder.exists()) {
finalItemsFolder.mkdir();
}
// 检查固定物品库中的物品
for (File file : Objects.requireNonNull(finalItemsFolder.listFiles())) {
loadItemsFile(file, true);
}
MsgUtils.send("载入 " + (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() + " 项物品名称");
}
public static File getItemCacheFile() {
File itemCacheFile = new File(Main.getInst().getDataFolder(), "items.yml");
if (!itemCacheFile.exists()) {
Main.getInst().saveResource("items.yml", true);
}
return itemCacheFile;
}
public static String getCustomName(ItemStack item) {
if (item == null || item.getType().equals(Material.AIR)) {
return "空";
}
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);
}
public static ItemStack getItemFromDir(String name) {
if (itemdir != null) {
return itemdir.getItemStack("item." + name);
}
return null;
}
@SuppressWarnings("deprecation")
public static ItemStack item(int n, int a, int d) {
return new ItemStack(n, a, (short) d);
}
public static ItemStack setName(ItemStack i, String n) {
ItemMeta meta = i.getItemMeta();
meta.setDisplayName(n);
i.setItemMeta(meta);
return i;
}
public static ItemStack Enchant(ItemStack i, Enchantment e, int l) {
ItemMeta meta = i.getItemMeta();
meta.addEnchant(e, l, false);
i.setItemMeta(meta);
return i;
}
public static ItemStack addFlag(ItemStack i, ItemFlag f) {
ItemMeta meta = i.getItemMeta();
meta.addItemFlags(f);
i.setItemMeta(meta);
return i;
}
public static boolean isNull(ItemStack item) {
return item == null || item.getType().equals(Material.AIR);
return item == null || item.getType().equals(Material.AIR);
}
public static boolean isName(ItemStack i, String a) {
return isNamed(i) && i.getItemMeta() != null && i.getItemMeta().getDisplayName() != null && i.getItemMeta().getDisplayName().equals(a);
}
public static boolean isNameAs(ItemStack i, String a) {
return isNamed(i) && i.getItemMeta().getDisplayName().contains(a);
}
public static String asString(String args, Player placeholderPlayer) {
if (placeholderPlayer == null) {
return args.replace("&", "§");
}
return PlaceholderAPI.setPlaceholders(placeholderPlayer, args.replace("&", "§"));
if (placeholderPlayer == null) {
return args.replace("&", "§");
}
return PlaceholderAPI.setPlaceholders(placeholderPlayer, args.replace("&", "§"));
}
public static List<String> asString(List<String> args, Player placeholderPlayer) {
for (int i = 0 ; i < args.size() ; i ++) {
args.set(i, asString(args.get(i), placeholderPlayer));
}
return args;
IntStream.range(0, args.size()).forEach(i -> args.set(i, asString(args.get(i), placeholderPlayer)));
return args;
}
public static ItemFlag asItemFlag(String flag) {
try {
return ItemFlag.valueOf(flag);
}
catch (Exception e) {
return null;
}
try {
return ItemFlag.valueOf(flag);
} catch (Exception e) {
return null;
}
}
@SuppressWarnings("deprecation")
public static Material asMaterial(String args) {
try {
Material material = Material.getMaterial(args);
return material != null ? material : Material.getMaterial(Integer.valueOf(args));
}
catch (Exception e) {
return Material.STONE;
}
}
@SuppressWarnings({ "deprecation" })
public static Enchantment asEnchantment(String enchant) {
try {
Enchantment enchantment = Enchantment.getByName(enchant);
return enchantment != null ? enchantment : Enchantment.getById(Integer.valueOf(enchant));
}
catch (Exception e) {
return null;
}
public static Material asMaterial(String args) {
try {
Material material = Material.getMaterial(args);
return material != null ? material : Material.getMaterial(Integer.valueOf(args));
} catch (Exception e) {
return Material.STONE;
}
}
@SuppressWarnings({"deprecation"})
public static Enchantment asEnchantment(String enchant) {
try {
Enchantment enchantment = Enchantment.getByName(enchant);
return enchantment != null ? enchantment : Enchantment.getById(Integer.valueOf(enchant));
} catch (Exception e) {
return null;
}
}
@SuppressWarnings("deprecation")
public static PotionEffectType asPotionEffectType(String potion) {
try {
PotionEffectType type = PotionEffectType.getByName(potion);
return type != null ? type : PotionEffectType.getById(Integer.valueOf(potion));
}
catch (Exception e) {
return null;
}
public static PotionEffectType asPotionEffectType(String potion) {
try {
PotionEffectType type = PotionEffectType.getByName(potion);
return type != null ? type : PotionEffectType.getById(Integer.valueOf(potion));
} catch (Exception e) {
return null;
}
}
public static Color asColor(String color) {
try {
return Color.fromBGR(Integer.valueOf(color.split("-")[0]), Integer.valueOf(color.split("-")[1]), Integer.valueOf(color.split("-")[2]));
}
catch (Exception e) {
return Color.fromBGR(0, 0, 0);
}
try {
return Color.fromBGR(Integer.valueOf(color.split("-")[0]), Integer.valueOf(color.split("-")[1]), Integer.valueOf(color.split("-")[2]));
} catch (Exception e) {
return Color.fromBGR(0, 0, 0);
}
}
public static String asAttribute(String name) {
switch (name.toLowerCase()) {
case "damage":
@ -267,320 +275,297 @@ public class ItemUtils {
case "luck":
return "generic.luck";
}
return null;
return null;
}
/**
*
*
*
* @param i
* @param a
*/
public static boolean hasLore(ItemStack i, String a) {
return isLored(i) && i.getItemMeta().getLore().toString().contains(a);
}
/**
*
*
*
* @param i
* @return
*/
public static boolean isLored(ItemStack i) {
return i != null && i.getItemMeta() != null && i.getItemMeta().getLore() != null;
}
/**
*
*
*
* @param i
* @return
*/
public static boolean isNamed(ItemStack i) {
public static boolean isNamed(ItemStack i) {
return i != null && i.getItemMeta() != null && i.getItemMeta().getDisplayName() != null;
}
/**
*
*
* @param is
*
* @param is
* @param lore
*/
public static ItemStack addLore(ItemStack is, String lore) {
ItemMeta meta = is.getItemMeta();
List<String> _lore = meta.hasLore() ? meta.getLore() : new ArrayList<>();
_lore.add(lore.replaceAll("&", "§"));
ItemMeta meta = is.getItemMeta();
List<String> _lore = meta.hasLore() ? meta.getLore() : Collections.emptyList();
_lore.add(lore.replaceAll("&", "§"));
is.setItemMeta(meta);
return is;
}
/**
*
*
* @param is
*
* @param is
* @param line
*/
public static ItemStack delLore(ItemStack is, int line) {
ItemMeta meta = is.getItemMeta();
ItemMeta meta = is.getItemMeta();
if (meta.hasLore()) {
List<String> l = meta.getLore();
if (l.size() >= line) {
l.remove(line);
meta.setLore(l);
is.setItemMeta(meta);
}
List<String> l = meta.getLore();
if (l.size() >= line) {
l.remove(line);
meta.setLore(l);
is.setItemMeta(meta);
}
}
return is;
}
/**
*
*
*
* @param i
* @param a
*/
public static int getLore(ItemStack i, String a) {
if (isLored(i)) {
for (int j = 0; j < i.getItemMeta().getLore().size() ; j++) {
if (i.getItemMeta().getLore().get(j).contains(a)) {
return j;
}
}
}
return 0;
return isLored(i) ? IntStream.range(0, i.getItemMeta().getLore().size()).filter(j -> i.getItemMeta().getLore().get(j).contains(a)).findFirst().orElse(0) : 0;
}
/**
*
*
*
* @param i
* @param d
*/
public static ItemStack addDurability(ItemStack i, int d) {
i.setDurability((short) (i.getDurability() + d));
int min = i.getDurability();
int max = i.getType().getMaxDurability();
if (min >= max) {
i.setType(Material.AIR);
}
return i;
i.setDurability((short) (i.getDurability() + d));
int min = i.getDurability();
int max = i.getType().getMaxDurability();
if (min >= max) {
i.setType(Material.AIR);
}
return i;
}
/**
*
*
* @param i
*
* @param i
* @param l1 1
* @param l2 2
*/
public static ItemStack repalceLore(ItemStack i, String l1, String l2) {
if (!isLored(i)) {
return i;
}
else {
ItemMeta meta = i.getItemMeta();
List<String> lore = meta.getLore();
for (int j = 0 ; j < lore.size() ; j++) {
lore.set(j, lore.get(j).replace(l1, l2));
}
meta.setLore(lore);
i.setItemMeta(meta);
}
return i;
if (!isLored(i)) {
return i;
} else {
ItemMeta meta = i.getItemMeta();
List<String> lore = meta.getLore();
IntStream.range(0, lore.size()).forEach(j -> lore.set(j, lore.get(j).replace(l1, l2)));
meta.setLore(lore);
i.setItemMeta(meta);
}
return i;
}
public static ItemStack loadItem(FileConfiguration f, String s) {
return loadItem(f, s, null);
return loadItem(f, s, null);
}
public static ItemStack loadItem(FileConfiguration f, String s, Player papiPlayer) {
return loadItem(f.getConfigurationSection(s), papiPlayer);
return loadItem(f.getConfigurationSection(s), papiPlayer);
}
public static ItemStack loadItem(ConfigurationSection section, Player papiPlayer) {
if (section.get("bukkit") instanceof ItemStack) {
return section.getItemStack("bukkit");
}
// 材质
ItemStack item = new ItemStack(asMaterial(section.get("material").toString()));
// 数量
item.setAmount(section.contains("amount") ? section.getInt("amount") : 1);
// 耐久
item.setDurability((short) section.getInt("data"));
// 元数据
ItemMeta meta = item.getItemMeta();
// 展示名
if (section.contains("name")) {
meta.setDisplayName(asString(section.getString("name"), papiPlayer));
}
// 描述
if (section.contains("lore")) {
meta.setLore(asString(section.getStringList("lore"), papiPlayer));
}
// 附魔
if (section.contains("enchants")) {
for (String preEnchant : section.getConfigurationSection("enchants").getKeys(false)) {
Enchantment enchant = asEnchantment(preEnchant);
if (enchant != null) {
meta.addEnchant(enchant, section.getInt("enchants." + preEnchant), true);
}
else {
MsgUtils.warn("&8" + preEnchant + " &c不是一个有效的附魔名称");
MsgUtils.warn("&c输入 &4/taboolib enchants&c 查看所有附魔");
}
}
}
// 标签
if (section.contains("flags") && TabooLib.getVerint() > 10700) {
for (String preFlag : section.getStringList("flags")) {
ItemFlag flag = asItemFlag(preFlag);
if (flag != null) {
meta.addItemFlags(flag);
}
else {
MsgUtils.warn("&8" + preFlag + " &c不是一个有效的标签名称");
MsgUtils.warn("&c输入 &4/taboolib flags&c 查看所有标签");
}
}
}
// 皮革
if (meta instanceof LeatherArmorMeta && section.contains("color")) {
((LeatherArmorMeta) meta).setColor(asColor(section.getString("color")));
}
// 药水
if (meta instanceof PotionMeta && section.contains("potions")) {
PotionMeta potionMeta = (PotionMeta) meta;
for (String prePotionName : section.getConfigurationSection("potions").getKeys(false)) {
PotionEffectType potionEffectType = asPotionEffectType(prePotionName);
if (potionEffectType != null) {
potionMeta.addCustomEffect(new PotionEffect(
potionEffectType,
NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[0]),
NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[1]) - 1), true);
}
else {
MsgUtils.warn("&8" + potionEffectType + " &c不是一个有效的药水名称");
MsgUtils.warn("&c输入 &4/taboolib potions&c 查看所有药水");
}
}
}
// 元数据
item.setItemMeta(meta);
// 数据
NBTItem nbt = new NBTItem(item);
// 物品标签
if (section.contains("nbt")) {
for (String name : section.getConfigurationSection("nbt").getKeys(false)) {
Object obj = section.get("nbt." + name);
if (obj instanceof String) {
nbt.setString(name, obj.toString());
}
else if (obj instanceof Double) {
nbt.setDouble(name, Double.valueOf(obj.toString()));
}
else if (obj instanceof Integer) {
nbt.setInteger(name, Integer.valueOf(obj.toString()));
}
else if (obj instanceof Long) {
nbt.setLong(name, Long.valueOf(obj.toString()));
}
else {
nbt.setObject(name, obj);
}
}
}
// 物品属性
if (section.contains("attributes")) {
NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound);
for (String hand : section.getConfigurationSection("attributes").getKeys(false)) {
for (String name : section.getConfigurationSection("attributes." + hand).getKeys(false)) {
if (asAttribute(name) != null) {
try {
NBTListCompound _attr = attr.addCompound();
Object num = section.get("attributes." + hand + "." + name);
if (num.toString().contains("%")) {
_attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D);
_attr.setInteger("Operation", 1);
}
else {
_attr.setDouble("Amount", Double.valueOf(num.toString()));
_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.setString("Name", asAttribute(name));
if (!hand.equals("all")) {
_attr.setString("Slot", hand);
}
}
catch (Exception e) {
MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage());
}
}
else {
MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称");
MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性");
}
}
}
}
return nbt.getItem();
if (section.get("bukkit") instanceof ItemStack) {
return section.getItemStack("bukkit");
}
// 材质
ItemStack item = new ItemStack(asMaterial(section.get("material").toString()));
// 数量
item.setAmount(section.contains("amount") ? section.getInt("amount") : 1);
// 耐久
item.setDurability((short) section.getInt("data"));
// 元数据
ItemMeta meta = item.getItemMeta();
// 展示名
if (section.contains("name")) {
meta.setDisplayName(asString(section.getString("name"), papiPlayer));
}
// 描述
if (section.contains("lore")) {
meta.setLore(asString(section.getStringList("lore"), papiPlayer));
}
// 附魔
if (section.contains("enchants")) {
for (String preEnchant : section.getConfigurationSection("enchants").getKeys(false)) {
Enchantment enchant = asEnchantment(preEnchant);
if (enchant != null) {
meta.addEnchant(enchant, section.getInt("enchants." + preEnchant), true);
} else {
MsgUtils.warn("&8" + preEnchant + " &c不是一个有效的附魔名称");
MsgUtils.warn("&c输入 &4/taboolib enchants&c 查看所有附魔");
}
}
}
// 标签
if (section.contains("flags") && TabooLib.getVerint() > 10700) {
for (String preFlag : section.getStringList("flags")) {
ItemFlag flag = asItemFlag(preFlag);
if (flag != null) {
meta.addItemFlags(flag);
} else {
MsgUtils.warn("&8" + preFlag + " &c不是一个有效的标签名称");
MsgUtils.warn("&c输入 &4/taboolib flags&c 查看所有标签");
}
}
}
// 皮革
if (meta instanceof LeatherArmorMeta && section.contains("color")) {
((LeatherArmorMeta) meta).setColor(asColor(section.getString("color")));
}
// 药水
if (meta instanceof PotionMeta && section.contains("potions")) {
PotionMeta potionMeta = (PotionMeta) meta;
for (String prePotionName : section.getConfigurationSection("potions").getKeys(false)) {
PotionEffectType potionEffectType = asPotionEffectType(prePotionName);
if (potionEffectType != null) {
potionMeta.addCustomEffect(new PotionEffect(
potionEffectType,
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 查看所有药水");
}
}
}
// 元数据
item.setItemMeta(meta);
// 数据
NBTItem nbt = new NBTItem(item);
// 物品标签
if (section.contains("nbt")) {
for (String name : section.getConfigurationSection("nbt").getKeys(false)) {
Object obj = section.get("nbt." + name);
if (obj instanceof String) {
nbt.setString(name, obj.toString());
} else if (obj instanceof Double) {
nbt.setDouble(name, Double.valueOf(obj.toString()));
} else if (obj instanceof Integer) {
nbt.setInteger(name, Integer.valueOf(obj.toString()));
} else if (obj instanceof Long) {
nbt.setLong(name, Long.valueOf(obj.toString()));
} else {
nbt.setObject(name, obj);
}
}
}
// 物品属性
if (section.contains("attributes")) {
NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound);
for (String hand : section.getConfigurationSection("attributes").getKeys(false)) {
for (String name : section.getConfigurationSection("attributes." + hand).getKeys(false)) {
if (asAttribute(name) != null) {
try {
NBTListCompound _attr = attr.addCompound();
Object num = section.get("attributes." + hand + "." + name);
if (num.toString().contains("%")) {
_attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D);
_attr.setInteger("Operation", 1);
} else {
_attr.setDouble("Amount", Double.valueOf(num.toString()));
_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.setString("Name", asAttribute(name));
if (!hand.equals("all")) {
_attr.setString("Slot", hand);
}
} catch (Exception e) {
MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage());
}
} else {
MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称");
MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性");
}
}
}
}
return nbt.getItem();
}
public static NBTItem setAttribute(NBTItem nbt, String name, Object num, String hand) {
NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound);
if (asAttribute(name) != null) {
try {
NBTListCompound _attr = null;
for (int i = 0 ; i < attr.size() ; i++) {
NBTListCompound nlc = attr.getCompound(i);
if (nlc.getString("AttributeName").equals(asAttribute(name))) {
_attr = nlc;
}
}
if (_attr == null) {
_attr = attr.addCompound();
}
if (num.toString().contains("%")) {
_attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D);
_attr.setInteger("Operation", 1);
}
else {
_attr.setDouble("Amount", Double.valueOf(num.toString()));
_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.setString("Name", asAttribute(name));
if (!hand.equals("all")) {
_attr.setString("Slot", hand);
}
}
catch (Exception e) {
MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage());
}
}
else {
MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称");
MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性");
}
return nbt;
NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound);
if (asAttribute(name) != null) {
try {
NBTListCompound _attr = null;
for (int i = 0; i < attr.size(); i++) {
NBTListCompound nlc = attr.getCompound(i);
if (nlc.getString("AttributeName").equals(asAttribute(name))) {
_attr = nlc;
}
}
if (_attr == null) {
_attr = attr.addCompound();
}
if (num.toString().contains("%")) {
_attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D);
_attr.setInteger("Operation", 1);
} else {
_attr.setDouble("Amount", Double.valueOf(num.toString()));
_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.setString("Name", asAttribute(name));
if (!hand.equals("all")) {
_attr.setString("Slot", hand);
}
} catch (Exception e) {
MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage());
}
} else {
MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称");
MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性");
}
return nbt;
}
@Deprecated
public static void putO(ItemStack item, Inventory inv, int i) {
inv.setItem(i, item);
inv.setItem(i+1, item);
inv.setItem(i+2, item);
inv.setItem(i+9, item);
inv.setItem(i+10, null);
inv.setItem(i+11, item);
inv.setItem(i+18, item);
inv.setItem(i+19, item);
inv.setItem(i+20, item);
}
inv.setItem(i, item);
inv.setItem(i + 1, item);
inv.setItem(i + 2, item);
inv.setItem(i + 9, item);
inv.setItem(i + 10, null);
inv.setItem(i + 11, item);
inv.setItem(i + 18, item);
inv.setItem(i + 19, item);
inv.setItem(i + 20, item);
}
}

View File

@ -1,8 +1,8 @@
package me.skymc.taboolib.inventory.speciaitem;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.message.MsgUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
@ -12,141 +12,144 @@ import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.plugin.Plugin;
import lombok.Getter;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.message.MsgUtils;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* @author sky
* @since 2018217 8:34:12
*/
public class SpecialItem implements Listener {
private static SpecialItem specialItem = null;
private final List<AbstractSpecialItem> ITEM_DATA = new CopyOnWriteArrayList<>();
@Getter
private boolean isLoaded;
/**
*
*/
private SpecialItem() {
}
/**
*
*
* @return {@link SpecialItem}
*/
public static SpecialItem getInst() {
if (specialItem == null) {
synchronized (SpecialItem.class) {
if (specialItem == null) {
specialItem = new SpecialItem();
// 注册监听器
Bukkit.getPluginManager().registerEvents(specialItem, Main.getInst());
}
}
}
return specialItem;
}
/**
*
*
* @param item
*/
public void register(AbstractSpecialItem item) {
if (contains(item.getName())) {
MsgUtils.warn("特殊物品接口已存在, 检查名称 &4" + item.getName() + " &c是否重复");
}
else {
ITEM_DATA.add(item);
if (isLoaded) {
item.onEnable();
}
}
}
/**
*
*
* @param name
*/
public void cancel(String name) {
for (AbstractSpecialItem specialitem : ITEM_DATA) {
if (specialitem.getName() != null && specialitem.getName().equals(specialitem.getName())) {
specialitem.onDisable();
ITEM_DATA.remove(specialitem);
}
}
}
/**
*
*
* @param plugin
*/
public void cancel(Plugin plugin) {
for (AbstractSpecialItem specialitem : ITEM_DATA) {
if (specialitem.getPlugin() != null && specialitem.getPlugin().equals(plugin)) {
specialitem.onDisable();
ITEM_DATA.remove(specialitem);
}
}
}
/**
*
*
* @param name
* @return boolean
*/
public boolean contains(String name) {
for (AbstractSpecialItem specialitem : ITEM_DATA) {
if (specialitem.getName().equals(name)) {
return true;
}
}
return false;
}
/**
*
*/
public void loadItems() {
private static SpecialItem specialItem = null;
private final List<AbstractSpecialItem> ITEM_DATA = new CopyOnWriteArrayList<>();
private boolean isLoaded;
public boolean isLoaded() {
return isLoaded;
}
/**
*
*/
private SpecialItem() {
}
/**
*
*
* @return {@link SpecialItem}
*/
public static SpecialItem getInst() {
if (specialItem == null) {
synchronized (SpecialItem.class) {
if (specialItem == null) {
specialItem = new SpecialItem();
// 注册监听器
Bukkit.getPluginManager().registerEvents(specialItem, Main.getInst());
}
}
}
return specialItem;
}
/**
*
*
* @param item
*/
public void register(AbstractSpecialItem item) {
if (contains(item.getName())) {
MsgUtils.warn("特殊物品接口已存在, 检查名称 &4" + item.getName() + " &c是否重复");
} else {
ITEM_DATA.add(item);
if (isLoaded) {
item.onEnable();
}
}
}
/**
*
*
* @param name
*/
public void cancel(String name) {
for (AbstractSpecialItem specialitem : ITEM_DATA) {
if (specialitem.getName() != null && specialitem.getName().equals(specialitem.getName())) {
specialitem.onDisable();
ITEM_DATA.remove(specialitem);
}
}
}
/**
*
*
* @param plugin
*/
public void cancel(Plugin plugin) {
for (AbstractSpecialItem specialitem : ITEM_DATA) {
if (specialitem.getPlugin() != null && specialitem.getPlugin().equals(plugin)) {
specialitem.onDisable();
ITEM_DATA.remove(specialitem);
}
}
}
/**
*
*
* @param name
* @return boolean
*/
public boolean contains(String name) {
for (AbstractSpecialItem specialitem : ITEM_DATA) {
if (specialitem.getName().equals(name)) {
return true;
}
}
return false;
}
/**
*
*/
public void loadItems() {
ITEM_DATA.forEach(AbstractSpecialItem::onEnable);
isLoaded = true;
}
/**
*
*/
public void unloadItems() {
isLoaded = true;
}
/**
*
*/
public void unloadItems() {
ITEM_DATA.forEach(AbstractSpecialItem::onDisable);
ITEM_DATA.clear();
}
@EventHandler
public void onDisable(PluginDisableEvent e) {
cancel(e.getPlugin());
}
@EventHandler (priority = EventPriority.MONITOR)
public void click(InventoryClickEvent e) {
if (e.isCancelled()) {
return;
}
if (ItemUtils.isNull(e.getCurrentItem()) || ItemUtils.isNull(e.getCursor())) {
return;
}
Player player = (Player) e.getWhoClicked();
for (AbstractSpecialItem specialitem : ITEM_DATA) {
for (SpecialItemResult result : specialitem.isCorrectClick(player, e.getCurrentItem(), e.getCursor())) {
ITEM_DATA.clear();
}
@EventHandler
public void onDisable(PluginDisableEvent e) {
cancel(e.getPlugin());
}
@EventHandler(priority = EventPriority.MONITOR)
public void click(InventoryClickEvent e) {
if (e.isCancelled()) {
return;
}
if (ItemUtils.isNull(e.getCurrentItem()) || ItemUtils.isNull(e.getCursor())) {
return;
}
Player player = (Player) e.getWhoClicked();
for (AbstractSpecialItem specialItem : ITEM_DATA) {
for (SpecialItemResult result : specialItem.isCorrectClick(player, e.getCurrentItem(), e.getCursor())) {
if (result == null) {
break;
}
switch (result) {
case CANCEL:
e.setCancelled(true);
@ -173,8 +176,8 @@ public class SpecialItem implements Listener {
e.getWhoClicked().setItemOnCursor(null);
}
break;
}
}
}
}
}
}
}
}
}

View File

@ -1,6 +1,6 @@
package me.skymc.taboolib.itemnbtapi;
public class NBTContainer extends NBTCompound{
public class NBTContainer extends NBTCompound {
private Object nbt;
@ -8,29 +8,29 @@ public class NBTContainer extends NBTCompound{
super(null, null);
nbt = NBTReflectionUtil.getNewNBTTag();
}
protected NBTContainer(Object nbt){
protected NBTContainer(Object nbt) {
super(null, null);
this.nbt = nbt;
}
public NBTContainer(String nbtString) throws IllegalArgumentException {
super(null, null);
try{
try {
nbt = NBTReflectionUtil.parseNBT(nbtString);
}catch(Exception ex){
} catch (Exception ex) {
ex.printStackTrace();
throw new IllegalArgumentException("Malformed Json: " + ex.getMessage());
}
}
@Override
protected Object getCompound() {
protected Object getCompound() {
return nbt;
}
@Override
protected void setCompound(Object tag) {
protected void setCompound(Object tag) {
nbt = tag;
}

View File

@ -36,12 +36,12 @@ public class NBTFile extends NBTCompound {
}
@Override
protected Object getCompound() {
protected Object getCompound() {
return nbt;
}
@Override
protected void setCompound(Object compound) {
protected void setCompound(Object compound) {
nbt = compound;
}

View File

@ -12,12 +12,12 @@ public class NBTItem extends NBTCompound {
}
@Override
protected Object getCompound() {
protected Object getCompound() {
return NBTReflectionUtil.getItemRootNBTTagCompound(NBTReflectionUtil.getNMSItemStack(bukkitItem));
}
@Override
protected void setCompound(Object compound) {
protected void setCompound(Object compound) {
bukkitItem = NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.setNBTTag(compound, NBTReflectionUtil.getNMSItemStack(bukkitItem)));
}
@ -28,12 +28,12 @@ public class NBTItem extends NBTCompound {
protected void setItem(ItemStack item) {
bukkitItem = item;
}
public static NBTContainer convertItemtoNBT(ItemStack item){
public static NBTContainer convertItemtoNBT(ItemStack item) {
return NBTReflectionUtil.convertNMSItemtoNBTCompound(NBTReflectionUtil.getNMSItemStack(item));
}
public static ItemStack convertNBTtoItem(NBTCompound comp){
public static ItemStack convertNBTtoItem(NBTCompound comp) {
return NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.convertNBTCompoundtoNMSItem(comp));
}

View File

@ -1,10 +1,10 @@
package me.skymc.taboolib.itemnbtapi;
import java.lang.reflect.Method;
import me.skymc.taboolib.itemnbtapi.utils.MethodNames;
import me.skymc.taboolib.message.MsgUtils;
import java.lang.reflect.Method;
public class NBTList {
private String listName;
@ -37,7 +37,7 @@ public class NBTList {
method.invoke(listObject, compound);
return new NBTListCompound(this, compound);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return null;
}
@ -52,7 +52,7 @@ public class NBTList {
Object compound = method.invoke(listObject, id);
return new NBTListCompound(this, compound);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return null;
}
@ -66,7 +66,7 @@ public class NBTList {
Method method = listObject.getClass().getMethod("getString", int.class);
return (String) method.invoke(listObject, i);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return null;
}
@ -82,7 +82,7 @@ public class NBTList {
method.invoke(listObject, NBTReflectionUtil.getNBTTagString().getConstructor(String.class).newInstance(s));
save();
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
}
@ -97,7 +97,7 @@ public class NBTList {
method.invoke(listObject, i, NBTReflectionUtil.getNBTTagString().getConstructor(String.class).newInstance(s));
save();
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
}
@ -107,7 +107,7 @@ public class NBTList {
method.invoke(listObject, i);
save();
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
}
@ -116,7 +116,7 @@ public class NBTList {
Method method = listObject.getClass().getMethod("size");
return (int) method.invoke(listObject);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return -1;
}

View File

@ -1,10 +1,10 @@
package me.skymc.taboolib.itemnbtapi;
import me.skymc.taboolib.message.MsgUtils;
import java.util.HashSet;
import java.util.Set;
import me.skymc.taboolib.message.MsgUtils;
public class NBTListCompound {
private NBTList owner;
@ -24,7 +24,7 @@ public class NBTListCompound {
compound.getClass().getMethod("setString", String.class, String.class).invoke(compound, key, value);
owner.save();
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
}
@ -33,7 +33,7 @@ public class NBTListCompound {
compound.getClass().getMethod("setInt", String.class, int.class).invoke(compound, key, value);
owner.save();
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
}
@ -41,7 +41,7 @@ public class NBTListCompound {
try {
return (int) compound.getClass().getMethod("getInt", String.class).invoke(compound, value);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return 0;
}
@ -51,7 +51,7 @@ public class NBTListCompound {
compound.getClass().getMethod("setDouble", String.class, double.class).invoke(compound, key, value);
owner.save();
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
}
@ -59,7 +59,7 @@ public class NBTListCompound {
try {
return (double) compound.getClass().getMethod("getDouble", String.class).invoke(compound, key);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return 0;
}
@ -69,7 +69,7 @@ public class NBTListCompound {
try {
return (String) compound.getClass().getMethod("getString", String.class).invoke(compound, key);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return "";
}
@ -78,7 +78,7 @@ public class NBTListCompound {
try {
return (boolean) compound.getClass().getMethod("hasKey", String.class).invoke(compound, key);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return false;
}
@ -88,7 +88,7 @@ public class NBTListCompound {
try {
return (Set<String>) compound.getClass().getMethod("c").invoke(compound);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return new HashSet<>();
}
@ -97,7 +97,7 @@ public class NBTListCompound {
try {
compound.getClass().getMethod("remove", String.class).invoke(compound, key);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
}

View File

@ -1,5 +1,14 @@
package me.skymc.taboolib.itemnbtapi;
import me.skymc.taboolib.TabooLib;
import me.skymc.taboolib.itemnbtapi.utils.GsonWrapper;
import me.skymc.taboolib.itemnbtapi.utils.MethodNames;
import me.skymc.taboolib.message.MsgUtils;
import org.bukkit.Bukkit;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import org.bukkit.inventory.ItemStack;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
@ -8,28 +17,18 @@ import java.lang.reflect.Method;
import java.util.Set;
import java.util.Stack;
import org.bukkit.Bukkit;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import org.bukkit.inventory.ItemStack;
import me.skymc.taboolib.TabooLib;
import me.skymc.taboolib.itemnbtapi.utils.GsonWrapper;
import me.skymc.taboolib.itemnbtapi.utils.MethodNames;
import me.skymc.taboolib.message.MsgUtils;
// TODO: finish codestyle cleanup -sgdc3
public class NBTReflectionUtil {
private static final String version = TabooLib.getVersion();
@SuppressWarnings("rawtypes")
private static Class getCraftItemStack() {
try {
return Class.forName("org.bukkit.craftbukkit." + version + ".inventory.CraftItemStack");
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null;
}
}
@ -39,7 +38,7 @@ public class NBTReflectionUtil {
try {
return Class.forName("org.bukkit.craftbukkit." + version + ".entity.CraftEntity");
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null;
}
}
@ -49,7 +48,7 @@ public class NBTReflectionUtil {
try {
return Class.forName("net.minecraft.server." + version + ".NBTBase");
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null;
}
}
@ -59,19 +58,19 @@ public class NBTReflectionUtil {
try {
return Class.forName("net.minecraft.server." + version + ".NBTTagString");
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null;
}
}
@SuppressWarnings("rawtypes")
protected static Class getNMSItemStack() {
try {
return Class.forName("net.minecraft.server." + version + ".ItemStack");
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null;
}
}
@ -81,8 +80,8 @@ public class NBTReflectionUtil {
try {
return Class.forName("net.minecraft.server." + version + ".NBTTagCompound");
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null;
}
}
@ -92,19 +91,19 @@ public class NBTReflectionUtil {
try {
return Class.forName("net.minecraft.server." + version + ".NBTCompressedStreamTools");
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null;
}
}
@SuppressWarnings("rawtypes")
protected static Class getMojangsonParser() {
try {
return Class.forName("net.minecraft.server." + version + ".MojangsonParser");
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null;
}
}
@ -114,8 +113,8 @@ public class NBTReflectionUtil {
try {
return Class.forName("net.minecraft.server." + version + ".TileEntity");
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null;
}
}
@ -125,8 +124,8 @@ public class NBTReflectionUtil {
try {
return Class.forName("org.bukkit.craftbukkit." + version + ".CraftWorld");
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null;
}
}
@ -138,8 +137,8 @@ public class NBTReflectionUtil {
Class c = Class.forName("net.minecraft.server." + version + ".NBTTagCompound");
return c.newInstance();
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null;
}
}
@ -151,8 +150,8 @@ public class NBTReflectionUtil {
Class clazz = Class.forName("net.minecraft.server." + version + ".BlockPosition");
return clazz.getConstructor(int.class, int.class, int.class).newInstance(x, y, z);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null;
}
}
@ -164,7 +163,7 @@ public class NBTReflectionUtil {
method.invoke(NMSItem, NBTTag);
return NMSItem;
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return null;
}
@ -178,7 +177,7 @@ public class NBTReflectionUtil {
method = clazz.getMethod("asNMSCopy", ItemStack.class);
return method.invoke(clazz, item);
} catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
}
return null;
}
@ -192,7 +191,7 @@ public class NBTReflectionUtil {
method = clazz.getMethod("getHandle");
return method.invoke(getCraftEntity().cast(entity));
} catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
}
return null;
}
@ -206,11 +205,11 @@ public class NBTReflectionUtil {
method = cis.getMethod("parse", String.class);
return method.invoke(null, json);
} catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
}
return null;
}
@SuppressWarnings({"unchecked"})
public static Object readNBTFile(FileInputStream stream) {
@SuppressWarnings("rawtypes")
@ -220,7 +219,7 @@ public class NBTReflectionUtil {
method = clazz.getMethod("a", InputStream.class);
return method.invoke(clazz, stream);
} catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
}
return null;
}
@ -234,7 +233,7 @@ public class NBTReflectionUtil {
method = clazz.getMethod("a", getNBTTagCompound(), OutputStream.class);
return method.invoke(clazz, nbt, stream);
} catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
}
return null;
}
@ -249,7 +248,7 @@ public class NBTReflectionUtil {
Object answer = method.invoke(clazz, item);
return (ItemStack) answer;
} catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
}
return null;
}
@ -263,11 +262,11 @@ public class NBTReflectionUtil {
method = clazz.getMethod("getTag");
return method.invoke(nmsitem);
} catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
}
return null;
}
@SuppressWarnings({"unchecked"})
public static Object convertNBTCompoundtoNMSItem(NBTCompound nbtcompound) {
@SuppressWarnings("rawtypes")
@ -275,11 +274,11 @@ public class NBTReflectionUtil {
try {
return clazz.getConstructor(getNBTTagCompound()).newInstance(nbtcompound.getCompound());
} catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
}
return null;
}
@SuppressWarnings({"unchecked"})
public static NBTContainer convertNMSItemtoNBTCompound(Object nmsitem) {
@SuppressWarnings("rawtypes")
@ -290,7 +289,7 @@ public class NBTReflectionUtil {
Object answer = method.invoke(nmsitem, getNewNBTTag());
return new NBTContainer(answer);
} catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
}
return null;
}
@ -308,7 +307,7 @@ public class NBTReflectionUtil {
answer = nbt;
return answer;
} catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
}
return null;
}
@ -320,7 +319,7 @@ public class NBTReflectionUtil {
method.invoke(NMSItem, NBTTag);
return NMSItem;
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return null;
}
@ -339,7 +338,7 @@ public class NBTReflectionUtil {
answer = tag;
return answer;
} catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
}
return null;
}
@ -354,7 +353,7 @@ public class NBTReflectionUtil {
method = getTileEntity().getMethod("a", getNBTTagCompound());
method.invoke(o, comp);
} catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
}
}
@ -368,7 +367,7 @@ public class NBTReflectionUtil {
method = c.getMethod("getCompound", String.class);
return method.invoke(compound, name);
} catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
}
return null;
}
@ -390,7 +389,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, name, getNBTTagCompound().newInstance());
comp.setCompound(nbttag);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
}
@ -416,7 +415,7 @@ public class NBTReflectionUtil {
}
return nbttag;
}
public static void addOtherNBTCompound(NBTCompound comp, NBTCompound nbtcompound) {
Object rootnbttag = comp.getCompound();
if (rootnbttag == null) {
@ -430,7 +429,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, nbtcompound.getCompound());
comp.setCompound(rootnbttag);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
}
@ -451,7 +450,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, key, text);
comp.setCompound(rootnbttag);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
}
@ -467,7 +466,7 @@ public class NBTReflectionUtil {
method = workingtag.getClass().getMethod("getString", String.class);
return (String) method.invoke(workingtag, key);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return null;
}
@ -484,7 +483,7 @@ public class NBTReflectionUtil {
method = workingtag.getClass().getMethod("get", String.class);
return method.invoke(workingtag, key).toString();
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return null;
}
@ -506,7 +505,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, key, i);
comp.setCompound(rootnbttag);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
}
@ -522,7 +521,7 @@ public class NBTReflectionUtil {
method = workingtag.getClass().getMethod("getInt", String.class);
return (Integer) method.invoke(workingtag, key);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return null;
}
@ -544,7 +543,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, key, b);
comp.setCompound(rootnbttag);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
}
@ -560,7 +559,7 @@ public class NBTReflectionUtil {
method = workingtag.getClass().getMethod("getByteArray", String.class);
return (byte[]) method.invoke(workingtag, key);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return null;
}
@ -582,7 +581,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, key, i);
comp.setCompound(rootnbttag);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
}
@ -598,7 +597,7 @@ public class NBTReflectionUtil {
method = workingtag.getClass().getMethod("getIntArray", String.class);
return (int[]) method.invoke(workingtag, key);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return null;
}
@ -620,7 +619,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, key, f);
comp.setCompound(rootnbttag);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
}
@ -636,7 +635,7 @@ public class NBTReflectionUtil {
method = workingtag.getClass().getMethod("getFloat", String.class);
return (Float) method.invoke(workingtag, key);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return null;
}
@ -658,7 +657,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, key, f);
comp.setCompound(rootnbttag);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
}
@ -674,7 +673,7 @@ public class NBTReflectionUtil {
method = workingtag.getClass().getMethod("getLong", String.class);
return (Long) method.invoke(workingtag, key);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return null;
}
@ -696,7 +695,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, key, f);
comp.setCompound(rootnbttag);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
}
@ -712,7 +711,7 @@ public class NBTReflectionUtil {
method = workingtag.getClass().getMethod("getShort", String.class);
return (Short) method.invoke(workingtag, key);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return null;
}
@ -734,7 +733,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, key, f);
comp.setCompound(rootnbttag);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
}
@ -750,7 +749,7 @@ public class NBTReflectionUtil {
method = workingtag.getClass().getMethod("getByte", String.class);
return (Byte) method.invoke(workingtag, key);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return null;
}
@ -772,7 +771,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, key, d);
comp.setCompound(rootnbttag);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
}
@ -788,7 +787,7 @@ public class NBTReflectionUtil {
method = workingtag.getClass().getMethod("getDouble", String.class);
return (Double) method.invoke(workingtag, key);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return null;
}
@ -805,7 +804,7 @@ public class NBTReflectionUtil {
method = workingtag.getClass().getMethod(MethodNames.getTypeMethodName(), String.class);
return (byte) method.invoke(workingtag, key);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return 0;
}
@ -827,7 +826,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, key, d);
comp.setCompound(rootnbttag);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
}
@ -843,7 +842,7 @@ public class NBTReflectionUtil {
method = workingtag.getClass().getMethod("getBoolean", String.class);
return (Boolean) method.invoke(workingtag, key);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return null;
}
@ -868,7 +867,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, key, val);
comp.setCompound(rootnbttag);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
}
@ -884,7 +883,7 @@ public class NBTReflectionUtil {
method = workingtag.getClass().getMethod("getList", String.class, int.class);
return new NBTList(comp, key, type, method.invoke(workingtag, key, type.getId()));
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return null;
}
@ -894,7 +893,7 @@ public class NBTReflectionUtil {
String json = GsonWrapper.getString(value);
setString(comp, key, json);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
}
@ -919,7 +918,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, key);
comp.setCompound(rootnbttag);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
}
@ -935,7 +934,7 @@ public class NBTReflectionUtil {
method = workingtag.getClass().getMethod("hasKey", String.class);
return (Boolean) method.invoke(workingtag, key);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return null;
}
@ -953,7 +952,7 @@ public class NBTReflectionUtil {
method = workingtag.getClass().getMethod("c");
return (Set<String>) method.invoke(workingtag);
} catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
}
return null;
}

View File

@ -12,12 +12,12 @@ public class NBTTileEntity extends NBTCompound {
}
@Override
protected Object getCompound() {
protected Object getCompound() {
return NBTReflectionUtil.getTileEntityNBTTagCompound(tile);
}
@Override
protected void setCompound(Object compound) {
protected void setCompound(Object compound) {
NBTReflectionUtil.setTileEntityNBTTagCompound(tile, compound);
}

View File

@ -1,6 +1,7 @@
package me.skymc.taboolib.itemnbtapi;
public enum NBTType {
NBTTagEnd(0),
NBTTagByte(1),
NBTTagShort(2),

View File

@ -1,7 +1,6 @@
package me.skymc.taboolib.itemnbtapi.utils;
import com.google.gson.Gson;
import me.skymc.taboolib.message.MsgUtils;
public class GsonWrapper {

View File

@ -11,7 +11,7 @@ public class MethodNames {
public static String getEntityNbtSetterMethodName() {
return "a";
}
public static String getTileDataMethodName() {
if (TabooLib.getVerint() <= 10800) {
return "b";

View File

@ -1,77 +1,76 @@
package me.skymc.taboolib.javascript;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import me.skymc.taboolib.Main;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import me.skymc.taboolib.Main;
@Deprecated
public class JavaScriptUtils {
private static ScriptEngineManager manager = new ScriptEngineManager();
public static ScriptEngineManager getScriptManager() {
return manager;
}
public static void invokeJavaScript(File jsFile, String method, Object... o) {
ScriptEngine engine = manager.getEngineByName("javascript");
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(Main.class.getClassLoader());
FileReader reader = new FileReader(jsFile);
engine.eval(reader);
// TODO run
Thread.currentThread().setContextClassLoader(classLoader);
}
catch (Exception e) {
// TODO: handle exception
}
}
@Deprecated
public static Object JavaScriptInterface(String jsFile, Object... o) {
ScriptEngine engine = manager.getEngineByName("javascript");
try {
FileReader reader = new FileReader(jsFile);
engine.eval(reader);
if (engine instanceof Invocable) {
return ((Invocable) engine).invokeFunction("main", o);
}
reader.close();
} catch (NoSuchMethodException | IOException | ScriptException e) {
e.printStackTrace();
}
return null;
}
@Deprecated
public static void JavaScriptExecute(String jsFile, Object... o) {
ScriptEngine engine = manager.getEngineByName("javascript");
try {
FileReader reader = new FileReader(jsFile);
engine.eval(reader);
if (engine instanceof Invocable) {
((Invocable) engine).invokeFunction("main", o);
}
reader.close();
} catch (NoSuchMethodException | IOException | ScriptException e) {
e.printStackTrace();
}
}
private static ScriptEngineManager manager = new ScriptEngineManager();
public static ScriptEngineManager getScriptManager() {
return manager;
}
public static void invokeJavaScript(File jsFile, String method, Object... o) {
ScriptEngine engine = manager.getEngineByName("javascript");
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(Main.class.getClassLoader());
FileReader reader = new FileReader(jsFile);
engine.eval(reader);
// TODO run
Thread.currentThread().setContextClassLoader(classLoader);
} catch (Exception e) {
// TODO: handle exception
}
}
@Deprecated
public static Object JavaScriptInterface(String jsFile, Object... o) {
ScriptEngine engine = manager.getEngineByName("javascript");
try {
FileReader reader = new FileReader(jsFile);
engine.eval(reader);
if (engine instanceof Invocable) {
return ((Invocable) engine).invokeFunction("main", o);
}
reader.close();
} catch (NoSuchMethodException | IOException | ScriptException e) {
e.printStackTrace();
}
return null;
}
@Deprecated
public static void JavaScriptExecute(String jsFile, Object... o) {
ScriptEngine engine = manager.getEngineByName("javascript");
try {
FileReader reader = new FileReader(jsFile);
engine.eval(reader);
if (engine instanceof Invocable) {
((Invocable) engine).invokeFunction("main", o);
}
reader.close();
} catch (NoSuchMethodException | IOException | ScriptException e) {
e.printStackTrace();
}
}
}

View File

@ -1,8 +1,6 @@
package me.skymc.taboolib.javashell;
import com.ilummc.tlib.dependency.TDependencyLoader;
import lombok.Getter;
import lombok.Setter;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.message.MsgUtils;
import org.apache.commons.lang.ArrayUtils;
@ -16,41 +14,78 @@ import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Objects;
public class JavaShell {
@Getter
@Setter
private static String paths = "";
@Getter
@Setter
private static File javaShellFolder;
@Getter
@Setter
private static File scriptFolder;
@Getter
@Setter
private static File cacheFolder;
@Getter
@Setter
private static File libFolder;
@Getter
@Setter
private static HashMap<String, Class<?>> shells = new HashMap<>();
public static String getPaths() {
return paths;
}
public static void setPaths(String paths) {
JavaShell.paths = paths;
}
public static File getJavaShellFolder() {
return javaShellFolder;
}
public static void setJavaShellFolder(File javaShellFolder) {
JavaShell.javaShellFolder = javaShellFolder;
}
public static File getScriptFolder() {
return scriptFolder;
}
public static void setScriptFolder(File scriptFolder) {
JavaShell.scriptFolder = scriptFolder;
}
public static File getCacheFolder() {
return cacheFolder;
}
public static void setCacheFolder(File cacheFolder) {
JavaShell.cacheFolder = cacheFolder;
}
public static File getLibFolder() {
return libFolder;
}
public static void setLibFolder(File libFolder) {
JavaShell.libFolder = libFolder;
}
public static HashMap<String, Class<?>> getShells() {
return shells;
}
public static void setShells(HashMap<String, Class<?>> shells) {
JavaShell.shells = shells;
}
public static void javaShellSetup() {
File dataFolder = Main.getInst().getDataFolder();
File pluginsFolder = dataFolder.getParentFile();
File serverRoot = Bukkit.getWorldContainer();
File[] rootJars = serverRoot.listFiles((dir, name) -> name.toLowerCase().endsWith("jar"));
File[] pluginJars = pluginsFolder.listFiles((dir, name) -> name.toLowerCase().endsWith("jar"));
for (File file : (File[]) ArrayUtils.addAll(rootJars, pluginJars)) {
@ -85,27 +120,23 @@ public class JavaShell {
}
loadLibrary();
new BukkitRunnable() {
@Override
public void run() {
long time = System.currentTimeMillis();
for (File file : scriptFolder.listFiles()) {
if (!file.getName().startsWith("-")) {
reloadShell(file.getName());
}
}
Arrays.stream(Objects.requireNonNull(scriptFolder.listFiles())).filter(file -> !file.getName().startsWith("-")).map(File::getName).forEach(JavaShell::reloadShell);
MsgUtils.send("载入 " + shells.size() + " 个脚本, 耗时 &f" + (System.currentTimeMillis() - time) + "ms");
}
}.runTask(Main.getInst());
}
public static void javaShellCancel() {
for (File cacheFile : cacheFolder.listFiles()) {
cacheFile.delete();
}
for (String name : shells.keySet()) {
invokeMethod(name, "onDisable");
try {
Arrays.stream(Objects.requireNonNull(cacheFolder.listFiles())).forEach(File::delete);
shells.keySet().forEach(name -> invokeMethod(name, "onDisable"));
} catch (Exception ignored) {
}
}
@ -117,8 +148,7 @@ public class JavaShell {
if (disableMethod != null) {
disableMethod.invoke(clazz.newInstance());
}
} catch (Exception e) {
//
} catch (Exception ignored) {
}
}
}
@ -128,15 +158,10 @@ public class JavaShell {
Class<?> clazz = shells.remove(shell);
try {
if (clazz.newInstance() instanceof Listener) {
for (RegisteredListener listener : HandlerList.getRegisteredListeners(Main.getInst())) {
if (listener.getListener().getClass().getName().equals(clazz.getName())) {
HandlerList.unregisterAll(listener.getListener());
}
}
HandlerList.getRegisteredListeners(Main.getInst()).stream().filter(listener -> listener.getListener().getClass().getName().equals(clazz.getName())).map(RegisteredListener::getListener).forEach(HandlerList::unregisterAll);
MsgUtils.send("已为脚本 &f" + shell + " &7注销监听器");
}
} catch (Exception e) {
//
} catch (Exception ignored) {
}
}
@ -189,13 +214,6 @@ public class JavaShell {
}
private static void loadLibrary() {
for (File jar : libFolder.listFiles()) {
try {
TDependencyLoader.addToPath(Main.getInst(), jar);
MsgUtils.send("成功载入 &f" + jar.getName() + " &7到运行库");
} catch (Exception e) {
//
}
}
Arrays.stream(Objects.requireNonNull(libFolder.listFiles())).forEach(jar -> TDependencyLoader.addToPath(Main.getInst(), jar));
}
}

View File

@ -10,52 +10,49 @@ public class CDL {
c = x.next();
} while (c == ' ' || c == '\t');
switch (c) {
case 0:
return null;
case '"':
case '\'':
q = c;
sb = new StringBuffer();
for (;;) {
c = x.next();
if (c == q) {
break;
case 0:
return null;
case '"':
case '\'':
q = c;
sb = new StringBuffer();
for (; ; ) {
c = x.next();
if (c == q) {
break;
}
if (c == 0 || c == '\n' || c == '\r') {
throw x.syntaxError("Missing close quote '" + q + "'.");
}
sb.append(c);
}
if (c == 0 || c == '\n' || c == '\r') {
throw x.syntaxError("Missing close quote '" + q + "'.");
}
sb.append(c);
}
return sb.toString();
case ',':
x.back();
return "";
default:
x.back();
return x.nextTo(',');
return sb.toString();
case ',':
x.back();
return "";
default:
x.back();
return x.nextTo(',');
}
}
public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException {
JSONArray ja = new JSONArray();
for (;;) {
for (; ; ) {
String value = getValue(x);
char c = x.next();
if (value == null ||
if (value == null ||
(ja.length() == 0 && value.length() == 0 && c != ',')) {
return null;
}
ja.put(value);
for (;;) {
if (c == ',') {
break;
}
while (c != ',') {
if (c != ' ') {
if (c == '\n' || c == '\r' || c == 0) {
return ja;
}
throw x.syntaxError("Bad character '" + c + "' (" +
(int)c + ").");
(int) c + ").");
}
c = x.next();
}
@ -65,7 +62,7 @@ public class CDL {
public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x)
throws JSONException {
JSONArray ja = rowToJSONArray(x);
return ja != null ? ja.toJSONObject(names) : null;
return ja != null ? ja.toJSONObject(names) : null;
}
public static String rowToString(JSONArray ja) {
@ -77,8 +74,8 @@ public class CDL {
Object object = ja.opt(i);
if (object != null) {
String string = object.toString();
if (string.length() > 0 && (string.indexOf(',') >= 0 ||
string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 ||
if (string.length() > 0 && (string.indexOf(',') >= 0 ||
string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 ||
string.indexOf(0) >= 0 || string.charAt(0) == '"')) {
sb.append('"');
int length = string.length();
@ -117,7 +114,7 @@ public class CDL {
return null;
}
JSONArray ja = new JSONArray();
for (;;) {
for (; ; ) {
JSONObject jo = rowToJSONObject(names, x);
if (jo == null) {
break;

View File

@ -3,16 +3,16 @@ package me.skymc.taboolib.json;
public class Cookie {
public static String escape(String string) {
char c;
String s = string.trim();
char c;
String s = string.trim();
StringBuilder sb = new StringBuilder();
int length = s.length();
int length = s.length();
for (int i = 0; i < length; i += 1) {
c = s.charAt(i);
if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') {
sb.append('%');
sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16));
sb.append(Character.forDigit((char)(c & 0x0f), 16));
sb.append(Character.forDigit((char) ((c >>> 4) & 0x0f), 16));
sb.append(Character.forDigit((char) (c & 0x0f), 16));
} else {
sb.append(c);
}
@ -21,9 +21,9 @@ public class Cookie {
}
public static JSONObject toJSONObject(String string) throws JSONException {
String name;
JSONObject jo = new JSONObject();
Object value;
String name;
JSONObject jo = new JSONObject();
Object value;
JSONTokener x = new JSONTokener(string);
jo.put("name", x.nextTo('='));
x.next('=');
@ -81,7 +81,7 @@ public class Cookie {
int d = JSONTokener.dehexchar(string.charAt(i + 1));
int e = JSONTokener.dehexchar(string.charAt(i + 2));
if (d >= 0 && e >= 0) {
c = (char)(d * 16 + e);
c = (char) (d * 16 + e);
i += 2;
}
}

View File

@ -17,10 +17,10 @@ public class CookieList {
}
@SuppressWarnings("rawtypes")
public static String toString(JSONObject jo) throws JSONException {
boolean b = false;
Iterator keys = jo.keys();
String string;
public static String toString(JSONObject jo) throws JSONException {
boolean b = false;
Iterator keys = jo.keys();
String string;
StringBuilder sb = new StringBuilder();
while (keys.hasNext()) {
string = keys.next().toString();

View File

@ -7,9 +7,9 @@ public class HTTP {
public static final String CRLF = "\r\n";
public static JSONObject toJSONObject(String string) throws JSONException {
JSONObject jo = new JSONObject();
HTTPTokener x = new HTTPTokener(string);
String token;
JSONObject jo = new JSONObject();
HTTPTokener x = new HTTPTokener(string);
String token;
token = x.nextToken();
if (token.toUpperCase().startsWith("HTTP")) {
@ -32,9 +32,9 @@ public class HTTP {
}
@SuppressWarnings("rawtypes")
public static String toString(JSONObject jo) throws JSONException {
Iterator keys = jo.keys();
String string;
public static String toString(JSONObject jo) throws JSONException {
Iterator keys = jo.keys();
String string;
StringBuilder sb = new StringBuilder();
if (jo.has("Status-Code") && jo.has("Reason-Phrase")) {
sb.append(jo.getString("HTTP-Version"));
@ -56,9 +56,9 @@ public class HTTP {
sb.append(CRLF);
while (keys.hasNext()) {
string = keys.next().toString();
if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) &&
if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) &&
!"Reason-Phrase".equals(string) && !"Method".equals(string) &&
!"Request-URI".equals(string) && !jo.isNull(string)) {
!"Request-URI".equals(string) && !jo.isNull(string)) {
sb.append(string);
sb.append(": ");
sb.append(jo.getString(string));

View File

@ -15,7 +15,7 @@ public class HTTPTokener extends JSONTokener {
} while (Character.isWhitespace(c));
if (c == '"' || c == '\'') {
q = c;
for (;;) {
for (; ; ) {
c = next();
if (c < ' ') {
throw syntaxError("Unterminated string.");
@ -25,8 +25,8 @@ public class HTTPTokener extends JSONTokener {
}
sb.append(c);
}
}
for (;;) {
}
for (; ; ) {
if (c == 0 || Character.isWhitespace(c)) {
return sb.toString();
}

View File

@ -24,7 +24,7 @@ public class JSONArray {
}
if (x.nextClean() != ']') {
x.back();
for (;;) {
for (; ; ) {
if (x.nextClean() == ',') {
x.back();
this.myArrayList.add(JSONObject.NULL);
@ -33,17 +33,17 @@ public class JSONArray {
this.myArrayList.add(x.nextValue());
}
switch (x.nextClean()) {
case ';':
case ',':
if (x.nextClean() == ']') {
case ';':
case ',':
if (x.nextClean() == ']') {
return;
}
x.back();
break;
case ']':
return;
}
x.back();
break;
case ']':
return;
default:
throw x.syntaxError("Expected a ',' or ']'");
default:
throw x.syntaxError("Expected a ',' or ']'");
}
}
}
@ -86,11 +86,11 @@ public class JSONArray {
Object object = this.get(index);
if (object.equals(Boolean.FALSE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("false"))) {
((String) object).equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("true"))) {
((String) object).equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONArray[" + index + "] is not a boolean.");
@ -100,11 +100,11 @@ public class JSONArray {
Object object = this.get(index);
try {
return object instanceof Number
? ((Number)object).doubleValue()
: Double.parseDouble((String)object);
? ((Number) object).doubleValue()
: Double.parseDouble((String) object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index +
"] is not a number.");
"] is not a number.");
}
}
@ -112,18 +112,18 @@ public class JSONArray {
Object object = this.get(index);
try {
return object instanceof Number
? ((Number)object).intValue()
: Integer.parseInt((String)object);
? ((Number) object).intValue()
: Integer.parseInt((String) object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index +
"] is not a number.");
"] is not a number.");
}
}
public JSONArray getJSONArray(int index) throws JSONException {
Object object = this.get(index);
if (object instanceof JSONArray) {
return (JSONArray)object;
return (JSONArray) object;
}
throw new JSONException("JSONArray[" + index +
"] is not a JSONArray.");
@ -132,28 +132,28 @@ public class JSONArray {
public JSONObject getJSONObject(int index) throws JSONException {
Object object = this.get(index);
if (object instanceof JSONObject) {
return (JSONObject)object;
return (JSONObject) object;
}
throw new JSONException("JSONArray[" + index +
"] is not a JSONObject.");
"] is not a JSONObject.");
}
public long getLong(int index) throws JSONException {
Object object = this.get(index);
try {
return object instanceof Number
? ((Number)object).longValue()
: Long.parseLong((String)object);
? ((Number) object).longValue()
: Long.parseLong((String) object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index +
"] is not a number.");
"] is not a number.");
}
}
public String getString(int index) throws JSONException {
Object object = this.get(index);
if (object instanceof String) {
return (String)object;
return (String) object;
}
throw new JSONException("JSONArray[" + index + "] not a string.");
}
@ -181,15 +181,15 @@ public class JSONArray {
public Object opt(int index) {
return (index < 0 || index >= this.length())
? null
: this.myArrayList.get(index);
? null
: this.myArrayList.get(index);
}
public boolean optBoolean(int index) {
public boolean optBoolean(int index) {
return this.optBoolean(index, false);
}
public boolean optBoolean(int index, boolean defaultValue) {
public boolean optBoolean(int index, boolean defaultValue) {
try {
return this.getBoolean(index);
} catch (Exception e) {
@ -223,12 +223,12 @@ public class JSONArray {
public JSONArray optJSONArray(int index) {
Object o = this.opt(index);
return o instanceof JSONArray ? (JSONArray)o : null;
return o instanceof JSONArray ? (JSONArray) o : null;
}
public JSONObject optJSONObject(int index) {
Object o = this.opt(index);
return o instanceof JSONObject ? (JSONObject)o : null;
return o instanceof JSONObject ? (JSONObject) o : null;
}
public long optLong(int index) {
@ -250,7 +250,7 @@ public class JSONArray {
public String optString(int index, String defaultValue) {
Object object = this.opt(index);
return JSONObject.NULL.equals(object)
? defaultValue : object
? defaultValue : object
.toString();
}
@ -355,7 +355,7 @@ public class JSONArray {
}
@Override
public String toString() {
public String toString() {
try {
return '[' + this.join(",") + ']';
} catch (Exception e) {
@ -407,7 +407,7 @@ public class JSONArray {
writer.write(']');
return writer;
} catch (IOException e) {
throw new JSONException(e);
throw new JSONException(e);
}
}
}

View File

@ -5,19 +5,15 @@ import java.util.Iterator;
@SuppressWarnings({"rawtypes"})
public class JSONML {
private static Object parse(
XMLTokener x,
boolean arrayForm,
JSONArray ja
) throws JSONException {
String attribute;
char c;
String closeTag = null;
int i;
JSONArray newja = null;
JSONObject newjo = null;
Object token;
String tagName = null;
private static Object parse(XMLTokener x, boolean arrayForm, JSONArray ja) throws JSONException {
String attribute;
char c;
String closeTag;
int i;
JSONArray newja;
JSONObject newjo;
Object token;
String tagName;
while (true) {
if (!x.more()) {
@ -32,7 +28,7 @@ public class JSONML {
if (!(token instanceof String)) {
throw new JSONException(
"Expected a closing name instead of '" +
token + "'.");
token + "'.");
}
if (x.nextToken() != XML.GT) {
throw x.syntaxError("Misshaped close tag");
@ -81,7 +77,7 @@ public class JSONML {
if (!(token instanceof String)) {
throw x.syntaxError("Bad tagName '" + token + "'.");
}
tagName = (String)token;
tagName = (String) token;
newja = new JSONArray();
newjo = new JSONObject();
if (arrayForm) {
@ -96,7 +92,7 @@ public class JSONML {
}
}
token = null;
for (;;) {
for (; ; ) {
if (token == null) {
token = x.nextToken();
}
@ -106,7 +102,7 @@ public class JSONML {
if (!(token instanceof String)) {
break;
}
attribute = (String)token;
attribute = (String) token;
if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) {
throw x.syntaxError("Reserved attribute.");
}
@ -116,7 +112,7 @@ public class JSONML {
if (!(token instanceof String)) {
throw x.syntaxError("Missing value");
}
newjo.accumulate(attribute, XML.stringToValue((String)token));
newjo.accumulate(attribute, XML.stringToValue((String) token));
token = null;
} else {
newjo.accumulate(attribute, "");
@ -140,13 +136,12 @@ public class JSONML {
if (token != XML.GT) {
throw x.syntaxError("Misshaped tag");
}
closeTag = (String)parse(x, arrayForm, newja);
closeTag = (String) parse(x, arrayForm, newja);
if (closeTag != null) {
if (!closeTag.equals(tagName)) {
throw x.syntaxError("Mismatched '" + tagName +
"' and '" + closeTag + "'");
}
tagName = null;
if (!arrayForm && newja.length() > 0) {
newjo.put("childNodes", newja);
}
@ -163,8 +158,8 @@ public class JSONML {
} else {
if (ja != null) {
ja.put(token instanceof String
? XML.stringToValue((String)token)
: token);
? XML.stringToValue((String) token)
: token);
}
}
}
@ -175,11 +170,11 @@ public class JSONML {
}
public static JSONArray toJSONArray(XMLTokener x) throws JSONException {
return (JSONArray)parse(x, true, null);
return (JSONArray) parse(x, true, null);
}
public static JSONObject toJSONObject(XMLTokener x) throws JSONException {
return (JSONObject)parse(x, false, null);
return (JSONObject) parse(x, false, null);
}
public static JSONObject toJSONObject(String string) throws JSONException {
@ -187,15 +182,15 @@ public class JSONML {
}
public static String toString(JSONArray ja) throws JSONException {
int i;
JSONObject jo;
String key;
Iterator keys;
int length;
Object object;
int i;
JSONObject jo;
String key;
Iterator keys;
int length;
Object object;
StringBuilder sb = new StringBuilder();
String tagName;
String value;
String tagName;
String value;
tagName = ja.getString(0);
XML.noSpace(tagName);
tagName = XML.escape(tagName);
@ -205,7 +200,7 @@ public class JSONML {
object = ja.opt(1);
if (object instanceof JSONObject) {
i = 2;
jo = (JSONObject)object;
jo = (JSONObject) object;
keys = jo.keys();
while (keys.hasNext()) {
key = keys.next().toString();
@ -236,9 +231,9 @@ public class JSONML {
if (object instanceof String) {
sb.append(XML.escape(object.toString()));
} else if (object instanceof JSONObject) {
sb.append(toString((JSONObject)object));
sb.append(toString((JSONObject) object));
} else if (object instanceof JSONArray) {
sb.append(toString((JSONArray)object));
sb.append(toString((JSONArray) object));
}
}
} while (i < length);
@ -252,14 +247,14 @@ public class JSONML {
public static String toString(JSONObject jo) throws JSONException {
StringBuilder sb = new StringBuilder();
int i;
JSONArray ja;
String key;
Iterator keys;
int length;
Object object;
String tagName;
String value;
int i;
JSONArray ja;
String key;
Iterator keys;
int length;
Object object;
String tagName;
String value;
tagName = jo.optString("tagName");
if (tagName == null) {
return XML.escape(jo.toString());
@ -297,9 +292,9 @@ public class JSONML {
if (object instanceof String) {
sb.append(XML.escape(object.toString()));
} else if (object instanceof JSONObject) {
sb.append(toString((JSONObject)object));
sb.append(toString((JSONObject) object));
} else if (object instanceof JSONArray) {
sb.append(toString((JSONArray)object));
sb.append(toString((JSONArray) object));
} else {
sb.append(object.toString());
}

View File

@ -6,31 +6,25 @@ import java.io.Writer;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.*;
@SuppressWarnings({"rawtypes", "unchecked"})
public class JSONObject {
private static final class Null {
private static final class Null {
@Override
protected final Object clone() {
protected final Object clone() {
return this;
}
@Override
public boolean equals(Object object) {
public boolean equals(Object object) {
return object == null || object == this;
}
@Override
public String toString() {
public String toString() {
return "null";
}
}
@ -61,16 +55,16 @@ public class JSONObject {
if (x.nextClean() != '{') {
throw x.syntaxError("A JSONObject text must begin with '{'");
}
for (;;) {
for (; ; ) {
c = x.nextClean();
switch (c) {
case 0:
throw x.syntaxError("A JSONObject text must end with '}'");
case '}':
return;
default:
x.back();
key = x.nextValue().toString();
case 0:
throw x.syntaxError("A JSONObject text must end with '}'");
case '}':
return;
default:
x.back();
key = x.nextValue().toString();
}
c = x.nextClean();
if (c == '=') {
@ -82,17 +76,17 @@ public class JSONObject {
}
this.putOnce(key, x.nextValue());
switch (x.nextClean()) {
case ';':
case ',':
if (x.nextClean() == '}') {
case ';':
case ',':
if (x.nextClean() == '}') {
return;
}
x.back();
break;
case '}':
return;
}
x.back();
break;
case '}':
return;
default:
throw x.syntaxError("Expected a ',' or '}'");
default:
throw x.syntaxError("Expected a ',' or '}'");
}
}
}
@ -138,7 +132,7 @@ public class JSONObject {
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
if (key instanceof String) {
String[] path = ((String)key).split("\\.");
String[] path = ((String) key).split("\\.");
int last = path.length - 1;
JSONObject target = this;
for (int i = 0; i < last; i += 1) {
@ -150,15 +144,12 @@ public class JSONObject {
}
target = nextTarget;
}
target.put(path[last], bundle.getString((String)key));
target.put(path[last], bundle.getString((String) key));
}
}
}
public JSONObject accumulate(
String key,
Object value
) throws JSONException {
public void accumulate(String key, Object value) throws JSONException {
testValidity(value);
Object object = this.opt(key);
if (object == null) {
@ -166,20 +157,19 @@ public class JSONObject {
? new JSONArray().put(value)
: value);
} else if (object instanceof JSONArray) {
((JSONArray)object).put(value);
((JSONArray) object).put(value);
} else {
this.put(key, new JSONArray().put(object).put(value));
}
return this;
}
public JSONObject append(String key, Object value) throws JSONException {
testValidity(value);
Object object = this.opt(key);
if (object == null) {
this.put(key, new JSONArray().put(value));
} else if (object instanceof JSONArray) {
this.put(key, ((JSONArray)object).put(value));
this.put(key, ((JSONArray) object).put(value));
} else {
throw new JSONException("JSONObject[" + key +
"] is not a JSONArray.");
@ -220,11 +210,11 @@ public class JSONObject {
Object object = this.get(key);
if (object.equals(Boolean.FALSE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("false"))) {
((String) object).equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("true"))) {
((String) object).equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONObject[" + quote(key) +
@ -235,11 +225,11 @@ public class JSONObject {
Object object = this.get(key);
try {
return object instanceof Number
? ((Number)object).doubleValue()
: Double.parseDouble((String)object);
? ((Number) object).doubleValue()
: Double.parseDouble((String) object);
} catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key) +
"] is not a number.");
"] is not a number.");
}
}
@ -247,18 +237,18 @@ public class JSONObject {
Object object = this.get(key);
try {
return object instanceof Number
? ((Number)object).intValue()
: Integer.parseInt((String)object);
? ((Number) object).intValue()
: Integer.parseInt((String) object);
} catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key) +
"] is not an int.");
"] is not an int.");
}
}
public JSONArray getJSONArray(String key) throws JSONException {
Object object = this.get(key);
if (object instanceof JSONArray) {
return (JSONArray)object;
return (JSONArray) object;
}
throw new JSONException("JSONObject[" + quote(key) +
"] is not a JSONArray.");
@ -267,7 +257,7 @@ public class JSONObject {
public JSONObject getJSONObject(String key) throws JSONException {
Object object = this.get(key);
if (object instanceof JSONObject) {
return (JSONObject)object;
return (JSONObject) object;
}
throw new JSONException("JSONObject[" + quote(key) +
"] is not a JSONObject.");
@ -277,11 +267,11 @@ public class JSONObject {
Object object = this.get(key);
try {
return object instanceof Number
? ((Number)object).longValue()
: Long.parseLong((String)object);
? ((Number) object).longValue()
: Long.parseLong((String) object);
} catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key) +
"] is not a long.");
"] is not a long.");
}
}
@ -294,7 +284,7 @@ public class JSONObject {
String[] names = new String[length];
int i = 0;
while (iterator.hasNext()) {
names[i] = (String)iterator.next();
names[i] = (String) iterator.next();
i += 1;
}
return names;
@ -320,10 +310,10 @@ public class JSONObject {
public String getString(String key) throws JSONException {
Object object = this.get(key);
if (object instanceof String) {
return (String)object;
return (String) object;
}
throw new JSONException("JSONObject[" + quote(key) +
"] not a string.");
"] not a string.");
}
public boolean has(String key) {
@ -381,7 +371,7 @@ public class JSONObject {
public JSONArray names() {
JSONArray ja = new JSONArray();
Iterator keys = this.keys();
Iterator keys = this.keys();
while (keys.hasNext()) {
ja.put(keys.next());
}
@ -449,12 +439,12 @@ public class JSONObject {
public JSONArray optJSONArray(String key) {
Object o = this.opt(key);
return o instanceof JSONArray ? (JSONArray)o : null;
return o instanceof JSONArray ? (JSONArray) o : null;
}
public JSONObject optJSONObject(String key) {
Object object = this.opt(key);
return object instanceof JSONObject ? (JSONObject)object : null;
return object instanceof JSONObject ? (JSONObject) object : null;
}
public long optLong(String key) {
@ -489,7 +479,7 @@ public class JSONObject {
} catch (Exception e) {
throw new JSONException(e);
}
if (object instanceof String) {
if (object != null) {
return (String) object;
}
throw new JSONException("Bad value from toJSONString: " + object);
@ -601,53 +591,52 @@ public class JSONObject {
b = c;
c = string.charAt(i);
switch (c) {
case '\\':
case '"':
w.write('\\');
w.write(c);
break;
case '/':
if (b == '<') {
case '\\':
case '"':
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);
}
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);
}
static Writer writeValue(Writer writer, Object value,
int indentFactor, int indent) throws JSONException, IOException {
if (value == null || value == 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);
@ -675,20 +664,19 @@ public class JSONObject {
} else {
quote(value.toString(), writer);
}
return writer;
}
public static void testValidity(Object o) throws JSONException {
if (o != null) {
if (o instanceof Double) {
if (((Double)o).isInfinite() || ((Double)o).isNaN()) {
if (((Double) o).isInfinite() || ((Double) o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
"JSON does not allow non-finite numbers.");
}
} else if (o instanceof Float) {
if (((Float)o).isInfinite() || ((Float)o).isNaN()) {
if (((Float) o).isInfinite() || ((Float) o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
"JSON does not allow non-finite numbers.");
}
}
}
@ -706,7 +694,7 @@ public class JSONObject {
}
@Override
public String toString() {
public String toString() {
try {
return this.toString(0);
} catch (Exception e) {
@ -727,48 +715,48 @@ public class JSONObject {
}
}
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;
}
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;
}
}
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 Writer write(Writer writer) throws JSONException {
public Writer write(Writer writer) throws JSONException {
return this.write(writer, 0, 0);
}
@ -880,5 +868,5 @@ public class JSONObject {
} catch (IOException exception) {
throw new JSONException(exception);
}
}
}
}

View File

@ -1,27 +1,22 @@
package me.skymc.taboolib.json;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.*;
public class JSONTokener {
private long character;
private long character;
private boolean eof;
private long index;
private long line;
private char previous;
private Reader reader;
private long index;
private long line;
private char previous;
private Reader reader;
private boolean usePrevious;
public JSONTokener(Reader reader) {
this.reader = reader.markSupported()
? reader
: new BufferedReader(reader);
? reader
: new BufferedReader(reader);
this.eof = false;
this.usePrevious = false;
this.previous = 0;
@ -114,26 +109,26 @@ public class JSONTokener {
return n;
}
public String next(int n) throws JSONException {
if (n == 0) {
return "";
}
public String next(int n) throws JSONException {
if (n == 0) {
return "";
}
char[] chars = new char[n];
int pos = 0;
char[] chars = new char[n];
int pos = 0;
while (pos < n) {
chars[pos] = this.next();
if (this.end()) {
throw this.syntaxError("Substring bounds error");
}
pos += 1;
}
return new String(chars);
}
while (pos < n) {
chars[pos] = this.next();
if (this.end()) {
throw this.syntaxError("Substring bounds error");
}
pos += 1;
}
return new String(chars);
}
public char nextClean() throws JSONException {
for (;;) {
for (; ; ) {
char c = this.next();
if (c == 0 || c > ' ') {
return c;
@ -144,56 +139,56 @@ public class JSONTokener {
public String nextString(char quote) throws JSONException {
char c;
StringBuilder sb = new StringBuilder();
for (;;) {
for (; ; ) {
c = this.next();
switch (c) {
case 0:
case '\n':
case '\r':
throw this.syntaxError("Unterminated string");
case '\\':
c = this.next();
switch (c) {
case 'b':
sb.append('\b');
break;
case 't':
sb.append('\t');
break;
case 'n':
sb.append('\n');
break;
case 'f':
sb.append('\f');
break;
case 'r':
sb.append('\r');
break;
case 'u':
sb.append((char)Integer.parseInt(this.next(4), 16));
break;
case '"':
case '\'':
case 0:
case '\n':
case '\r':
throw this.syntaxError("Unterminated string");
case '\\':
case '/':
sb.append(c);
c = this.next();
switch (c) {
case 'b':
sb.append('\b');
break;
case 't':
sb.append('\t');
break;
case 'n':
sb.append('\n');
break;
case 'f':
sb.append('\f');
break;
case 'r':
sb.append('\r');
break;
case 'u':
sb.append((char) Integer.parseInt(this.next(4), 16));
break;
case '"':
case '\'':
case '\\':
case '/':
sb.append(c);
break;
default:
throw this.syntaxError("Illegal escape.");
}
break;
default:
throw this.syntaxError("Illegal escape.");
}
break;
default:
if (c == quote) {
return sb.toString();
}
sb.append(c);
if (c == quote) {
return sb.toString();
}
sb.append(c);
}
}
}
public String nextTo(char delimiter) throws JSONException {
StringBuilder sb = new StringBuilder();
for (;;) {
for (; ; ) {
char c = this.next();
if (c == delimiter || c == 0 || c == '\n' || c == '\r') {
if (c != 0) {
@ -208,7 +203,7 @@ public class JSONTokener {
public String nextTo(String delimiters) throws JSONException {
char c;
StringBuilder sb = new StringBuilder();
for (;;) {
for (; ; ) {
c = this.next();
if (delimiters.indexOf(c) >= 0 || c == 0 ||
c == '\n' || c == '\r') {
@ -281,8 +276,8 @@ public class JSONTokener {
}
@Override
public String toString() {
public String toString() {
return " at " + this.index + " [character " + this.character + " line " +
this.line + "]";
this.line + "]";
}
}

View File

@ -4,7 +4,7 @@ import java.io.IOException;
import java.io.Writer;
public class JSONWriter {
private static final int maxdepth = 200;
private boolean comma;
@ -60,8 +60,8 @@ public class JSONWriter {
private JSONWriter end(char mode, char c) throws JSONException {
if (this.mode != mode) {
throw new JSONException(mode == 'a'
? "Misplaced endArray."
: "Misplaced endObject.");
? "Misplaced endArray."
: "Misplaced endObject.");
}
this.pop(mode);
try {
@ -127,10 +127,10 @@ public class JSONWriter {
}
this.top -= 1;
this.mode = this.top == 0
? 'd'
: this.stack[this.top - 1] == null
? 'a'
: 'k';
? 'd'
: this.stack[this.top - 1] == null
? 'a'
: 'k';
}
private void push(JSONObject jo) throws JSONException {

View File

@ -29,23 +29,23 @@ public class XML {
for (int i = 0, length = string.length(); i < length; i++) {
char c = string.charAt(i);
switch (c) {
case '&':
sb.append("&amp;");
break;
case '<':
sb.append("&lt;");
break;
case '>':
sb.append("&gt;");
break;
case '"':
sb.append("&quot;");
break;
case '\'':
sb.append("&apos;");
break;
default:
sb.append(c);
case '&':
sb.append("&amp;");
break;
case '<':
sb.append("&lt;");
break;
case '>':
sb.append("&gt;");
break;
case '"':
sb.append("&quot;");
break;
case '\'':
sb.append("&apos;");
break;
default:
sb.append(c);
}
}
return sb.toString();
@ -58,7 +58,7 @@ public class XML {
}
for (i = 0; i < length; i += 1) {
if (Character.isWhitespace(string.charAt(i))) {
throw new JSONException("'" + string +
throw new JSONException("'" + string +
"' contains a space character.");
}
}
@ -66,12 +66,12 @@ public class XML {
private static boolean parse(XMLTokener x, JSONObject context,
String name) throws JSONException {
char c;
int i;
char c;
int i;
JSONObject jsonobject = null;
String string;
String tagName;
Object token;
String string;
String tagName;
Object token;
token = x.nextToken();
if (token == BANG) {
c = x.next();
@ -113,7 +113,7 @@ public class XML {
token = x.nextToken();
if (name == null) {
throw x.syntaxError("Mismatched close tag " + token);
}
}
if (!token.equals(name)) {
throw x.syntaxError("Mismatched " + name + " and " + token);
}
@ -125,23 +125,23 @@ public class XML {
} else if (token instanceof Character) {
throw x.syntaxError("Misshaped tag");
} else {
tagName = (String)token;
tagName = (String) token;
token = null;
jsonobject = new JSONObject();
for (;;) {
for (; ; ) {
if (token == null) {
token = x.nextToken();
}
if (token instanceof String) {
string = (String)token;
string = (String) token;
token = x.nextToken();
if (token == EQ) {
token = x.nextToken();
if (!(token instanceof String)) {
throw x.syntaxError("Missing value");
}
jsonobject.accumulate(string,
XML.stringToValue((String)token));
jsonobject.accumulate(string,
XML.stringToValue((String) token));
token = null;
} else {
jsonobject.accumulate(string, "");
@ -157,7 +157,7 @@ public class XML {
}
return false;
} else if (token == GT) {
for (;;) {
for (; ; ) {
token = x.nextContent();
if (token == null) {
if (tagName != null) {
@ -165,9 +165,9 @@ public class XML {
}
return false;
} else if (token instanceof String) {
string = (String)token;
string = (String) token;
if (string.length() > 0) {
jsonobject.accumulate("content",
jsonobject.accumulate("content",
XML.stringToValue(string));
}
} else if (token == LT) {
@ -175,8 +175,8 @@ public class XML {
if (jsonobject.length() == 0) {
context.accumulate(tagName, "");
} else if (jsonobject.length() == 1 &&
jsonobject.opt("content") != null) {
context.accumulate(tagName,
jsonobject.opt("content") != null) {
context.accumulate(tagName,
jsonobject.opt("content"));
} else {
context.accumulate(tagName, jsonobject);
@ -230,7 +230,7 @@ public class XML {
}
}
}
} catch (Exception ignore) {
} catch (Exception ignore) {
}
return string;
}
@ -248,24 +248,23 @@ public class XML {
return toString(object, null);
}
public static String toString(Object object, String tagName)
throws JSONException {
public static String toString(Object object, String tagName) throws JSONException {
StringBuilder sb = new StringBuilder();
int i;
JSONArray ja;
JSONObject jo;
String key;
Iterator keys;
int length;
String string;
Object value;
int i;
JSONArray ja;
JSONObject jo;
String key;
Iterator keys;
int length;
String string;
Object value;
if (object instanceof JSONObject) {
if (tagName != null) {
sb.append('<');
sb.append(tagName);
sb.append('>');
}
jo = (JSONObject)object;
jo = (JSONObject) object;
keys = jo.keys();
while (keys.hasNext()) {
key = keys.next().toString();
@ -273,14 +272,9 @@ public class XML {
if (value == null) {
value = "";
}
if (value instanceof String) {
string = (String)value;
} else {
string = null;
}
if ("content".equals(key)) {
if (value instanceof JSONArray) {
ja = (JSONArray)value;
ja = (JSONArray) value;
length = ja.length();
for (i = 0; i < length; i += 1) {
if (i > 0) {
@ -292,7 +286,7 @@ public class XML {
sb.append(escape(value.toString()));
}
} else if (value instanceof JSONArray) {
ja = (JSONArray)value;
ja = (JSONArray) value;
length = ja.length();
for (i = 0; i < length; i += 1) {
value = ja.get(i);
@ -327,17 +321,17 @@ public class XML {
object = new JSONArray(object);
}
if (object instanceof JSONArray) {
ja = (JSONArray)object;
ja = (JSONArray) object;
length = ja.length();
for (i = 0; i < length; i += 1) {
sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName));
}
return sb.toString();
} else {
string = (object == null) ? "null" : escape(object.toString());
string = escape(object.toString());
return (tagName == null) ? "\"" + string + "\"" :
(string.length() == 0) ? "<" + tagName + "/>" :
"<" + tagName + ">" + string + "</" + tagName + ">";
(string.length() == 0) ? "<" + tagName + "/>" :
"<" + tagName + ">" + string + "</" + tagName + ">";
}
}
}

Some files were not shown because too many files have changed in this diff Show More