合并,删除 .idea 文件夹,数据库

This commit is contained in:
Izzel_Aliz 2018-05-07 18:16:43 +08:00
commit 3f4940c6b7
156 changed files with 9353 additions and 8998 deletions

View File

@ -12,7 +12,7 @@
<inspection_tool class="AlibabaEnumConstantsMustHaveComment" enabled="false" level="CRITICAL" enabled_by_default="false" /> <inspection_tool class="AlibabaEnumConstantsMustHaveComment" enabled="false" level="CRITICAL" enabled_by_default="false" />
<inspection_tool class="AlibabaThreadPoolCreation" enabled="false" level="BLOCKER" enabled_by_default="false" /> <inspection_tool class="AlibabaThreadPoolCreation" enabled="false" level="BLOCKER" enabled_by_default="false" />
<inspection_tool class="AlibabaUndefineMagicConstant" enabled="false" level="MAJOR" enabled_by_default="false" /> <inspection_tool class="AlibabaUndefineMagicConstant" enabled="false" level="MAJOR" enabled_by_default="false" />
<inspection_tool class="JavaDoc" enabled="true" level="WARNING" enabled_by_default="true"> <inspection_tool class="JavaDoc" enabled="false" level="WARNING" enabled_by_default="false">
<option name="TOP_LEVEL_CLASS_OPTIONS"> <option name="TOP_LEVEL_CLASS_OPTIONS">
<value> <value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" /> <option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
@ -48,5 +48,17 @@
<option name="processLiterals" value="true" /> <option name="processLiterals" value="true" />
<option name="processComments" value="true" /> <option name="processComments" value="true" />
</inspection_tool> </inspection_tool>
<inspection_tool class="unused" enabled="false" level="WARNING" enabled_by_default="false">
<option name="LOCAL_VARIABLE" value="true" />
<option name="FIELD" value="true" />
<option name="METHOD" value="true" />
<option name="CLASS" value="true" />
<option name="PARAMETER" value="true" />
<option name="REPORT_PARAMETER_FOR_PUBLIC_METHODS" value="true" />
<option name="ADD_MAINS_TO_ENTRIES" value="true" />
<option name="ADD_APPLET_TO_ENTRIES" value="true" />
<option name="ADD_SERVLET_TO_ENTRIES" value="true" />
<option name="ADD_NONJAVA_TO_ENTRIES" value="true" />
</inspection_tool>
</profile> </profile>
</component> </component>

View File

@ -1,13 +0,0 @@
<component name="libraryTable">
<library name="Maven: org.projectlombok:lombok:1.16.20">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/projectlombok/lombok/1.16.20/lombok-1.16.20.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/projectlombok/lombok/1.16.20/lombok-1.16.20-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/projectlombok/lombok/1.16.20/lombok-1.16.20-sources.jar!/" />
</SOURCES>
</library>
</component>

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

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

View File

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

View File

@ -12,7 +12,6 @@ import com.ilummc.tlib.logger.TLogger;
import com.ilummc.tlib.resources.TLocale; import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.resources.TLocaleLoader; import com.ilummc.tlib.resources.TLocaleLoader;
import com.ilummc.tlib.util.IO; import com.ilummc.tlib.util.IO;
import lombok.Getter;
import me.skymc.taboolib.Main; import me.skymc.taboolib.Main;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.InvalidConfigurationException;
@ -38,37 +37,34 @@ import java.nio.charset.Charset;
@Dependency(type = Dependency.Type.LIBRARY, maven = "com.h2database:h2:1.4.197") @Dependency(type = Dependency.Type.LIBRARY, maven = "com.h2database:h2:1.4.197")
public class TLib { public class TLib {
@Getter
private static TLib tLib; private static TLib tLib;
private static YamlConfiguration internalLanguage;
@Getter
private TLogger logger = new TLogger("§8[§3§lTabooLib§8][§r{1}§8] §f{2}", Main.getInst(), TLogger.FINE); private TLogger logger = new TLogger("§8[§3§lTabooLib§8][§r{1}§8] §f{2}", Main.getInst(), TLogger.FINE);
private TLibConfig config;
@Getter
private TLibConfig config = new TLibConfig();
@Getter
private TConfigWatcher configWatcher = new TConfigWatcher(); private TConfigWatcher configWatcher = new TConfigWatcher();
@Getter
private File libsFolder; private File libsFolder;
@Getter
private YamlConfiguration internalLang;
private TLib() { private TLib() {
libsFolder = new File(Main.getInst().getDataFolder(), "/libs"); libsFolder = new File(Main.getInst().getDataFolder(), "/libs");
if (!libsFolder.exists()) { if (!libsFolder.exists()) {
libsFolder.mkdirs(); libsFolder.mkdirs();
} }
try { try {
String yamlText = new String(IO.readFully(TLib.class.getResourceAsStream("/internalLang.yml")), Charset.forName("utf-8")); String yamlText = new String(IO.readFully(TLib.class.getResourceAsStream("/lang/internal.yml")), Charset.forName("utf-8"));
internalLang = new YamlConfiguration(); internalLanguage = new YamlConfiguration();
internalLang.loadFromString(yamlText); internalLanguage.loadFromString(yamlText);
} catch (IOException | InvalidConfigurationException ignored) { } catch (IOException | InvalidConfigurationException ignored) {
} }
} }
public static TLib getTLib() {
return tLib;
}
public static YamlConfiguration getInternalLanguage() {
return internalLanguage;
}
public static void init() { public static void init() {
tLib = new TLib(); tLib = new TLib();
@ -106,4 +102,20 @@ public class TLib {
TLocale.Logger.fatal("TLIB.INJECTION-FAILED"); 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

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

View File

@ -10,7 +10,7 @@ import com.ilummc.tlib.util.Ref;
@Target(ElementType.TYPE) @Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface Config { public @interface TConfig {
String name() default "config.yml"; String name() default "config.yml";

View File

@ -0,0 +1,11 @@
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;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TLocalePlugin {
}

View File

@ -1,16 +1,12 @@
package com.ilummc.tlib.config; package com.ilummc.tlib.config;
import com.ilummc.tlib.annotations.Config; import com.ilummc.tlib.annotations.TConfig;
import lombok.Getter;
import java.util.HashMap;
import java.util.Map;
/** /**
* @author sky * @author sky
* @since 2018-04-22 14:31:11 * @since 2018-04-22 14:31:11
*/ */
@Config(name = "tlib.yml", listenChanges = true, readOnly = false) @TConfig(name = "tlib.yml", listenChanges = true)
public class TLibConfig { public class TLibConfig {
@Getter @Getter

View File

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

View File

@ -3,14 +3,13 @@ package com.ilummc.tlib.inject;
import com.google.common.io.Files; import com.google.common.io.Files;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.ilummc.tlib.annotations.Config; import com.ilummc.tlib.annotations.TConfig;
import com.ilummc.tlib.resources.TLocale; import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.fileutils.ConfigUtils; import me.skymc.taboolib.fileutils.ConfigUtils;
import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.Validate;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -53,14 +52,13 @@ public class TConfigInjector {
public static Object loadConfig(Plugin plugin, Class<?> clazz) { public static Object loadConfig(Plugin plugin, Class<?> clazz) {
try { try {
Config config = clazz.getAnnotation(Config.class); TConfig config = clazz.getAnnotation(TConfig.class);
Validate.notNull(config); Validate.notNull(config);
File file = new File(plugin.getDataFolder(), config.name()); File file = new File(plugin.getDataFolder(), config.name());
if (!file.exists()) if (config.fromJar()) plugin.saveResource(config.name(), true); if (!file.exists()) if (config.fromJar()) plugin.saveResource(config.name(), true);
else saveConfig(plugin, clazz.newInstance()); else saveConfig(plugin, clazz.newInstance());
Gson gson = new GsonBuilder().disableHtmlEscaping().create(); Object obj = unserialize(plugin, clazz);
Object obj = gson.fromJson(gson.toJson(new Yaml().load(Files.toString(file, Charset.forName(config.charset())))), clazz); if (config.readOnly()) saveConfig(plugin, obj);
if (!config.readOnly()) saveConfig(plugin, obj);
return obj; return obj;
} catch (NullPointerException e) { } catch (NullPointerException e) {
TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-ANNOTATION", plugin.toString(), clazz.getSimpleName()); TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-ANNOTATION", plugin.toString(), clazz.getSimpleName());
@ -72,12 +70,12 @@ public class TConfigInjector {
public static void reloadConfig(Plugin plugin, Object object) { public static void reloadConfig(Plugin plugin, Object object) {
try { try {
Config config = object.getClass().getAnnotation(Config.class); TConfig config = object.getClass().getAnnotation(TConfig.class);
Validate.notNull(config); Validate.notNull(config);
File file = new File(plugin.getDataFolder(), config.name()); File file = new File(plugin.getDataFolder(), config.name());
Map<String, Object> map = ConfigUtils.confToMap(ConfigUtils.loadYaml(plugin, file)); Map<String, Object> map = ConfigUtils.confToMap(ConfigUtils.loadYaml(plugin, file));
Object obj = ConfigUtils.mapToObj(map, object); Object obj = ConfigUtils.mapToObj(map, object);
if (!config.readOnly()) saveConfig(plugin, obj); if (config.readOnly()) saveConfig(plugin, obj);
} catch (NullPointerException e) { } catch (NullPointerException e) {
TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-ANNOTATION", plugin.toString(), object.getClass().getSimpleName()); TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-ANNOTATION", plugin.toString(), object.getClass().getSimpleName());
} catch (Exception e) { } catch (Exception e) {
@ -87,7 +85,7 @@ public class TConfigInjector {
public static Object unserialize(Plugin plugin, Class<?> clazz) { public static Object unserialize(Plugin plugin, Class<?> clazz) {
try { try {
Config config = clazz.getAnnotation(Config.class); TConfig config = clazz.getAnnotation(TConfig.class);
Validate.notNull(config); Validate.notNull(config);
return ConfigUtils.confToObj( return ConfigUtils.confToObj(
ConfigUtils.mapToConf( ConfigUtils.mapToConf(
@ -108,7 +106,7 @@ public class TConfigInjector {
public static Map<String, Object> serialize(Plugin plugin, Object object) { public static Map<String, Object> serialize(Plugin plugin, Object object) {
try { try {
Config config = object.getClass().getAnnotation(Config.class); TConfig config = object.getClass().getAnnotation(TConfig.class);
Validate.notNull(config); Validate.notNull(config);
return ConfigUtils.objToMap(ConfigUtils.objToConf(object).getValues(false), config.excludeModifiers()); return ConfigUtils.objToMap(ConfigUtils.objToConf(object).getValues(false), config.excludeModifiers());
} catch (NullPointerException e) { } catch (NullPointerException e) {
@ -120,7 +118,7 @@ public class TConfigInjector {
} }
public static void saveConfig(Plugin plugin, Object object) throws IOException, NullPointerException { 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); Validate.notNull(config);
Gson gson = new GsonBuilder().disableHtmlEscaping().create(); Gson gson = new GsonBuilder().disableHtmlEscaping().create();
Map map = gson.fromJson(gson.toJson(object), HashMap.class); Map map = gson.fromJson(gson.toJson(object), HashMap.class);

View File

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

View File

@ -1,8 +1,6 @@
package com.ilummc.tlib.logger; package com.ilummc.tlib.logger;
import com.ilummc.tlib.util.Strings; import com.ilummc.tlib.util.Strings;
import lombok.Getter;
import lombok.Setter;
import me.skymc.taboolib.Main; import me.skymc.taboolib.Main;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; 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; 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); private static TLogger globalLogger = new TLogger("§8[§3§lTabooLib§8][§r{1}§8] §f{2}", Main.getInst(), TLogger.FINE);
@Getter
private final String pattern; private final String pattern;
@Getter
private Plugin plugin; private Plugin plugin;
@Getter
@Setter
private int level; 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) { public TLogger(String pattern, Plugin plugin, int level) {
this.pattern = pattern; this.pattern = pattern;
this.plugin = plugin; this.plugin = plugin;

View File

@ -10,6 +10,8 @@ import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;
public class TLocale { public class TLocale {
@ -17,25 +19,18 @@ public class TLocale {
throw new AssertionError(); throw new AssertionError();
} }
private static JavaPlugin getCallerPlugin(Class<?> callerClass) { static String asString(String path, Class<?> callerClass, String... args) {
try { return TLocaleLoader.asString(getCallerPlugin(callerClass), path, args);
Field pluginField = callerClass.getClassLoader().getClass().getDeclaredField("plugin"); }
pluginField.setAccessible(true);
return (JavaPlugin) pluginField.get(callerClass.getClassLoader()); static List<String> asStringList(String path, Class<?> callerClass, String... args) {
} catch (Exception ignored) { return TLocaleLoader.asStringList(getCallerPlugin(callerClass), path, args);
TLib.getTLib().getLogger().error("无效的语言文件发送形式: &4" + callerClass.getName());
}
return (JavaPlugin) Main.getInst();
} }
private static void sendTo(String path, CommandSender sender, String[] args, Class<?> callerClass) { private static void sendTo(String path, CommandSender sender, String[] args, Class<?> callerClass) {
TLocaleLoader.sendTo(getCallerPlugin(callerClass), path, sender, args); 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) { public static void sendToConsole(String path, String... args) {
Ref.getCallerClass(3).ifPresent(clazz -> sendTo(path, Bukkit.getConsoleSender(), args, clazz)); 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) { public static String asString(String path, String... args) {
try { try {
return asString(path, Ref.getCallerClass(3).get(), args); return asString(path, Ref.getCallerClassNotOptional(3), args);
} catch (Exception e) { } 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().getInternalLanguage().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("LOCALE-ERROR-REASON"), e.getMessage()));
return "§4<" + path + "§4>"; 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() { public static void reload() {
Ref.getCallerClass(3).ifPresent(clazz -> TLocaleLoader.load(getCallerPlugin(clazz), false)); 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 final class Logger extends TLocale {
public static void info(String path, String... args) { 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.google.common.collect.ImmutableList;
import com.ilummc.tlib.TLib; import com.ilummc.tlib.TLib;
import com.ilummc.tlib.logger.TLogger;
import com.ilummc.tlib.resources.type.TLocaleText; import com.ilummc.tlib.resources.type.TLocaleText;
import com.ilummc.tlib.util.Strings; import com.ilummc.tlib.util.Strings;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@ -22,13 +23,36 @@ import java.util.stream.Collectors;
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
class TLocaleInstance { class TLocaleInstance {
private final Map<String, List<TLocaleSendable>> map = new HashMap<>();
private final Plugin plugin; private final Plugin plugin;
private int updateNodes;
TLocaleInstance(Plugin plugin) { TLocaleInstance(Plugin plugin) {
this.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 { try {
map.getOrDefault(path, ImmutableList.of(TLocaleSendable.getEmpty(path))).forEach(sendable -> { map.getOrDefault(path, ImmutableList.of(TLocaleSendable.getEmpty(path))).forEach(sendable -> {
if (Bukkit.isPrimaryThread()) { if (Bukkit.isPrimaryThread()) {
@ -38,39 +62,39 @@ class TLocaleInstance {
} }
}); });
} catch (Exception | Error e) { } 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().getInternalLanguage().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("LOCALE-ERROR-REASON"), e.toString()));
e.printStackTrace(); 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); 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 -> { configuration.getKeys(true).forEach(s -> {
boolean isCover = false;
Object object = configuration.get(s); Object object = configuration.get(s);
if (object instanceof TLocaleSendable) { 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()) { } 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)) { } else if (!(object instanceof ConfigurationSection)) {
String str = String.valueOf(object); 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 -> { private static final Function<Object, TLocaleSendable> TO_SENDABLE = o -> {
if (o instanceof TLocaleSendable) { if (o instanceof TLocaleSendable) {
return ((TLocaleSendable) o); return ((TLocaleSendable) o);
@ -80,7 +104,4 @@ class TLocaleInstance {
return TLocaleText.of(String.valueOf(o)); 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; package com.ilummc.tlib.resources;
import com.ilummc.tlib.TLib; import com.ilummc.tlib.TLib;
import com.ilummc.tlib.resources.type.TLocaleActionBar; import com.ilummc.tlib.annotations.TLocalePlugin;
import com.ilummc.tlib.resources.type.TLocaleJson; import com.ilummc.tlib.logger.TLogger;
import com.ilummc.tlib.resources.type.TLocaleText; import com.ilummc.tlib.resources.type.*;
import com.ilummc.tlib.resources.type.TLocaleTitle; import com.ilummc.tlib.util.IO;
import com.ilummc.tlib.util.Strings; import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.Main; import me.skymc.taboolib.Main;
import me.skymc.taboolib.fileutils.ConfigUtils; import me.skymc.taboolib.fileutils.ConfigUtils;
import me.skymc.taboolib.other.NumberUtils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
@ -16,8 +17,9 @@ import org.bukkit.plugin.Plugin;
import java.io.File; import java.io.File;
import java.io.InputStream; import java.io.InputStream;
import java.nio.file.Files; import java.nio.charset.Charset;
import java.nio.file.StandardOpenOption; import java.util.Collections;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ -26,7 +28,15 @@ public class TLocaleLoader {
private static final Map<String, TLocaleInstance> map = new ConcurrentHashMap<>(); 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()) if (Bukkit.isPrimaryThread())
Optional.ofNullable(map.get(plugin.getName())).ifPresent(localeInstance -> localeInstance.sendTo(path, sender, args)); Optional.ofNullable(map.get(plugin.getName())).ifPresent(localeInstance -> localeInstance.sendTo(path, sender, args));
else synchronized (TLocaleLoader.class) { else synchronized (TLocaleLoader.class) {
@ -34,67 +44,121 @@ public class TLocaleLoader {
} }
} }
static String asString(Plugin plugin, String path, String... args) { public static String asString(Plugin plugin, String path, String... args) {
return map.get(plugin.getName()).asString(path, args); TLocaleInstance tLocaleInstance = map.get(plugin.getName());
} if (tLocaleInstance != null) {
return tLocaleInstance.asString(path, args);
public static void init() { } else {
ConfigurationSerialization.registerClass(TLocaleText.class, "TEXT"); return "";
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 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 org.bukkit.command.CommandSender;
import java.util.Collections;
import java.util.List;
public interface TLocaleSendable { public interface TLocaleSendable {
static TLocaleSendable getEmpty() {
return (sender, args) -> {
// Empty
};
}
static TLocaleSendable getEmpty(String path) { static TLocaleSendable getEmpty(String path) {
return new TLocaleSendable() { return new TLocaleSendable() {
@Override @Override
public void sendTo(CommandSender sender, String... args) { public void sendTo(CommandSender sender, String... args) {
sender.sendMessage("§4<" + path + "§4>"); sender.sendMessage("§4<" + path + "§4>");
@ -15,23 +25,21 @@ public interface TLocaleSendable {
public String asString(String... args) { public String asString(String... args) {
return "§4<" + path + "§4>"; return "§4<" + path + "§4>";
} }
};
}
static TLocaleSendable getEmpty() {
return new TLocaleSendable() {
@Override
public void sendTo(CommandSender sender, String... args) {
}
@Override @Override
public String asString(String... args) { public List<String> asStringList(String... args) {
return ""; return Collections.singletonList("§4<" + path + "§4>");
} }
}; };
} }
void sendTo(CommandSender sender, String... args); 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 { public class TLocaleActionBar implements TLocaleSendable, ConfigurationSerializable {
private final String text; private final String text;
private final boolean papi; private final boolean papi;
private TLocaleActionBar(String text, boolean papi) { private TLocaleActionBar(String text, boolean papi) {
@ -54,8 +53,9 @@ public class TLocaleActionBar implements TLocaleSendable, ConfigurationSerializa
public Map<String, Object> serialize() { public Map<String, Object> serialize() {
Map<String, Object> map = Maps.newHashMap(); Map<String, Object> map = Maps.newHashMap();
map.put("text", text); map.put("text", text);
if (papi) if (papi) {
map.put("papi", true); map.put("papi", true);
}
return map; return map;
} }

View File

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

View File

@ -0,0 +1,69 @@
package com.ilummc.tlib.resources.type;
import com.google.common.collect.Maps;
import com.ilummc.tlib.resources.TLocaleSendable;
import me.skymc.taboolib.sound.SoundPack;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.configuration.serialization.SerializableAs;
import org.bukkit.entity.Player;
import javax.annotation.concurrent.Immutable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @Author sky
* @Since 2018-05-06 14:35
*/
@Immutable
@SerializableAs("ACTION")
public class TLocaleSound implements TLocaleSendable, ConfigurationSerializable {
private final List<SoundPack> soundPacks;
public TLocaleSound(List<SoundPack> soundPacks) {
this.soundPacks = soundPacks;
}
@Override
public void sendTo(CommandSender sender, String... args) {
if (sender instanceof Player) {
soundPacks.forEach(x -> x.play((Player) sender));
}
}
@Override
public String asString(String... args) {
return toString();
}
@Override
public String toString() {
return "soundPacks=" + "TLocaleSound{" + soundPacks + '}';
}
@Override
public Map<String, Object> serialize() {
Map<String, Object> map = Maps.newHashMap();
if (soundPacks.size() == 1) {
map.put("sounds", soundPacks.get(0).toString());
} else if (soundPacks.size() > 1) {
map.put("sounds", soundPacks.stream().map(SoundPack::toString).collect(Collectors.toList()));
}
return map;
}
public static TLocaleSound valueOf(Map<String, Object> map) {
List<SoundPack> soundPacks = new ArrayList<>();
Object sounds = map.containsKey("sounds") ? map.get("sounds") : map.getOrDefault("sound", "");
if (sounds instanceof List) {
soundPacks = ((List<String>) sounds).stream().map(SoundPack::new).collect(Collectors.toList());
} else {
soundPacks.add(new SoundPack(sounds.toString()));
}
return new TLocaleSound(soundPacks);
}
}

View File

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

View File

@ -54,7 +54,7 @@ public class TLocaleTitle implements TLocaleSendable, ConfigurationSerializable
(int) map.getOrDefault("stay", 20), (int) map.getOrDefault("stay", 20),
(boolean) map.getOrDefault("papi", Main.getInst().getConfig().getBoolean("LOCALE.USE_PAPI", false))); (boolean) map.getOrDefault("papi", Main.getInst().getConfig().getBoolean("LOCALE.USE_PAPI", false)));
} catch (Exception e) { } 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; return title;
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,8 +1,5 @@
package me.skymc.taboolib.bookformatter.action; package me.skymc.taboolib.bookformatter.action;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.experimental.Accessors;
import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.ClickEvent;
/** /**
@ -13,12 +10,14 @@ public interface ClickAction {
/** /**
* Get the Chat-Component action * Get the Chat-Component action
*
* @return the Chat-Component action * @return the Chat-Component action
*/ */
ClickEvent.Action action(); ClickEvent.Action action();
/** /**
* The value paired to the action * The value paired to the action
*
* @return the value paired tot the action * @return the value paired tot the action
*/ */
String value(); 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 * 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 * @param command the command to be executed
* @return a new ClickAction * @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 * 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 * @param command the command to be suggested
* @return a new ClickAction * @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 * 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 * @param url the url to be opened
* @return a new ClickAction * @return a new ClickAction
*/ */
static ClickAction openUrl(String url) { 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); return new SimpleClickAction(ClickEvent.Action.OPEN_URL, url);
else else
throw new IllegalArgumentException("Invalid url: \"" + url + "\", it should start with http:// or https://"); 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 * 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 * @param page the new page
* @return a new ClickAction * @return a new ClickAction
*/ */
@ -63,11 +66,32 @@ public interface ClickAction {
return new SimpleClickAction(ClickEvent.Action.CHANGE_PAGE, Integer.toString(page)); return new SimpleClickAction(ClickEvent.Action.CHANGE_PAGE, Integer.toString(page));
} }
@Getter
@Accessors(fluent = true)
@RequiredArgsConstructor
class SimpleClickAction implements ClickAction { class SimpleClickAction implements ClickAction {
private final ClickEvent.Action action; private final ClickEvent.Action action;
private final String value; 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; 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.BookAchievement;
import me.skymc.taboolib.bookformatter.BookReflection; import me.skymc.taboolib.bookformatter.BookReflection;
import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.HoverEvent; import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent; 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 * @author sky
@ -23,11 +20,14 @@ public interface HoverAction {
/** /**
* Get the Chat-Component action * Get the Chat-Component action
*
* @return the Chat-Component action * @return the Chat-Component action
*/ */
HoverEvent.Action action(); HoverEvent.Action action();
/** /**
* The value paired to the action * The value paired to the action
*
* @return the value paired tot the action * @return the value paired tot the action
*/ */
BaseComponent[] value(); 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 * Creates a show_text action: when the component is hovered the text used as parameter will be displayed
*
* @param text the text to display * @param text the text to display
* @return a new HoverAction instance * @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 * Creates a show_text action: when the component is hovered the text used as parameter will be displayed
*
* @param text the text to display * @param text the text to display
* @return a new HoverAction instance * @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 * 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 * @param item a component array representing item to display
* @return a new HoverAction instance * @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 * Creates a show_item action: when the component is hovered some item information will be displayed
*
* @param item the item to display * @param item the item to display
* @return a new HoverAction instance * @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 * 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 * @param entity a component array representing the item to display
* @return a new HoverAction instance * @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 * Creates a show_entity action: when the component is hovered some entity information will be displayed
*
* @param uuid the entity's UniqueId * @param uuid the entity's UniqueId
* @param type the entity's type * @param type the entity's type
* @param name the entity's name * @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 * Creates a show_entity action: when the component is hovered some entity information will be displayed
*
* @param entity the item to display * @param entity the item to display
* @return a new HoverAction instance * @return a new HoverAction instance
*/ */
static HoverAction showEntity(Entity entity) { static HoverAction showEntity(Entity entity) {
return showEntity(entity.getUniqueId(), entity.getType().getName(), entity.getName()); 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 * 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 * @param achievementId the id of the achievement to display
* @return a new HoverAction instance * @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 * Creates a show_achievement action: when the component is hovered the achievement information will be displayed
*
* @param achievement the achievement to display * @param achievement the achievement to display
* @return a new HoverAction instance * @return a new HoverAction instance
*/ */
static HoverAction showAchievement(Achievement achievement) { static HoverAction showAchievement(Achievement achievement) {
return showAchievement(BookAchievement.toId(achievement)); return showAchievement(BookAchievement.toId(achievement));
} }
/** /**
* Creates a show_achievement action: when the component is hovered the statistic information will be displayed * 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 * @param statisticId the id of the statistic to display
* @return a new HoverAction instance * @return a new HoverAction instance
*/ */
@ -129,8 +139,6 @@ public interface HoverAction {
return new SimpleHoverAction(HoverEvent.Action.SHOW_ACHIEVEMENT, new TextComponent("statistic." + statisticId)); return new SimpleHoverAction(HoverEvent.Action.SHOW_ACHIEVEMENT, new TextComponent("statistic." + statisticId));
} }
@Getter
@Accessors(fluent = true)
class SimpleHoverAction implements HoverAction { class SimpleHoverAction implements HoverAction {
private final HoverEvent.Action action; private final HoverEvent.Action action;
private final BaseComponent[] value; private final BaseComponent[] value;
@ -139,5 +147,23 @@ public interface HoverAction {
this.action = action; this.action = action;
this.value = value; 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; 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.ClickAction;
import me.skymc.taboolib.bookformatter.action.HoverAction; import me.skymc.taboolib.bookformatter.action.HoverAction;
import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.BaseComponent;
@ -14,31 +11,54 @@ import net.md_5.bungee.api.chat.TextComponent;
* @author sky * @author sky
* @since 2018-03-08 22:37:27 * @since 2018-03-08 22:37:27
*/ */
@Setter
@Getter
@Accessors(fluent = true, chain = true)
public class TextBuilder { public class TextBuilder {
private String text = ""; private String text = "";
private ClickAction onClick = null; private ClickAction onClick = null;
private HoverAction onHover = 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) { public TextBuilder(String text) {
this.text = text; this.text = text;
} }
/** /**
* Creates the component representing the built text * Creates the component representing the built text
*
* @return the component representing the built text * @return the component representing the built text
*/ */
public BaseComponent build() { public BaseComponent build() {
TextComponent res = new TextComponent(text); TextComponent res = new TextComponent(text);
if(onClick != null) { if (onClick != null) {
res.setClickEvent(new ClickEvent(onClick.action(), onClick.value())); res.setClickEvent(new ClickEvent(onClick.action(), onClick.value()));
} }
if(onHover != null) { if (onHover != null) {
res.setHoverEvent(new HoverEvent(onHover.action(), onHover.value())); res.setHoverEvent(new HoverEvent(onHover.action(), onHover.value()));
} }
return res; return res;
@ -46,10 +66,11 @@ public class TextBuilder {
/** /**
* Creates a new TextBuilder with the parameter as his initial text * Creates a new TextBuilder with the parameter as his initial text
*
* @param text initial text * @param text initial text
* @return a new TextBuilder with the parameter as his initial text * @return a new TextBuilder with the parameter as his initial text
*/ */
public static TextBuilder of(String 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; package me.skymc.taboolib.commands;
import org.bukkit.command.Command; import com.ilummc.tlib.resources.TLocale;
import org.bukkit.command.CommandExecutor; import me.skymc.taboolib.commands.sub.*;
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 me.skymc.taboolib.commands.sub.cycle.CycleCommand; import me.skymc.taboolib.commands.sub.cycle.CycleCommand;
import me.skymc.taboolib.commands.sub.itemlist.ItemListCommand; import me.skymc.taboolib.commands.sub.itemlist.ItemListCommand;
import me.skymc.taboolib.commands.sub.shell.ShellCommand; import me.skymc.taboolib.commands.sub.shell.ShellCommand;
import me.skymc.taboolib.commands.sub.sounds.SoundsCommand; import me.skymc.taboolib.commands.sub.sounds.SoundsCommand;
import me.skymc.taboolib.inventory.ItemUtils; 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 class MainCommands implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (args.length == 0 || args[0].equalsIgnoreCase("help")) { @Override
new HelpCommand(sender, args); public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
} if (args.length == 0 || args[0].equalsIgnoreCase("help")) {
else if (args[0].equalsIgnoreCase("itemreload") || args[0].equalsIgnoreCase("ireload")) { TLocale.sendTo(sender, "COMMANDS.TABOOLIB.HELP");
ItemUtils.reloadItemCache(); } else if (args[0].equalsIgnoreCase("save")) {
ItemUtils.reloadItemName(); new SaveCommand(sender, args);
MsgUtils.send(sender, "重载成功"); } else if (args[0].equalsIgnoreCase("enchants")) {
} new EnchantCommand(sender, args);
else if (args[0].equalsIgnoreCase("save")) { } else if (args[0].equalsIgnoreCase("potions")) {
new SaveCommand(sender, args); new PotionCommand(sender, args);
} } else if (args[0].equalsIgnoreCase("flags")) {
else if (args[0].equalsIgnoreCase("enchants")) { new FlagCommand(sender, args);
new EnchantCommand(sender, args); } else if (args[0].equalsIgnoreCase("attributes")) {
} new AttributesCommand(sender, args);
else if (args[0].equalsIgnoreCase("potions")) { } else if (args[0].equalsIgnoreCase("slots")) {
new PotionCommand(sender, args); new SlotCommand(sender, args);
} } else if (args[0].equalsIgnoreCase("importdata")) {
else if (args[0].equalsIgnoreCase("flags")) { new ImportCommand(sender, args);
new FlagCommand(sender, args); } else if (args[0].equalsIgnoreCase("iteminfo")) {
} new InfoCommand(sender, args);
else if (args[0].equalsIgnoreCase("attributes")) { } else if (args[0].equalsIgnoreCase("itemlist")) {
new AttributesCommand(sender, args); new ItemListCommand(sender, args);
} } else if (args[0].equalsIgnoreCase("item") || args[0].equalsIgnoreCase("i")) {
else if (args[0].equalsIgnoreCase("slots")) { new ItemCommand(sender, args);
new SlotCommand(sender, args); } else if (args[0].equalsIgnoreCase("setvariable")) {
} new VariableSetCommand(sender, args);
else if (args[0].equalsIgnoreCase("importdata")) { } else if (args[0].equalsIgnoreCase("getvariable")) {
new ImportCommand(sender, args); new VariableGetCommand(sender, args);
} } else if (args[0].equalsIgnoreCase("shell") || args[0].equalsIgnoreCase("s")) {
else if (args[0].equalsIgnoreCase("iteminfo")) { new ShellCommand(sender, args);
new InfoCommand(sender, args); } else if (args[0].equalsIgnoreCase("cycle") || args[0].equalsIgnoreCase("c")) {
} new CycleCommand(sender, args);
else if (args[0].equalsIgnoreCase("itemlist")) { } else if (args[0].equalsIgnoreCase("sounds")) {
new ItemListCommand(sender, args); new SoundsCommand(sender, args);
} } else if (args[0].equalsIgnoreCase("tagprefix")) {
else if (args[0].equalsIgnoreCase("item") || args[0].equalsIgnoreCase("i")) { new TagPrefixCommand(sender, args);
new ItemCommand(sender, args); } else if (args[0].equalsIgnoreCase("tagsuffix")) {
} new TagSuffixCommand(sender, args);
else if (args[0].equalsIgnoreCase("setvariable")) { } else if (args[0].equalsIgnoreCase("tagdelete")) {
new VariableSetCommand(sender, args); new TagDeleteCommand(sender, args);
} } else if (args[0].equalsIgnoreCase("itemreload") || args[0].equalsIgnoreCase("ireload")) {
else if (args[0].equalsIgnoreCase("getvariable")) { ItemUtils.reloadItemCache();
new VariableGetCommand(sender, args); ItemUtils.reloadItemName();
} TLocale.sendTo(sender, "COMMANDS.RELOAD.SUCCESS-NORMAL");
else if (args[0].equalsIgnoreCase("shell") || args[0].equalsIgnoreCase("s")) { } else {
new ShellCommand(sender, args); TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN");
} }
else if (args[0].equalsIgnoreCase("cycle") || args[0].equalsIgnoreCase("c")) { return true;
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;
}
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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; package me.skymc.taboolib.commands.sub;
import java.io.File; import java.io.File;
import java.util.Objects;
import com.ilummc.tlib.resources.TLocale;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
@ -18,28 +20,34 @@ public class ImportCommand extends SubCommand {
super(sender, args); super(sender, args);
if (isPlayer()) { 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("开始导入玩家数据..."); TLocale.sendTo(sender, "COMMANDS.TABOOLIB.IMPORTDATA.CLEARING");
int size = Main.getPlayerDataFolder().listFiles().length; Main.getConnection().truncateTable(Main.getTablePrefix() + "_playerdata");
int loop = 1;
for (File file : Main.getPlayerDataFolder().listFiles()) { if (!Main.getPlayerDataFolder().exists()) {
FileConfiguration conf = YamlConfiguration.loadConfiguration(file); TLocale.sendTo(sender, "COMMANDS.TABOOLIB.IMPORTDATA.EMPTYDATA");
Main.getConnection().intoValue(Main.getTablePrefix() + "_playerdata", file.getName().replace(".yml", ""), ConfigUtils.encodeYAML(conf)); return;
MsgUtils.send("导入玩家: &f" + file.getName().replace(".yml", "") + " &7进度: &f" + loop + "/" + size);
loop++;
}
MsgUtils.send("导入完成!");
} }
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; 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.Material;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; 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 { public class InfoCommand extends SubCommand {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public InfoCommand(CommandSender sender, String[] args) { public InfoCommand(CommandSender sender, String[] args) {
super(sender, args); super(sender, args);
if (isPlayer()) {
if (isPlayer()) { Player player = (Player) sender;
Player player = (Player) sender; if (player.getItemInHand().getType().equals(Material.AIR)) {
if (player.getItemInHand().getType().equals(Material.AIR)) { TLocale.sendTo(sender, "COMMANDS.TABOOLIB.INFO.INVALID-ITEM");
MsgUtils.send(player, "&7请手持正确物品"); } else {
} NBTItem nbt = new NBTItem(player.getItemInHand());
else { TLocale.sendTo(sender, "COMAMNDS.TABOOLIB.INFO.ITEM-INFO",
sender.sendMessage("§f"); player.getItemInHand().getType().name(),
sender.sendMessage("§b§l----- §3§lItemStack Info §b§l-----"); ItemUtils.getCustomName(player.getItemInHand()),
sender.sendMessage("§f"); player.getItemInHand().getTypeId() + ":" + player.getItemInHand().getDurability(),
nbt.toString());
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");
}
}
}
} }

View File

@ -1,77 +1,64 @@
package me.skymc.taboolib.commands.sub; 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.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import me.skymc.taboolib.commands.SubCommand; import java.util.HashMap;
import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.message.MsgUtils;
import me.skymc.taboolib.other.NumberUtils;
public class ItemCommand extends SubCommand { public class ItemCommand extends SubCommand {
/** public ItemCommand(CommandSender sender, String[] args) {
* /TabooLib item 物品 玩家 数量 super(sender, args);
*
* @param sender
* @param args
*/
public ItemCommand(CommandSender sender, String[] args) {
super(sender, args);
if (args.length < 2) { if (args.length < 2) {
MsgUtils.send(sender, "请输入正确的物品名称"); TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEM.INVALID-NAME");
setReturn(false); return;
} }
else {
if (ItemUtils.getCacheItem(args[1]) == null) {
MsgUtils.send(sender, "物品 &f" + args[1] + "&7 不存在");
setReturn(false);
return;
}
Player player; if (ItemUtils.getCacheItem(args[1]) == null) {
Integer amount = 1; TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEM.INVALID-ITEM", args[1]);
ItemStack item = ItemUtils.getCacheItem(args[1]).clone(); return;
}
if (args.length > 2) { Player player;
player = Bukkit.getPlayerExact(args[2]); Integer amount = 1;
if (player == null) { ItemStack item = ItemUtils.getCacheItem(args[1]).clone();
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) { if (args.length > 2) {
amount = NumberUtils.getInteger(args[3]); player = Bukkit.getPlayerExact(args[2]);
if (amount < 1) { if (player == null) {
MsgUtils.send(sender, "数量必须大于0"); TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEM.INVALID-PLAYER", args[2]);
setReturn(false); return;
return; }
} } else if (sender instanceof Player) {
} player = (Player) sender;
item.setAmount(amount); } else {
TLocale.sendTo(sender, "COMMANDS.GLOBAL.ONLY-PLAYER");
return;
}
HashMap<Integer, ItemStack> map = player.getInventory().addItem(item); if (args.length > 3) {
if (map.size() > 0) { amount = NumberUtils.getInteger(args[3]);
player.getWorld().dropItem(player.getLocation(), item); if (amount < 1) {
} TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEM.INVALID-NUMBER");
return;
}
}
item.setAmount(amount);
MsgUtils.send(sender, "物品已发送至玩家 &f" + player.getName() + " &7的背包中"); HashMap<Integer, ItemStack> map = player.getInventory().addItem(item);
setReturn(true); 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; package me.skymc.taboolib.commands.sub;
import com.ilummc.tlib.resources.TLocale;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType; 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.click.SuggestCommandEvent;
import me.skymc.taboolib.jsonformatter.hover.ShowTextEvent; import me.skymc.taboolib.jsonformatter.hover.ShowTextEvent;
import java.util.Arrays;
public class PotionCommand extends SubCommand { public class PotionCommand extends SubCommand {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public PotionCommand(CommandSender sender, String[] args) { public PotionCommand(CommandSender sender, String[] args) {
super(sender, args); super(sender, args);
sender.sendMessage("§f"); TLocale.sendTo(sender, "COMMANDS.TABOOLIB.POTIONS.HEAD");
sender.sendMessage("§b§l----- §3§lPotionEffect Types §b§l-----");
sender.sendMessage("§f");
for (PotionEffectType type : PotionEffectType.values()) { for (PotionEffectType potionEffectType : PotionEffectType.values()) {
if (type != null) { if (potionEffectType != null) {
if (isPlayer()) { TLocale.sendTo(sender, "COMMANDS.TABOOLIB.POTIONS.BODY", String.valueOf(potionEffectType.getId()), potionEffectType.getName());
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); TLocale.sendTo(sender, "COMMANDS.TABOOLIB.POTIONS.FOOT");
}
else {
sender.sendMessage(" §7- §f" + type.getId() + ". " + type.getName() + "");
}
}
}
sender.sendMessage("§f");
} }
} }

View File

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

View File

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

View File

@ -1,5 +1,6 @@
package me.skymc.taboolib.commands.sub; package me.skymc.taboolib.commands.sub;
import com.ilummc.tlib.resources.TLocale;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import me.skymc.taboolib.commands.SubCommand; import me.skymc.taboolib.commands.SubCommand;
@ -12,10 +13,13 @@ public class VariableGetCommand extends SubCommand {
super(sender, args); super(sender, args);
if (args.length < 3) { 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(); Long time = System.currentTimeMillis();
@ -28,13 +32,7 @@ public class VariableGetCommand extends SubCommand {
value = GlobalDataManager.getVariableAsynchronous(args[2], null); value = GlobalDataManager.getVariableAsynchronous(args[2], null);
} }
if (value == null) { TLocale.sendTo(sender, "COAMMNDS.TABOOLIB.VARIABLE.READ-SUCCESS", String.valueOf(System.currentTimeMillis() - time));
MsgUtils.send(sender, "读取完成, 耗时: &f" + (System.currentTimeMillis() - time) + " &7(ms)"); TLocale.sendTo(sender, "COAMMNDS.TABOOLIB.VARIABLE.READ-RESULT", value == null ? "null" : value);
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);
}
} }
} }

View File

@ -1,5 +1,6 @@
package me.skymc.taboolib.commands.sub; package me.skymc.taboolib.commands.sub;
import com.ilummc.tlib.resources.TLocale;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import me.skymc.taboolib.commands.SubCommand; import me.skymc.taboolib.commands.SubCommand;
@ -12,10 +13,13 @@ public class VariableSetCommand extends SubCommand {
super(sender, args); super(sender, args);
if (args.length < 4) { 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(); Long time = System.currentTimeMillis();
@ -28,7 +32,7 @@ public class VariableSetCommand extends SubCommand {
GlobalDataManager.setVariableAsynchronous(args[2], value); 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); setReturn(true);
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -1,11 +1,10 @@
package me.skymc.taboolib.commands.sub.sounds; 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.SubCommand;
import me.skymc.taboolib.commands.sub.sounds.listener.SoundsLibraryPatch; import me.skymc.taboolib.commands.sub.sounds.listener.SoundsLibraryPatch;
import me.skymc.taboolib.other.NumberUtils; import me.skymc.taboolib.other.NumberUtils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/** /**
* @author sky * @author sky
@ -13,19 +12,16 @@ import me.skymc.taboolib.other.NumberUtils;
*/ */
public class SoundsCommand extends SubCommand { public class SoundsCommand extends SubCommand {
/** public SoundsCommand(CommandSender sender, String[] args) {
* @param sender super(sender, args);
* @param args if (isPlayer()) {
*/ if (args.length == 1) {
public SoundsCommand(CommandSender sender, String[] args) { SoundsLibraryPatch.openInventory((Player) sender, 1, null);
super(sender, args); } else if (args.length == 2) {
if (isPlayer()) { SoundsLibraryPatch.openInventory((Player) sender, NumberUtils.getInteger(args[1]), null);
if (args.length == 1) { } else {
SoundsLibraryPatch.openInventory((Player) sender, 1); SoundsLibraryPatch.openInventory((Player) sender, NumberUtils.getInteger(args[1]), args[2]);
} }
else { }
SoundsLibraryPatch.openInventory((Player) sender, NumberUtils.getInteger(args[1])); }
}
}
}
} }

View File

@ -1,8 +1,11 @@
package me.skymc.taboolib.commands.sub.sounds.listener; package me.skymc.taboolib.commands.sub.sounds.listener;
import java.util.Arrays; import com.ilummc.tlib.resources.TLocale;
import java.util.HashMap; 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.Bukkit;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Sound; import org.bukkit.Sound;
@ -15,8 +18,11 @@ import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import me.skymc.taboolib.inventory.InventoryUtil; import java.util.ArrayList;
import me.skymc.taboolib.inventory.ItemUtils; import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
/** /**
* @author sky * @author sky
@ -24,86 +30,93 @@ import me.skymc.taboolib.inventory.ItemUtils;
*/ */
public class SoundsLibraryPatch implements Listener { public class SoundsLibraryPatch implements Listener {
/** public static void openInventory(Player player, int page, String search) {
* 打开物品库界面 if (page < 1) {
* page = 1;
* @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; SoundLibraryHolder holder = new SoundLibraryHolder(page, search);
for (Sound sound : Arrays.asList(Sound.values())) { Inventory inventory = Bukkit.createInventory(holder, 54, TLocale.asString("COMMANDS.TABOOLIB.SOUNDS.MENU.TITLE", String.valueOf(page)));
if (loop >= (page - 1) * 28) { List<Sound> soundFilter = Arrays.stream(Sound.values()).filter(sound -> search == null || sound.name().contains(search.toUpperCase())).collect(Collectors.toList());
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++;
}
if (page > 1) { int loop = 0;
inventory.setItem(47, ItemUtils.setName(new ItemStack(Material.ARROW), "§f上一页")); for (Sound sound : soundFilter) {
} if (loop >= (page - 1) * 28) {
if (((int) Math.ceil(Sound.values().length / 28D)) > page) { if (loop < page * 28) {
inventory.setItem(51, ItemUtils.setName(new ItemStack(Material.ARROW), "§f下一页")); int slot = InventoryUtil.SLOT_OF_CENTENTS.get(loop - ((page - 1) * 28));
} inventory.setItem(slot, getSoundItem(sound.name()));
player.openInventory(inventory); holder.SOUNDS_DATA.put(slot, sound);
} } else {
break;
}
}
loop++;
}
@EventHandler if (page > 1) {
public void inventoryClick(InventoryClickEvent e) { inventory.setItem(47, ItemUtils.setName(new ItemStack(Material.ARROW), TLocale.asString("COMMANDS.TABOOLIB.SOUNDS.MENU.BACK")));
if (e.getInventory().getHolder() instanceof SoundLibraryHolder) { }
e.setCancelled(true); 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")));
}
if (e.getCurrentItem() == null || e.getCurrentItem().getType().equals(Material.AIR) || e.getRawSlot() >= e.getInventory().getSize()) { if (!(player.getOpenInventory().getTopInventory().getHolder() instanceof SoundLibraryHolder)) {
return; TLocale.sendTo(player, "COMMANDS.TABOOLIB.SOUNDS.RESULT.SEARCH", (search == null ? "*" : search), String.valueOf(soundFilter.size()));
} }
player.openInventory(inventory);
}
switch (e.getRawSlot()) { @EventHandler
case 47: public void inventoryClick(InventoryClickEvent e) {
openInventory((Player) e.getWhoClicked(), ((SoundLibraryHolder) e.getInventory().getHolder()).PAGE - 1); if (e.getInventory().getHolder() instanceof SoundLibraryHolder) {
break; e.setCancelled(true);
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 (e.getCurrentItem() == null || e.getCurrentItem().getType().equals(Material.AIR) || e.getRawSlot() >= e.getInventory().getSize()) {
return;
}
public final int PAGE; SoundLibraryHolder soundLibraryHolder = ((SoundLibraryHolder) e.getInventory().getHolder());
public final HashMap<Integer, Sound> SOUNDS_DATA = new HashMap<>(); 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());
}
}
}
}
public SoundLibraryHolder(int page) { private static ItemStack getSoundItem(String sound) {
this.PAGE = page; 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;
}
@Override public static class SoundLibraryHolder implements InventoryHolder {
public Inventory getInventory() {
return null; 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; package me.skymc.taboolib.csvutils;
import java.io.BufferedReader; import java.io.*;
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.nio.charset.Charset; import java.nio.charset.Charset;
import java.text.NumberFormat; import java.text.NumberFormat;
import java.util.HashMap; import java.util.HashMap;
public class CsvReader public class CsvReader {
{
private Reader inputStream; private Reader inputStream;
private String fileName; private String fileName;
private UserSettings userSettings; private UserSettings userSettings;
@ -255,8 +247,7 @@ public class CsvReader
this.headersHolder.IndexByName.clear(); this.headersHolder.IndexByName.clear();
if (headers != null) { if (headers != null) {
this.headersHolder.Length = headers.length; this.headersHolder.Length = headers.length;
} } else {
else {
this.headersHolder.Length = 0; this.headersHolder.Length = 0;
} }
for (int i = 0; i < this.headersHolder.Length; ++i) { for (int i = 0; i < this.headersHolder.Length; ++i) {
@ -301,8 +292,7 @@ public class CsvReader
do { do {
if (this.dataBuffer.Position == this.dataBuffer.Count) { if (this.dataBuffer.Position == this.dataBuffer.Count) {
this.checkDataLength(); this.checkDataLength();
} } else {
else {
this.startedWithQualifier = false; this.startedWithQualifier = false;
char c = this.dataBuffer.Buffer[this.dataBuffer.Position]; char c = this.dataBuffer.Buffer[this.dataBuffer.Position];
if (this.userSettings.UseTextQualifier && c == this.userSettings.TextQualifier) { if (this.userSettings.UseTextQualifier && c == this.userSettings.TextQualifier) {
@ -326,24 +316,21 @@ public class CsvReader
do { do {
if (this.dataBuffer.Position == this.dataBuffer.Count) { if (this.dataBuffer.Position == this.dataBuffer.Count) {
this.checkDataLength(); this.checkDataLength();
} } else {
else {
final char lastLetter = this.dataBuffer.Buffer[this.dataBuffer.Position]; final char lastLetter = this.dataBuffer.Buffer[this.dataBuffer.Position];
if (n2 != 0) { if (n2 != 0) {
this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1;
if (lastLetter == this.userSettings.Delimiter) { if (lastLetter == this.userSettings.Delimiter) {
this.endColumn(); 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.endColumn();
this.endRecord(); this.endRecord();
} }
} } else if (n4 != 0) {
else if (n4 != 0) {
++n6; ++n6;
switch (n5) { switch (n5) {
case 1: { case 1: {
c2 = (char)((char)(c2 * '\u0010') + hexToDec(lastLetter)); c2 = (char) ((char) (c2 * '\u0010') + hexToDec(lastLetter));
if (n6 == 4) { if (n6 == 4) {
n4 = 0; n4 = 0;
break; break;
@ -351,7 +338,7 @@ public class CsvReader
break; break;
} }
case 2: { case 2: {
c2 = (char)((char)(c2 * '\b') + (char)(lastLetter - '0')); c2 = (char) ((char) (c2 * '\b') + (char) (lastLetter - '0'));
if (n6 == 3) { if (n6 == 3) {
n4 = 0; n4 = 0;
break; break;
@ -359,7 +346,7 @@ public class CsvReader
break; break;
} }
case 3: { case 3: {
c2 = (char)((char)(c2 * '\n') + (char)(lastLetter - '0')); c2 = (char) ((char) (c2 * '\n') + (char) (lastLetter - '0'));
if (n6 == 3) { if (n6 == 3) {
n4 = 0; n4 = 0;
break; break;
@ -367,7 +354,7 @@ public class CsvReader
break; break;
} }
case 4: { case 4: {
c2 = (char)((char)(c2 * '\u0010') + hexToDec(lastLetter)); c2 = (char) ((char) (c2 * '\u0010') + hexToDec(lastLetter));
if (n6 == 2) { if (n6 == 2) {
n4 = 0; n4 = 0;
break; break;
@ -377,25 +364,21 @@ public class CsvReader
} }
if (n4 == 0) { if (n4 == 0) {
this.appendLetter(c2); this.appendLetter(c2);
} } else {
else {
this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1;
} }
} } else if (lastLetter == this.userSettings.TextQualifier) {
else if (lastLetter == this.userSettings.TextQualifier) {
if (n3 != 0) { if (n3 != 0) {
n3 = 0; n3 = 0;
n = 0; n = 0;
} } else {
else {
this.updateCurrentValue(); this.updateCurrentValue();
if (this.userSettings.EscapeMode == 1) { if (this.userSettings.EscapeMode == 1) {
n3 = 1; n3 = 1;
} }
n = 1; n = 1;
} }
} } else if (this.userSettings.EscapeMode == 2 && n3 != 0) {
else if (this.userSettings.EscapeMode == 2 && n3 != 0) {
switch (lastLetter) { switch (lastLetter) {
case 'n': { case 'n': {
this.appendLetter('\n'); this.appendLetter('\n');
@ -440,7 +423,7 @@ public class CsvReader
n5 = 2; n5 = 2;
n4 = 1; n4 = 1;
n6 = 1; n6 = 1;
c2 = (char)(lastLetter - '0'); c2 = (char) (lastLetter - '0');
this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1;
break; break;
} }
@ -482,20 +465,16 @@ public class CsvReader
} }
} }
n3 = 0; n3 = 0;
} } else if (lastLetter == textQualifier) {
else if (lastLetter == textQualifier) {
this.updateCurrentValue(); this.updateCurrentValue();
n3 = 1; n3 = 1;
} } else if (n != 0) {
else if (n != 0) {
if (lastLetter == this.userSettings.Delimiter) { if (lastLetter == this.userSettings.Delimiter) {
this.endColumn(); 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.endColumn();
this.endRecord(); this.endRecord();
} } else {
else {
this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1;
n2 = 1; n2 = 1;
} }
@ -513,40 +492,32 @@ public class CsvReader
} }
} }
} while (this.hasMoreData && this.startedColumn); } while (this.hasMoreData && this.startedColumn);
} } else if (c == this.userSettings.Delimiter) {
else if (c == this.userSettings.Delimiter) {
this.lastLetter = c; this.lastLetter = c;
this.endColumn(); 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) { if (this.startedColumn || this.columnsCount > 0 || !this.userSettings.SkipEmptyRecords) {
this.endColumn(); this.endColumn();
this.endRecord(); this.endRecord();
} } else {
else {
this.dataBuffer.LineStart = this.dataBuffer.Position + 1; this.dataBuffer.LineStart = this.dataBuffer.Position + 1;
} }
this.lastLetter = c; 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'))) { if (this.startedColumn || this.columnsCount > 0 || (!this.userSettings.SkipEmptyRecords && (c == '\r' || this.lastLetter != '\r'))) {
this.endColumn(); this.endColumn();
this.endRecord(); this.endRecord();
} } else {
else {
this.dataBuffer.LineStart = this.dataBuffer.Position + 1; this.dataBuffer.LineStart = this.dataBuffer.Position + 1;
} }
this.lastLetter = c; 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.lastLetter = c;
this.skipLine(); this.skipLine();
} } else if (this.userSettings.TrimWhitespace && (c == ' ' || c == '\t')) {
else if (this.userSettings.TrimWhitespace && (c == ' ' || c == '\t')) {
this.startedColumn = true; this.startedColumn = true;
this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1;
} } else {
else {
this.startedColumn = true; this.startedColumn = true;
this.dataBuffer.ColumnStart = this.dataBuffer.Position; this.dataBuffer.ColumnStart = this.dataBuffer.Position;
int n7 = 0; int n7 = 0;
@ -558,25 +529,22 @@ public class CsvReader
do { do {
if (n11 == 0 && this.dataBuffer.Position == this.dataBuffer.Count) { if (n11 == 0 && this.dataBuffer.Position == this.dataBuffer.Count) {
this.checkDataLength(); this.checkDataLength();
} } else {
else {
if (n11 == 0) { if (n11 == 0) {
c = this.dataBuffer.Buffer[this.dataBuffer.Position]; c = this.dataBuffer.Buffer[this.dataBuffer.Position];
} }
if (!this.userSettings.UseTextQualifier && this.userSettings.EscapeMode == 2 && c == '\\') { if (!this.userSettings.UseTextQualifier && this.userSettings.EscapeMode == 2 && c == '\\') {
if (n7 != 0) { if (n7 != 0) {
n7 = 0; n7 = 0;
} } else {
else {
this.updateCurrentValue(); this.updateCurrentValue();
n7 = 1; n7 = 1;
} }
} } else if (n8 != 0) {
else if (n8 != 0) {
++n10; ++n10;
switch (n9) { switch (n9) {
case 1: { case 1: {
c3 = (char)((char)(c3 * '\u0010') + hexToDec(c)); c3 = (char) ((char) (c3 * '\u0010') + hexToDec(c));
if (n10 == 4) { if (n10 == 4) {
n8 = 0; n8 = 0;
break; break;
@ -584,7 +552,7 @@ public class CsvReader
break; break;
} }
case 2: { case 2: {
c3 = (char)((char)(c3 * '\b') + (char)(c - '0')); c3 = (char) ((char) (c3 * '\b') + (char) (c - '0'));
if (n10 == 3) { if (n10 == 3) {
n8 = 0; n8 = 0;
break; break;
@ -592,7 +560,7 @@ public class CsvReader
break; break;
} }
case 3: { case 3: {
c3 = (char)((char)(c3 * '\n') + (char)(c - '0')); c3 = (char) ((char) (c3 * '\n') + (char) (c - '0'));
if (n10 == 3) { if (n10 == 3) {
n8 = 0; n8 = 0;
break; break;
@ -600,7 +568,7 @@ public class CsvReader
break; break;
} }
case 4: { case 4: {
c3 = (char)((char)(c3 * '\u0010') + hexToDec(c)); c3 = (char) ((char) (c3 * '\u0010') + hexToDec(c));
if (n10 == 2) { if (n10 == 2) {
n8 = 0; n8 = 0;
break; break;
@ -610,12 +578,10 @@ public class CsvReader
} }
if (n8 == 0) { if (n8 == 0) {
this.appendLetter(c3); this.appendLetter(c3);
} } else {
else {
this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; 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) { switch (c) {
case 'n': { case 'n': {
this.appendLetter('\n'); this.appendLetter('\n');
@ -660,7 +626,7 @@ public class CsvReader
n9 = 2; n9 = 2;
n8 = 1; n8 = 1;
n10 = 1; n10 = 1;
c3 = (char)(c - '0'); c3 = (char) (c - '0');
this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1; this.dataBuffer.ColumnStart = this.dataBuffer.Position + 1;
break; break;
} }
@ -702,11 +668,9 @@ public class CsvReader
} }
} }
n7 = 0; n7 = 0;
} } else if (c == this.userSettings.Delimiter) {
else if (c == this.userSettings.Delimiter) {
this.endColumn(); 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.endColumn();
this.endRecord(); this.endRecord();
} }
@ -740,16 +704,13 @@ public class CsvReader
if (this.hasMoreData) { if (this.hasMoreData) {
if (this.rawBuffer.Position == 0) { if (this.rawBuffer.Position == 0) {
this.rawRecord = new String(this.dataBuffer.Buffer, this.dataBuffer.LineStart, this.dataBuffer.Position - this.dataBuffer.LineStart - 1); 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); 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); this.rawRecord = new String(this.rawBuffer.Buffer, 0, this.rawBuffer.Position);
} }
} } else {
else {
this.rawRecord = ""; this.rawRecord = "";
} }
return this.hasReadNextLine; return this.hasReadNextLine;
@ -776,8 +737,7 @@ public class CsvReader
} }
try { try {
this.dataBuffer.Count = this.inputStream.read(this.dataBuffer.Buffer, 0, this.dataBuffer.Buffer.length); this.dataBuffer.Count = this.inputStream.read(this.dataBuffer.Buffer, 0, this.dataBuffer.Buffer.length);
} } catch (IOException ex) {
catch (IOException ex) {
this.close(); this.close();
throw ex; throw ex;
} }
@ -831,8 +791,7 @@ public class CsvReader
} }
s = new String(this.dataBuffer.Buffer, this.dataBuffer.ColumnStart, n - this.dataBuffer.ColumnStart + 1); s = new String(this.dataBuffer.Buffer, this.dataBuffer.ColumnStart, n - this.dataBuffer.ColumnStart + 1);
} }
} } else {
else {
this.updateCurrentValue(); this.updateCurrentValue();
int n2 = this.columnBuffer.Position - 1; int n2 = this.columnBuffer.Position - 1;
if (this.userSettings.TrimWhitespace && !this.startedWithQualifier) { if (this.userSettings.TrimWhitespace && !this.startedWithQualifier) {
@ -922,8 +881,7 @@ public class CsvReader
do { do {
if (this.dataBuffer.Position == this.dataBuffer.Count) { if (this.dataBuffer.Position == this.dataBuffer.Count) {
this.checkDataLength(); this.checkDataLength();
} } else {
else {
b = true; b = true;
final char lastLetter = this.dataBuffer.Buffer[this.dataBuffer.Position]; final char lastLetter = this.dataBuffer.Buffer[this.dataBuffer.Position];
if (lastLetter == '\r' || lastLetter == '\n') { if (lastLetter == '\r' || lastLetter == '\n') {
@ -980,34 +938,30 @@ public class CsvReader
} }
@Override @Override
protected void finalize() { protected void finalize() {
this.close(false); this.close(false);
} }
private static char hexToDec(final char c) { private static char hexToDec(final char c) {
char c2; char c2;
if (c >= 'a') { if (c >= 'a') {
c2 = (char)(c - 'a' + '\n'); c2 = (char) (c - 'a' + '\n');
} } else if (c >= 'A') {
else if (c >= 'A') { c2 = (char) (c - 'A' + '\n');
c2 = (char)(c - 'A' + '\n'); } else {
} c2 = (char) (c - '0');
else {
c2 = (char)(c - '0');
} }
return c2; return c2;
} }
private class StaticSettings private class StaticSettings {
{
public static final int MAX_BUFFER_SIZE = 1024; public static final int MAX_BUFFER_SIZE = 1024;
public static final int MAX_FILE_BUFFER_SIZE = 4096; public static final int MAX_FILE_BUFFER_SIZE = 4096;
public static final int INITIAL_COLUMN_COUNT = 10; public static final int INITIAL_COLUMN_COUNT = 10;
public static final int INITIAL_COLUMN_BUFFER_SIZE = 50; public static final int INITIAL_COLUMN_BUFFER_SIZE = 50;
} }
private class HeadersHolder private class HeadersHolder {
{
public String[] Headers; public String[] Headers;
public int Length; public int Length;
public HashMap<String, Integer> IndexByName; public HashMap<String, Integer> IndexByName;
@ -1019,8 +973,7 @@ public class CsvReader
} }
} }
private class UserSettings private class UserSettings {
{
public boolean CaseSensitive; public boolean CaseSensitive;
public char TextQualifier; public char TextQualifier;
public boolean TrimWhitespace; public boolean TrimWhitespace;
@ -1050,8 +1003,7 @@ public class CsvReader
} }
} }
private class Letters private class Letters {
{
public static final char LF = '\n'; public static final char LF = '\n';
public static final char CR = '\r'; public static final char CR = '\r';
public static final char QUOTE = '\"'; public static final char QUOTE = '\"';
@ -1068,8 +1020,7 @@ public class CsvReader
public static final char ALERT = '\u0007'; public static final char ALERT = '\u0007';
} }
private class RawRecordBuffer private class RawRecordBuffer {
{
public char[] Buffer; public char[] Buffer;
public int Position; public int Position;
@ -1079,8 +1030,7 @@ public class CsvReader
} }
} }
private class ColumnBuffer private class ColumnBuffer {
{
public char[] Buffer; public char[] Buffer;
public int Position; public int Position;
@ -1090,8 +1040,7 @@ public class CsvReader
} }
} }
private class DataBuffer private class DataBuffer {
{
public char[] Buffer; public char[] Buffer;
public int Position; public int Position;
public int Count; public int Count;
@ -1107,8 +1056,7 @@ public class CsvReader
} }
} }
private class ComplexEscape private class ComplexEscape {
{
private static final int UNICODE = 1; private static final int UNICODE = 1;
private static final int OCTAL = 2; private static final int OCTAL = 2;
private static final int DECIMAL = 3; private static final int DECIMAL = 3;

View File

@ -1,15 +1,10 @@
package me.skymc.taboolib.csvutils; package me.skymc.taboolib.csvutils;
import java.io.BufferedWriter; import java.io.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset; import java.nio.charset.Charset;
public class CsvWriter public class CsvWriter {
{
private Writer outputStream; private Writer outputStream;
private String fileName; private String fileName;
private boolean firstColumn; private boolean firstColumn;
@ -159,26 +154,22 @@ public class CsvWriter
if (this.userSettings.EscapeMode == 2) { if (this.userSettings.EscapeMode == 2) {
s = replace(s, "\\", "\\\\"); s = replace(s, "\\", "\\\\");
s = replace(s, "" + this.userSettings.TextQualifier, "\\" + this.userSettings.TextQualifier); s = replace(s, "" + this.userSettings.TextQualifier, "\\" + this.userSettings.TextQualifier);
} } else {
else {
s = replace(s, "" + this.userSettings.TextQualifier, "" + this.userSettings.TextQualifier + this.userSettings.TextQualifier); 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, "\\", "\\\\");
s = replace(s, "" + this.userSettings.Delimiter, "\\" + this.userSettings.Delimiter); s = replace(s, "" + this.userSettings.Delimiter, "\\" + this.userSettings.Delimiter);
if (this.useCustomRecordDelimiter) { if (this.useCustomRecordDelimiter) {
s = replace(s, "" + this.userSettings.RecordDelimiter, "\\" + this.userSettings.RecordDelimiter); s = replace(s, "" + this.userSettings.RecordDelimiter, "\\" + this.userSettings.RecordDelimiter);
} } else {
else {
s = replace(s, "\r", "\\\r"); s = replace(s, "\r", "\\\r");
s = replace(s, "\n", "\\\n"); s = replace(s, "\n", "\\\n");
} }
if (this.firstColumn && s.length() > 0 && s.charAt(0) == this.userSettings.Comment) { if (this.firstColumn && s.length() > 0 && s.charAt(0) == this.userSettings.Comment) {
if (s.length() > 1) { if (s.length() > 1) {
s = "\\" + this.userSettings.Comment + s.substring(1); s = "\\" + this.userSettings.Comment + s.substring(1);
} } else {
else {
s = "\\" + this.userSettings.Comment; s = "\\" + this.userSettings.Comment;
} }
} }
@ -201,8 +192,7 @@ public class CsvWriter
this.outputStream.write(s); this.outputStream.write(s);
if (this.useCustomRecordDelimiter) { if (this.useCustomRecordDelimiter) {
this.outputStream.write(this.userSettings.RecordDelimiter); this.outputStream.write(this.userSettings.RecordDelimiter);
} } else {
else {
this.outputStream.write(this.systemRecordDelimiter); this.outputStream.write(this.systemRecordDelimiter);
} }
this.firstColumn = true; this.firstColumn = true;
@ -234,8 +224,7 @@ public class CsvWriter
this.checkInit(); this.checkInit();
if (this.useCustomRecordDelimiter) { if (this.useCustomRecordDelimiter) {
this.outputStream.write(this.userSettings.RecordDelimiter); this.outputStream.write(this.userSettings.RecordDelimiter);
} } else {
else {
this.outputStream.write(this.systemRecordDelimiter); this.outputStream.write(this.systemRecordDelimiter);
} }
this.firstColumn = true; this.firstColumn = true;
@ -277,7 +266,7 @@ public class CsvWriter
} }
@Override @Override
protected void finalize() { protected void finalize() {
this.close(false); this.close(false);
} }
@ -297,8 +286,7 @@ public class CsvWriter
} }
} }
private class UserSettings private class UserSettings {
{
public char TextQualifier; public char TextQualifier;
public boolean UseTextQualifier; public boolean UseTextQualifier;
public char Delimiter; public char Delimiter;
@ -318,8 +306,7 @@ public class CsvWriter
} }
} }
private class Letters private class Letters {
{
public static final char LF = '\n'; public static final char LF = '\n';
public static final char CR = '\r'; public static final char CR = '\r';
public static final char QUOTE = '\"'; public static final char QUOTE = '\"';

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,14 +1,13 @@
package me.skymc.taboolib.entity; 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.List;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.entity.Entity;
import org.bukkit.scheduler.BukkitRunnable;
import me.skymc.taboolib.Main;
/** /**
* - MetaData * - MetaData
* *
@ -17,256 +16,256 @@ import me.skymc.taboolib.Main;
*/ */
public class EntityTag { public class EntityTag {
private static EntityTag inst; private static EntityTag inst;
private static ConcurrentHashMap<UUID, ConcurrentHashMap<String, Object>> entityData = new ConcurrentHashMap<>(); private static ConcurrentHashMap<UUID, ConcurrentHashMap<String, Object>> entityData = new ConcurrentHashMap<>();
private EntityTag() { private EntityTag() {
new BukkitRunnable() { new BukkitRunnable() {
@Override @Override
public void run() { public void run() {
for (UUID uuid : entityData.keySet()) { for (UUID uuid : entityData.keySet()) {
if (EntityUtils.getEntityWithUUID(uuid) == null) { if (EntityUtils.getEntityWithUUID(uuid) == null) {
entityData.remove(uuid); entityData.remove(uuid);
} }
} }
} }
}.runTaskTimerAsynchronously(Main.getInst(), 20 * 180, 20 * 180); }.runTaskTimerAsynchronously(Main.getInst(), 20 * 180, 20 * 180);
} }
public static EntityTag getInst() { public static EntityTag getInst() {
if (inst == null) { if (inst == null) {
synchronized (EntityTag.class) { synchronized (EntityTag.class) {
if (inst == null) { if (inst == null) {
inst = new EntityTag(); inst = new EntityTag();
} }
} }
} }
return inst; return inst;
} }
/** /**
* 设置标签 * 设置标签
* *
* @param entity 实体 * @param entity 实体
* @param key * @param key
* @param value * @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, Entity... entities) { public void set(String key, Object value, Entity entity) {
for (Entity entity : entities) set(key, value, 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 key
* @param value * @param value
*/ */
public void set(String key, Object value, List<Entity> entities) { public void set(String key, Object value, Entity... entities) {
for (Entity entity : entities) set(key, value, entity); for (Entity entity : entities) set(key, value, entity);
} }
/** /**
* 移除标签 * 设置标签
* *
* @param key * @param key
* @param entity 实体 * @param value
*/ */
public Object remove(String key, Entity entity) { public void set(String key, Object value, List<Entity> entities) {
if (contains(entity)) { for (Entity entity : entities) set(key, value, entity);
entityData.get(entity.getUniqueId()).remove(key); }
if (entityData.get(entity.getUniqueId()).size() == 0) {
return entityData.remove(entity.getUniqueId());
}
}
return null;
}
/** /**
* 移除标签 * 移除标签
* *
* @param key * @param key
* @param entities 实体 * @param entity 实体
*/ */
public void remove(String key, Entity... entities) { public Object remove(String key, Entity entity) {
for (Entity entity : entities) remove(key, 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 key
* @param entities 实体 * @param entities 实体
*/ */
public void remove(String key, List<Entity> entities) { public void remove(String key, Entity... entities) {
for (Entity entity : entities) remove(key, entity); for (Entity entity : entities) remove(key, entity);
} }
/** /**
* 检查数据 * 移除标签
* *
* @param entity 实体 * @param key
* @return boolean * @param entities 实体
*/ */
public boolean contains(Entity entity) { public void remove(String key, List<Entity> entities) {
return entityData.containsKey(entity.getUniqueId()); for (Entity entity : entities) remove(key, entity);
} }
/** /**
* 检查标签 * 检查数据
* *
* @param key * @param entity 实体
* @param entity 实体 * @return boolean
* @return boolean */
*/ public boolean contains(Entity entity) {
public boolean hasKey(String key, 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); return contains(entity) && entityData.get(entity.getUniqueId()).containsKey(key);
} }
/** /**
* 获取数据 * 获取数据
* *
* @param key * @param key
* @param entity 实体 * @param entity 实体
* @return Object * @return Object
*/ */
public Object get(String key, Entity entity) { public Object get(String key, Entity entity) {
if (contains(entity)) { if (contains(entity)) {
return entityData.get(entity.getUniqueId()).get(key); return entityData.get(entity.getUniqueId()).get(key);
} }
return null; return null;
} }
/** /**
* 获取数据 * 获取数据
* *
* @param key * @param key
* @param entity * @param entity
* @return String * @return String
*/ */
public String getString(String key, Entity entity) { public String getString(String key, Entity entity) {
Object object = get(key, entity); Object object = get(key, entity);
if (object instanceof String) { if (object instanceof String) {
return (String) object; return (String) object;
} }
return null; return null;
} }
/** /**
* 获取数据 * 获取数据
* *
* @param key * @param key
* @param entity * @param entity
* @return int * @return int
*/ */
public int getInteger(String key, Entity entity) { public int getInteger(String key, Entity entity) {
Object object = get(key, entity); Object object = get(key, entity);
if (object != null) { if (object != null) {
return (int) object; return (int) object;
} }
return 0; return 0;
} }
/** /**
* 获取数据 * 获取数据
* *
* @param key * @param key
* @param entity * @param entity
* @return long * @return long
*/ */
public long getLong(String key, Entity entity) { public long getLong(String key, Entity entity) {
Object object = get(key, entity); Object object = get(key, entity);
if (object != null) { if (object != null) {
return (long) object; return (long) object;
} }
return 0L; return 0L;
} }
/** /**
* 获取数据 * 获取数据
* *
* @param key * @param key
* @param entity 实体 * @param entity 实体
* @return boolean * @return boolean
*/ */
public boolean getBoolean(String key, Entity entity) { public boolean getBoolean(String key, Entity entity) {
Object object = get(key, entity); Object object = get(key, entity);
return object != null && (boolean) object; return object != null && (boolean) object;
} }
/** /**
* 获取数据 * 获取数据
* *
* @param key * @param key
* @param entity 实体 * @param entity 实体
* @return double * @return double
*/ */
public double getDouble(String key, Entity entity) { public double getDouble(String key, Entity entity) {
Object object = get(key, entity); Object object = get(key, entity);
if (object != null) { if (object != null) {
return (double) object; return (double) object;
} }
return 0D; return 0D;
} }
/** /**
* 获取数据 * 获取数据
* *
* @param key * @param key
* @param entity 实体 * @param entity 实体
* @return float * @return float
*/ */
public double getFloat(String key, Entity entity) { public double getFloat(String key, Entity entity) {
Object object = get(key, entity); Object object = get(key, entity);
if (object != null) { if (object != null) {
return (float) object; return (float) object;
} }
return 0F; return 0F;
} }
/** /**
* 获取数据 * 获取数据
* *
* @param key * @param key
* @param entity 实体 * @param entity 实体
* @return short * @return short
*/ */
public short getShort(String key, Entity entity) { public short getShort(String key, Entity entity) {
Object object = get(key, entity); Object object = get(key, entity);
if (object != null) { if (object != null) {
return (short) object; return (short) object;
} }
return (short) 0; return (short) 0;
} }
/** /**
* 获取数据 * 获取数据
* *
* @param key * @param key
* @param entity 实体 * @param entity 实体
* @return byte * @return byte
*/ */
public byte getByte(String key, Entity entity) { public byte getByte(String key, Entity entity) {
Object object = get(key, entity); Object object = get(key, entity);
if (object != null) { if (object != null) {
return (byte) object; return (byte) object;
} }
return (byte) 0; return (byte) 0;
} }
} }

View File

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

View File

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

View File

@ -5,8 +5,8 @@ import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent; import org.bukkit.event.player.PlayerEvent;
public class DefaultEvent2 extends PlayerEvent public class DefaultEvent2 extends PlayerEvent {
{
private static final HandlerList handlers; private static final HandlerList handlers;
static { static {
@ -22,12 +22,11 @@ public class DefaultEvent2 extends PlayerEvent
} }
@Override @Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return DefaultEvent2.handlers; return DefaultEvent2.handlers;
} }
public static class Pre extends DefaultEvent2 implements Cancellable public static class Pre extends DefaultEvent2 implements Cancellable {
{
private boolean cancelled; private boolean cancelled;
public Pre(Player who) { public Pre(Player who) {
@ -36,18 +35,17 @@ public class DefaultEvent2 extends PlayerEvent
} }
@Override @Override
public boolean isCancelled() { public boolean isCancelled() {
return this.cancelled; return this.cancelled;
} }
@Override @Override
public void setCancelled(final boolean cancelled) { public void setCancelled(final boolean cancelled) {
this.cancelled = cancelled; this.cancelled = cancelled;
} }
} }
public static class Post extends DefaultEvent2 public static class Post extends DefaultEvent2 {
{
public Post(Player who) { public Post(Player who) {
super(who); super(who);
} }

View File

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

View File

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

View File

@ -1,123 +1,116 @@
package me.skymc.taboolib.fileutils; package me.skymc.taboolib.fileutils;
import java.io.File; import java.io.*;
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.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException; import java.nio.charset.UnsupportedCharsetException;
public class EncodeUtils { public class EncodeUtils {
/** /**
* 把指定文件或目录转换成指定的编码 * 把指定文件或目录转换成指定的编码
* *
* @param fileName 要转换的文件 * @param fileName 要转换的文件
* @param fromCharsetName 源文件的编码 * @param fromCharsetName 源文件的编码
* @param toCharsetName 要转换的编码 * @param toCharsetName 要转换的编码
* @throws Exception * @throws Exception
*/ */
public static void convert(String fileName, String fromCharsetName, String toCharsetName) throws Exception { public static void convert(String fileName, String fromCharsetName, String toCharsetName) throws Exception {
convert(new File(fileName), fromCharsetName, toCharsetName, null); convert(new File(fileName), fromCharsetName, toCharsetName, null);
} }
/** /**
* 把指定文件或目录转换成指定的编码 * 把指定文件或目录转换成指定的编码
* *
* @param file 要转换的文件或目录 * @param file 要转换的文件或目录
* @param fromCharsetName 源文件的编码 * @param fromCharsetName 源文件的编码
* @param toCharsetName 要转换的编码 * @param toCharsetName 要转换的编码
* @throws Exception * @throws Exception
*/ */
public static void convert(File file, String fromCharsetName, String toCharsetName) throws Exception { public static void convert(File file, String fromCharsetName, String toCharsetName) throws Exception {
convert(file, fromCharsetName, toCharsetName, null); convert(file, fromCharsetName, toCharsetName, null);
} }
/** /**
* 把指定文件或目录转换成指定的编码 * 把指定文件或目录转换成指定的编码
* *
* @param fromCharsetName 源文件的编码 * @param fromCharsetName 源文件的编码
* @param toCharsetName 转换的编码 * @param toCharsetName 转换的编码
* @param filter 文件名过滤器 * @param filter 文件名过滤器
* @throws Exception * @throws Exception
*/ */
public static void convert(String fileName, String fromCharsetName, String toCharsetName, FilenameFilter filter) throws Exception { public static void convert(String fileName, String fromCharsetName, String toCharsetName, FilenameFilter filter) throws Exception {
convert(new File(fileName), fromCharsetName, toCharsetName, filter); convert(new File(fileName), fromCharsetName, toCharsetName, filter);
} }
/** /**
* 把指定文件或目录转换成指定的编码 * 把指定文件或目录转换成指定的编码
* *
* @param file 要转换的文件或目录 * @param file 要转换的文件或目录
* @param fromCharsetName 源文件的编码 * @param fromCharsetName 源文件的编码
* @param toCharsetName 要转换的编码 * @param toCharsetName 要转换的编码
* @param filter 文件名过滤器 * @param filter 文件名过滤器
* @throws Exception * @throws Exception
*/ */
public static void convert(File file, String fromCharsetName, String toCharsetName, FilenameFilter filter) throws Exception { public static void convert(File file, String fromCharsetName, String toCharsetName, FilenameFilter filter) throws Exception {
if (file.isDirectory()) { if (file.isDirectory()) {
File[] fileList = null; File[] fileList = null;
if (filter == null) { if (filter == null) {
fileList = file.listFiles(); fileList = file.listFiles();
} else { } else {
fileList = file.listFiles(filter); fileList = file.listFiles(filter);
} }
for (File f : fileList) { for (File f : fileList) {
convert(f, fromCharsetName, toCharsetName, filter); convert(f, fromCharsetName, toCharsetName, filter);
} }
} else { } else {
if (filter == null if (filter == null
|| filter.accept(file.getParentFile(), file.getName())) { || filter.accept(file.getParentFile(), file.getName())) {
String fileContent = getFileContentFromCharset(file, String fileContent = getFileContentFromCharset(file,
fromCharsetName); fromCharsetName);
saveFile2Charset(file, toCharsetName, fileContent); saveFile2Charset(file, toCharsetName, fileContent);
} }
} }
} }
/** /**
* 以指定编码方式读取文件返回文件内容 * 以指定编码方式读取文件返回文件内容
* *
* @param file 要转换的文件 * @param file 要转换的文件
* @param fromCharsetName 源文件的编码 * @param fromCharsetName 源文件的编码
* @return * @return
* @throws Exception * @throws Exception
*/ */
public static String getFileContentFromCharset(File file, String fromCharsetName) throws Exception { public static String getFileContentFromCharset(File file, String fromCharsetName) throws Exception {
if (!Charset.isSupported(fromCharsetName)) { if (!Charset.isSupported(fromCharsetName)) {
throw new UnsupportedCharsetException(fromCharsetName); throw new UnsupportedCharsetException(fromCharsetName);
} }
InputStream inputStream = new FileInputStream(file); InputStream inputStream = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(inputStream, InputStreamReader reader = new InputStreamReader(inputStream,
fromCharsetName); fromCharsetName);
char[] chs = new char[(int) file.length()]; char[] chs = new char[(int) file.length()];
reader.read(chs); reader.read(chs);
String str = new String(chs).trim(); String str = new String(chs).trim();
reader.close(); reader.close();
return str; return str;
} }
/** /**
* 以指定编码方式写文本文件存在会覆盖 * 以指定编码方式写文本文件存在会覆盖
* *
* @param file 要写入的文件 * @param file 要写入的文件
* @param toCharsetName 要转换的编码 * @param toCharsetName 要转换的编码
* @param content 文件内容 * @param content 文件内容
* @throws Exception * @throws Exception
*/ */
public static void saveFile2Charset(File file, String toCharsetName, String content) throws Exception { public static void saveFile2Charset(File file, String toCharsetName, String content) throws Exception {
if (!Charset.isSupported(toCharsetName)) { if (!Charset.isSupported(toCharsetName)) {
throw new UnsupportedCharsetException(toCharsetName); throw new UnsupportedCharsetException(toCharsetName);
} }
OutputStream outputStream = new FileOutputStream(file); OutputStream outputStream = new FileOutputStream(file);
OutputStreamWriter outWrite = new OutputStreamWriter(outputStream, toCharsetName); OutputStreamWriter outWrite = new OutputStreamWriter(outputStream, toCharsetName);
outWrite.write(content); outWrite.write(content);
outWrite.close(); outWrite.close();
System.out.println("[Encodeing...] 更改文件: " + file.getPath()); System.out.println("[Encodeing...] 更改文件: " + file.getPath());
} }
} }

View File

@ -11,9 +11,9 @@ import java.nio.channels.FileChannel;
public class FileUtils { public class FileUtils {
public static String ip() { public static String ip() {
try { try {
InputStream ins = null; InputStream ins = null;
URL url = new URL("http://1212.ip138.com/ic.asp"); URL url = new URL("http://1212.ip138.com/ic.asp");
URLConnection con = url.openConnection(); URLConnection con = url.openConnection();
ins = con.getInputStream(); ins = con.getInputStream();
@ -28,97 +28,96 @@ public class FileUtils {
int end = webContent.indexOf("]"); int end = webContent.indexOf("]");
ins.close(); ins.close();
return webContent.substring(start, end); return webContent.substring(start, end);
} catch (Exception e) {
// TODO: handle exception
} }
catch (Exception e) {
// TODO: handle exception
}
return "[IP ERROR]"; return "[IP ERROR]";
} }
/** /**
* 创建并获取文件 * 创建并获取文件
* *
* @param filePath * @param filePath
* @return * @return
*/ */
public static File file(String filePath) { public static File file(String filePath) {
File file = new File(filePath); File file = new File(filePath);
if (!file.exists()) { if (!file.exists()) {
try { try {
file.createNewFile(); file.createNewFile();
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
} }
} }
return file; return file;
} }
/** /**
* 创建并获取文件 * 创建并获取文件
* *
* @param Path * @param Path
* @param filePath * @param filePath
* @return * @return
*/ */
public static File file(File Path, String filePath) { public static File file(File Path, String filePath) {
File file = new File(Path, filePath); File file = new File(Path, filePath);
if (!file.exists()) { if (!file.exists()) {
try { try {
file.createNewFile(); file.createNewFile();
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
} }
} }
return file; return file;
} }
/** /**
* 删除文件夹 * 删除文件夹
* *
* @param file * @param file
*/ */
public void deleteAllFile(File file) { public void deleteAllFile(File file) {
if (!file.exists()) { if (!file.exists()) {
return; return;
} }
if (file.isFile()) { if (file.isFile()) {
file.delete(); file.delete();
return; return;
} }
File[] files = file.listFiles(); File[] files = file.listFiles();
for (File file1 : files) { for (File file1 : files) {
deleteAllFile(file1); deleteAllFile(file1);
} }
file.delete(); file.delete();
} }
/** /**
* 复制文件夹 * 复制文件夹
* *
* @param file1 文件1 * @param file1 文件1
* @param file2 文件2 * @param file2 文件2
* @throws Exception * @throws Exception
*/ */
public void copyAllFile(String file1, String file2) throws Exception { public void copyAllFile(String file1, String file2) throws Exception {
File _file1 = new File(file1); File _file1 = new File(file1);
File _file2 = new File(file2); File _file2 = new File(file2);
if (!_file2.exists()) { if (!_file2.exists()) {
if (!_file1.isDirectory()) { if (!_file1.isDirectory()) {
_file2.createNewFile(); _file2.createNewFile();
} else { } else {
_file2.mkdirs(); _file2.mkdirs();
} }
} }
if (_file1.isDirectory()) { if (_file1.isDirectory()) {
for (File file : _file1.listFiles()) { for (File file : _file1.listFiles()) {
if (file.isDirectory()) { if (file.isDirectory()) {
copyAllFile(file.getAbsolutePath(), file2 + "/" + file.getName()); copyAllFile(file.getAbsolutePath(), file2 + "/" + file.getName());
} else { } else {
fileChannelCopy(file, new File(file2 + "/" + file.getName())); fileChannelCopy(file, new File(file2 + "/" + file.getName()));
} }
} }
} else { } else {
fileChannelCopy(_file1, _file2); fileChannelCopy(_file1, _file2);
} }
} }
@ -128,7 +127,7 @@ public class FileUtils {
* @param file1 文件1 * @param file1 文件1
* @param file2 文件2 * @param file2 文件2
*/ */
public void fileChannelCopy(File file1, File file2) { public void fileChannelCopy(File file1, File file2) {
FileInputStream fileIn = null; FileInputStream fileIn = null;
FileOutputStream fileOut = null; FileOutputStream fileOut = null;
FileChannel channelIn = null; FileChannel channelIn = null;
@ -143,7 +142,7 @@ public class FileUtils {
// //
} finally { } finally {
try { try {
fileIn.close(); fileIn.close();
channelIn.close(); channelIn.close();
fileOut.close(); fileOut.close();
channelOut.close(); channelOut.close();
@ -153,97 +152,97 @@ public class FileUtils {
} }
} }
/** /**
* 通过输入流读取文本 * 通过输入流读取文本
* *
* @param in * @param in
* @param size * @param size
* @param encode * @param encode
* @return * @return
*/ */
public static String getStringFromInputStream(InputStream in, int size, String encode) { public static String getStringFromInputStream(InputStream in, int size, String encode) {
try { try {
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[size]; byte[] b = new byte[size];
int i = 0; int i = 0;
while ((i = in.read(b)) > 0) { while ((i = in.read(b)) > 0) {
bos.write(b, 0, i); bos.write(b, 0, i);
} }
bos.close(); bos.close();
return new String(bos.toByteArray(), encode); return new String(bos.toByteArray(), encode);
} catch (IOException e) { } catch (IOException e) {
MsgUtils.warn("输入流读取出错: &4" + e.getMessage()); MsgUtils.warn("输入流读取出错: &4" + e.getMessage());
} }
return null; return null;
} }
/** /**
* 通过文件读取文本 * 通过文件读取文本
* *
* @param file * @param file
* @param size * @param size
* @param encode * @param encode
* @return * @return
*/ */
public static String getStringFromFile(File file, int size, String encode) { public static String getStringFromFile(File file, int size, String encode) {
try { try {
FileInputStream fin = new FileInputStream(file); FileInputStream fin = new FileInputStream(file);
BufferedInputStream bin = new BufferedInputStream(fin); BufferedInputStream bin = new BufferedInputStream(fin);
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[size]; byte[] b = new byte[size];
int i = 0; int i = 0;
while ((i = bin.read(b)) > 0) { while ((i = bin.read(b)) > 0) {
bos.write(b, 0, i); bos.write(b, 0, i);
} }
bos.close(); bos.close();
bin.close(); bin.close();
fin.close(); fin.close();
return new String(bos.toByteArray(), encode); return new String(bos.toByteArray(), encode);
} catch (IOException e) { } catch (IOException e) {
MsgUtils.warn("文件读取出错: &4" + e.getMessage()); MsgUtils.warn("文件读取出错: &4" + e.getMessage());
} }
return null; return null;
} }
/** /**
* 通过 URL 读取文本 * 通过 URL 读取文本
* *
* @param url * @param url
* @param size * @param size
* @return * @return
*/ */
public static String getStringFromURL(String url, int size) { public static String getStringFromURL(String url, int size) {
try { try {
URLConnection conn = new URL(url).openConnection(); URLConnection conn = new URL(url).openConnection();
BufferedInputStream bin = new BufferedInputStream(conn.getInputStream()); BufferedInputStream bin = new BufferedInputStream(conn.getInputStream());
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[size]; byte[] b = new byte[size];
int i = 0; int i = 0;
while ((i = bin.read(b)) > 0) { while ((i = bin.read(b)) > 0) {
bos.write(b, 0, i); bos.write(b, 0, i);
} }
bos.close(); bos.close();
bin.close(); bin.close();
return new String(bos.toByteArray(), conn.getContentEncoding() == null ? "UTF-8" : conn.getContentEncoding()); return new String(bos.toByteArray(), conn.getContentEncoding() == null ? "UTF-8" : conn.getContentEncoding());
} catch (IOException e) { } catch (IOException e) {
MsgUtils.warn("网络访问出错: &4" + e.getMessage()); MsgUtils.warn("网络访问出错: &4" + e.getMessage());
} }
return null; return null;
} }
public static String getStringFromURL(String url, String def) { public static String getStringFromURL(String url, String def) {
String s = getStringFromURL(url, 1024); String s = getStringFromURL(url, 1024);
return s == null ? def : s; return s == null ? def : s;
} }
/** /**
* 下载文件 * 下载文件
@ -253,61 +252,59 @@ public class FileUtils {
* @param saveDir * @param saveDir
*/ */
public static void download(String urlStr, String filename, File saveDir) { public static void download(String urlStr, String filename, File saveDir) {
try { try {
URL url = new URL(urlStr); URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 超时时间 // 超时时间
conn.setConnectTimeout(5 * 1000); conn.setConnectTimeout(5 * 1000);
// 防止屏蔽程序抓取而返回 403 错误 // 防止屏蔽程序抓取而返回 403 错误
conn.setRequestProperty("User-Agent", "Mozilla/31.0 (compatible; MSIE 10.0; Windows NT; DigExt)"); conn.setRequestProperty("User-Agent", "Mozilla/31.0 (compatible; MSIE 10.0; Windows NT; DigExt)");
// 得到输入流 // 得到输入流
InputStream inputStream = conn.getInputStream(); InputStream inputStream = conn.getInputStream();
// 获取数组 // 获取数组
byte[] data = read(inputStream); byte[] data = read(inputStream);
// 创建文件夹 // 创建文件夹
if (!saveDir.exists()) { if (!saveDir.exists()) {
saveDir.mkdirs(); saveDir.mkdirs();
} }
// 保存文件 // 保存文件
File file = new File(saveDir, filename); File file = new File(saveDir, filename);
FileOutputStream fos = new FileOutputStream(file); FileOutputStream fos = new FileOutputStream(file);
// 写入文件 // 写入文件
fos.write(data); fos.write(data);
// 结束 // 结束
fos.close(); fos.close();
inputStream.close(); inputStream.close();
} } catch (Exception e) {
catch (Exception e) { e.printStackTrace();
e.printStackTrace(); }
} }
}
public static byte[] read(InputStream in) { public static byte[] read(InputStream in) {
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
int len = 0; int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
try { try {
while((len = in.read(buffer)) != -1) { while ((len = in.read(buffer)) != -1) {
bos.write(buffer, 0, len); bos.write(buffer, 0, len);
} }
} } catch (Exception ignored) {
catch (Exception ignored) { }
} return bos.toByteArray();
return bos.toByteArray(); }
}
public static void close(Closeable closeable) { public static void close(Closeable closeable) {
try { try {
if (closeable != null) { if (closeable != null) {
closeable.close(); closeable.close();
} }
} catch (Exception ignored) { } catch (Exception ignored) {
} }
} }
} }

View File

@ -1,24 +1,20 @@
package me.skymc.taboolib.fileutils; 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.BufferedWriter;
import java.io.File; import java.io.File;
import java.io.FileWriter; import java.io.FileWriter;
import org.bukkit.plugin.Plugin;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.other.DateUtils;
@Deprecated @Deprecated
public class LogUtils { public class LogUtils {
public static void Log(String s, String s2) public static void Log(String s, String s2) {
{ try {
try File file = new File(Main.getInst().getDataFolder(), s2 + ".txt");
{ if (!file.exists()) {
File file = new File(Main.getInst().getDataFolder(), s2+".txt");
if(!file.exists())
{
file.createNewFile(); file.createNewFile();
} }
@ -27,32 +23,25 @@ public class LogUtils {
bufferWritter.write(s); bufferWritter.write(s);
bufferWritter.newLine(); bufferWritter.newLine();
bufferWritter.close(); bufferWritter.close();
} } catch (Exception e) {
catch (Exception e) Main.getInst().getLogger().warning(s2 + ":" + s);
{
Main.getInst().getLogger().warning(s2+":"+s);
} }
} }
public static void newLog(Plugin main, String s, String s2) public static void newLog(Plugin main, String s, String s2) {
{ try {
try File file = new File(main.getDataFolder(), s2 + ".txt");
{ if (!file.exists()) {
File file = new File(main.getDataFolder(), s2+".txt");
if(!file.exists())
{
file.createNewFile(); file.createNewFile();
} }
FileWriter fileWritter = new FileWriter(file, true); FileWriter fileWritter = new FileWriter(file, true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter); 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.newLine();
bufferWritter.close(); bufferWritter.close();
} } catch (Exception e) {
catch (Exception e) Main.getInst().getLogger().warning(s2 + ":" + s);
{
Main.getInst().getLogger().warning(s2+":"+s);
} }
} }

View File

@ -1,20 +1,19 @@
package me.skymc.taboolib.inventory; package me.skymc.taboolib.inventory;
import me.skymc.taboolib.other.NumberUtils;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Item; import org.bukkit.entity.Item;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector; import org.bukkit.util.Vector;
import me.skymc.taboolib.other.NumberUtils;
public class DropUtils { public class DropUtils {
public static Item drop(Player player, ItemStack itemStack, double bulletSpread, double radius) { public static Item drop(Player player, ItemStack itemStack, double bulletSpread, double radius) {
Location location = player.getLocation(); Location location = player.getLocation();
location.setY(location.getY() + 1.5); location.setY(location.getY() + 1.5);
Item item = player.getWorld().dropItem(location, itemStack); Item item = player.getWorld().dropItem(location, itemStack);
double yaw = Math.toRadians(-player.getLocation().getYaw() - 90.0F); double yaw = Math.toRadians(-player.getLocation().getYaw() - 90.0F);
double pitch = Math.toRadians(-player.getLocation().getPitch()); double pitch = Math.toRadians(-player.getLocation().getPitch());
@ -24,17 +23,16 @@ public class DropUtils {
double z = 0; double z = 0;
if (bulletSpread > 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++) { 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]; x = Math.cos(pitch) * Math.cos(yaw) + spread[0];
y = Math.sin(pitch) + spread[1]; y = Math.sin(pitch) + spread[1];
z = -Math.sin(yaw) * Math.cos(pitch) + spread[2]; z = -Math.sin(yaw) * Math.cos(pitch) + spread[2];
} } else {
else { x = Math.cos(pitch) * Math.cos(yaw);
x = Math.cos(pitch) * Math.cos(yaw);
y = Math.sin(pitch); y = Math.sin(pitch);
z = -Math.sin(yaw) * Math.cos(pitch); z = -Math.sin(yaw) * Math.cos(pitch);
} }
@ -43,6 +41,6 @@ public class DropUtils {
item.setVelocity(dirVel); item.setVelocity(dirVel);
return item; return item;
} }
} }

View File

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

View File

@ -1,10 +1,16 @@
package me.skymc.taboolib.inventory; package me.skymc.taboolib.inventory;
import java.io.File; import me.clip.placeholderapi.PlaceholderAPI;
import java.util.ArrayList; import me.skymc.taboolib.Main;
import java.util.LinkedHashMap; import me.skymc.taboolib.TabooLib;
import java.util.List; 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.Color;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
@ -21,133 +27,142 @@ import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType; import org.bukkit.potion.PotionEffectType;
import lombok.Getter; import java.io.File;
import me.clip.placeholderapi.PlaceholderAPI; import java.util.*;
import me.skymc.taboolib.Main; import java.util.stream.IntStream;
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;
public class ItemUtils { public class ItemUtils {
@Getter private static FileConfiguration itemdir = null;
private static FileConfiguration itemdir = null;
@Getter private static FileConfiguration itemCache = null;
private static FileConfiguration itemCache = null;
@Getter private static File finalItemsFolder;
private static File finalItemsFolder;
@Getter private static LinkedHashMap<String, String> itemlib = new LinkedHashMap<>();
private static LinkedHashMap<String, String> itemlib = new LinkedHashMap<>();
@Getter private static LinkedHashMap<String, ItemStack> itemCaches = new LinkedHashMap<>();
private static LinkedHashMap<String, ItemStack> itemCaches = new LinkedHashMap<>();
@Getter private static LinkedHashMap<String, ItemStack> itemCachesFinal = new LinkedHashMap<>();
private static LinkedHashMap<String, ItemStack> itemCachesFinal = new LinkedHashMap<>();
/** public static FileConfiguration getItemdir() {
* 获取物品缓存 return itemdir;
* 检测顺序 }
* 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) { public static FileConfiguration getItemCache() {
return itemCachesFinal.containsKey(name) || itemCaches.containsKey(name); return itemCache;
} }
public static void LoadLib() { public static File getFinalItemsFolder() {
try { return finalItemsFolder;
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) { public static LinkedHashMap<String, String> getItemlib() {
FileConfiguration conf = ConfigUtils.load(Main.getInst(), file); return itemlib;
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() { public static LinkedHashMap<String, ItemStack> getItemCaches() {
itemCaches.clear(); return itemCaches;
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() { public static LinkedHashMap<String, ItemStack> getItemCachesFinal() {
FileConfiguration conf = new Language("ITEM_NAME", Main.getInst(), true).getConfiguration(); return itemCachesFinal;
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); * 1. 固定物品库
} * 2. 动态物品库
return itemCacheFile; *
} * @param name 物品名称
* @return
*/
public static ItemStack getCacheItem(String name) {
// 检测固定物品库是否存在该物品
if (itemCachesFinal.containsKey(name)) {
return itemCachesFinal.get(name);
}
// 返回动态物品库
return itemCaches.get(name);
}
public static String getCustomName(ItemStack item) { public static boolean isExists(String name) {
if (item == null || item.getType().equals(Material.AIR)) { return itemCachesFinal.containsKey(name) || itemCaches.containsKey(name);
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) { public static void LoadLib() {
if (itemdir != null) { try {
return itemdir.getItemStack("item." + name); reloadItemName();
} reloadItemCache();
return null; itemdir = YamlConfiguration.loadConfiguration(new File(Main.getInst().getConfig().getString("DATAURL.ITEMDIR")));
} } catch (Exception e) {
MsgUtils.warn("物品库载入失败: &4" + e.getMessage());
}
}
@SuppressWarnings("deprecation") 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) { public static ItemStack item(int n, int a, int d) {
return new ItemStack(n, a, (short) d); return new ItemStack(n, a, (short) d);
} }
@ -174,7 +189,7 @@ public class ItemUtils {
} }
public static boolean isNull(ItemStack item) { 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) { public static boolean isName(ItemStack i, String a) {
@ -186,68 +201,61 @@ public class ItemUtils {
} }
public static String asString(String args, Player placeholderPlayer) { public static String asString(String args, Player placeholderPlayer) {
if (placeholderPlayer == null) { if (placeholderPlayer == null) {
return args.replace("&", "§"); return args.replace("&", "§");
} }
return PlaceholderAPI.setPlaceholders(placeholderPlayer, args.replace("&", "§")); return PlaceholderAPI.setPlaceholders(placeholderPlayer, args.replace("&", "§"));
} }
public static List<String> asString(List<String> args, Player placeholderPlayer) { public static List<String> asString(List<String> args, Player placeholderPlayer) {
for (int i = 0 ; i < args.size() ; i ++) { IntStream.range(0, args.size()).forEach(i -> args.set(i, asString(args.get(i), placeholderPlayer)));
args.set(i, asString(args.get(i), placeholderPlayer)); return args;
}
return args;
} }
public static ItemFlag asItemFlag(String flag) { public static ItemFlag asItemFlag(String flag) {
try { try {
return ItemFlag.valueOf(flag); return ItemFlag.valueOf(flag);
} } catch (Exception e) {
catch (Exception e) { return null;
return null; }
}
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public static Material asMaterial(String args) { public static Material asMaterial(String args) {
try { try {
Material material = Material.getMaterial(args); Material material = Material.getMaterial(args);
return material != null ? material : Material.getMaterial(Integer.valueOf(args)); return material != null ? material : Material.getMaterial(Integer.valueOf(args));
} } catch (Exception e) {
catch (Exception e) { return Material.STONE;
return Material.STONE; }
} }
}
@SuppressWarnings({ "deprecation" }) @SuppressWarnings({"deprecation"})
public static Enchantment asEnchantment(String enchant) { public static Enchantment asEnchantment(String enchant) {
try { try {
Enchantment enchantment = Enchantment.getByName(enchant); Enchantment enchantment = Enchantment.getByName(enchant);
return enchantment != null ? enchantment : Enchantment.getById(Integer.valueOf(enchant)); return enchantment != null ? enchantment : Enchantment.getById(Integer.valueOf(enchant));
} } catch (Exception e) {
catch (Exception e) { return null;
return null; }
}
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public static PotionEffectType asPotionEffectType(String potion) { public static PotionEffectType asPotionEffectType(String potion) {
try { try {
PotionEffectType type = PotionEffectType.getByName(potion); PotionEffectType type = PotionEffectType.getByName(potion);
return type != null ? type : PotionEffectType.getById(Integer.valueOf(potion)); return type != null ? type : PotionEffectType.getById(Integer.valueOf(potion));
} } catch (Exception e) {
catch (Exception e) { return null;
return null; }
}
} }
public static Color asColor(String color) { public static Color asColor(String color) {
try { try {
return Color.fromBGR(Integer.valueOf(color.split("-")[0]), Integer.valueOf(color.split("-")[1]), Integer.valueOf(color.split("-")[2])); return Color.fromBGR(Integer.valueOf(color.split("-")[0]), Integer.valueOf(color.split("-")[1]), Integer.valueOf(color.split("-")[2]));
} } catch (Exception e) {
catch (Exception e) { return Color.fromBGR(0, 0, 0);
return Color.fromBGR(0, 0, 0); }
}
} }
public static String asAttribute(String name) { public static String asAttribute(String name) {
@ -267,7 +275,7 @@ public class ItemUtils {
case "luck": case "luck":
return "generic.luck"; return "generic.luck";
} }
return null; return null;
} }
/** /**
@ -296,21 +304,21 @@ public class ItemUtils {
* @param i * @param i
* @return * @return
*/ */
public static boolean isNamed(ItemStack i) { public static boolean isNamed(ItemStack i) {
return i != null && i.getItemMeta() != null && i.getItemMeta().getDisplayName() != null; return i != null && i.getItemMeta() != null && i.getItemMeta().getDisplayName() != null;
} }
/** /**
* 添加描述 * 添加描述
* *
* @param is 物品 * @param is 物品
* @param lore 描述 * @param lore 描述
*/ */
public static ItemStack addLore(ItemStack is, String lore) { public static ItemStack addLore(ItemStack is, String lore) {
ItemMeta meta = is.getItemMeta(); ItemMeta meta = is.getItemMeta();
List<String> _lore = meta.hasLore() ? meta.getLore() : new ArrayList<>(); List<String> _lore = meta.hasLore() ? meta.getLore() : Collections.emptyList();
_lore.add(lore.replaceAll("&", "§")); _lore.add(lore.replaceAll("&", "§"));
is.setItemMeta(meta); is.setItemMeta(meta);
return is; return is;
@ -319,18 +327,18 @@ public class ItemUtils {
/** /**
* 移除描述 * 移除描述
* *
* @param is 物品 * @param is 物品
* @param line 行数 * @param line 行数
*/ */
public static ItemStack delLore(ItemStack is, int line) { public static ItemStack delLore(ItemStack is, int line) {
ItemMeta meta = is.getItemMeta(); ItemMeta meta = is.getItemMeta();
if (meta.hasLore()) { if (meta.hasLore()) {
List<String> l = meta.getLore(); List<String> l = meta.getLore();
if (l.size() >= line) { if (l.size() >= line) {
l.remove(line); l.remove(line);
meta.setLore(l); meta.setLore(l);
is.setItemMeta(meta); is.setItemMeta(meta);
} }
} }
return is; return is;
} }
@ -342,14 +350,7 @@ public class ItemUtils {
* @param a 关键字 * @param a 关键字
*/ */
public static int getLore(ItemStack i, String a) { public static int getLore(ItemStack i, String a) {
if (isLored(i)) { return isLored(i) ? IntStream.range(0, i.getItemMeta().getLore().size()).filter(j -> i.getItemMeta().getLore().get(j).contains(a)).findFirst().orElse(0) : 0;
for (int j = 0; j < i.getItemMeta().getLore().size() ; j++) {
if (i.getItemMeta().getLore().get(j).contains(a)) {
return j;
}
}
}
return 0;
} }
/** /**
@ -359,228 +360,212 @@ public class ItemUtils {
* @param d 耐久 * @param d 耐久
*/ */
public static ItemStack addDurability(ItemStack i, int d) { public static ItemStack addDurability(ItemStack i, int d) {
i.setDurability((short) (i.getDurability() + d)); i.setDurability((short) (i.getDurability() + d));
int min = i.getDurability(); int min = i.getDurability();
int max = i.getType().getMaxDurability(); int max = i.getType().getMaxDurability();
if (min >= max) { if (min >= max) {
i.setType(Material.AIR); i.setType(Material.AIR);
} }
return i; return i;
} }
/** /**
* 替换描述 * 替换描述
* *
* @param i 物品 * @param i 物品
* @param l1 关键字1 * @param l1 关键字1
* @param l2 关键字2 * @param l2 关键字2
*/ */
public static ItemStack repalceLore(ItemStack i, String l1, String l2) { public static ItemStack repalceLore(ItemStack i, String l1, String l2) {
if (!isLored(i)) { if (!isLored(i)) {
return i; return i;
} } else {
else { ItemMeta meta = i.getItemMeta();
ItemMeta meta = i.getItemMeta(); List<String> lore = meta.getLore();
List<String> lore = meta.getLore(); IntStream.range(0, lore.size()).forEach(j -> lore.set(j, lore.get(j).replace(l1, l2)));
for (int j = 0 ; j < lore.size() ; j++) { meta.setLore(lore);
lore.set(j, lore.get(j).replace(l1, l2)); i.setItemMeta(meta);
} }
meta.setLore(lore); return i;
i.setItemMeta(meta);
}
return i;
} }
public static ItemStack loadItem(FileConfiguration f, String s) { 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) { 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) { public static ItemStack loadItem(ConfigurationSection section, Player papiPlayer) {
if (section.get("bukkit") instanceof ItemStack) { if (section.get("bukkit") instanceof ItemStack) {
return section.getItemStack("bukkit"); return section.getItemStack("bukkit");
} }
// 材质 // 材质
ItemStack item = new ItemStack(asMaterial(section.get("material").toString())); ItemStack item = new ItemStack(asMaterial(section.get("material").toString()));
// 数量 // 数量
item.setAmount(section.contains("amount") ? section.getInt("amount") : 1); item.setAmount(section.contains("amount") ? section.getInt("amount") : 1);
// 耐久 // 耐久
item.setDurability((short) section.getInt("data")); item.setDurability((short) section.getInt("data"));
// 元数据 // 元数据
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
// 展示名 // 展示名
if (section.contains("name")) { if (section.contains("name")) {
meta.setDisplayName(asString(section.getString("name"), papiPlayer)); meta.setDisplayName(asString(section.getString("name"), papiPlayer));
} }
// 描述 // 描述
if (section.contains("lore")) { if (section.contains("lore")) {
meta.setLore(asString(section.getStringList("lore"), papiPlayer)); meta.setLore(asString(section.getStringList("lore"), papiPlayer));
} }
// 附魔 // 附魔
if (section.contains("enchants")) { if (section.contains("enchants")) {
for (String preEnchant : section.getConfigurationSection("enchants").getKeys(false)) { for (String preEnchant : section.getConfigurationSection("enchants").getKeys(false)) {
Enchantment enchant = asEnchantment(preEnchant); Enchantment enchant = asEnchantment(preEnchant);
if (enchant != null) { if (enchant != null) {
meta.addEnchant(enchant, section.getInt("enchants." + preEnchant), true); meta.addEnchant(enchant, section.getInt("enchants." + preEnchant), true);
} } else {
else { MsgUtils.warn("&8" + preEnchant + " &c不是一个有效的附魔名称");
MsgUtils.warn("&8" + preEnchant + " &c不是一个有效的附魔名称"); MsgUtils.warn("&c输入 &4/taboolib enchants&c 查看所有附魔");
MsgUtils.warn("&c输入 &4/taboolib enchants&c 查看所有附魔"); }
} }
} }
} // 标签
// 标签 if (section.contains("flags") && TabooLib.getVerint() > 10700) {
if (section.contains("flags") && TabooLib.getVerint() > 10700) { for (String preFlag : section.getStringList("flags")) {
for (String preFlag : section.getStringList("flags")) { ItemFlag flag = asItemFlag(preFlag);
ItemFlag flag = asItemFlag(preFlag); if (flag != null) {
if (flag != null) { meta.addItemFlags(flag);
meta.addItemFlags(flag); } else {
} MsgUtils.warn("&8" + preFlag + " &c不是一个有效的标签名称");
else { MsgUtils.warn("&c输入 &4/taboolib flags&c 查看所有标签");
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 LeatherArmorMeta && section.contains("color")) { }
((LeatherArmorMeta) meta).setColor(asColor(section.getString("color"))); // 药水
} if (meta instanceof PotionMeta && section.contains("potions")) {
// 药水 PotionMeta potionMeta = (PotionMeta) meta;
if (meta instanceof PotionMeta && section.contains("potions")) { for (String prePotionName : section.getConfigurationSection("potions").getKeys(false)) {
PotionMeta potionMeta = (PotionMeta) meta; PotionEffectType potionEffectType = asPotionEffectType(prePotionName);
for (String prePotionName : section.getConfigurationSection("potions").getKeys(false)) { if (potionEffectType != null) {
PotionEffectType potionEffectType = asPotionEffectType(prePotionName); potionMeta.addCustomEffect(new PotionEffect(
if (potionEffectType != null) { potionEffectType,
potionMeta.addCustomEffect(new PotionEffect( NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[0]),
potionEffectType, NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[1]) - 1), true);
NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[0]), } else {
NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[1]) - 1), true); MsgUtils.warn("&8" + prePotionName + " &c不是一个有效的药水名称");
} MsgUtils.warn("&c输入 &4/taboolib potions&c 查看所有药水");
else { }
MsgUtils.warn("&8" + potionEffectType + " &c不是一个有效的药水名称"); }
MsgUtils.warn("&c输入 &4/taboolib potions&c 查看所有药水"); }
} // 元数据
} item.setItemMeta(meta);
} // 数据
// 元数据 NBTItem nbt = new NBTItem(item);
item.setItemMeta(meta); // 物品标签
// 数据 if (section.contains("nbt")) {
NBTItem nbt = new NBTItem(item); for (String name : section.getConfigurationSection("nbt").getKeys(false)) {
// 物品标签 Object obj = section.get("nbt." + name);
if (section.contains("nbt")) { if (obj instanceof String) {
for (String name : section.getConfigurationSection("nbt").getKeys(false)) { nbt.setString(name, obj.toString());
Object obj = section.get("nbt." + name); } else if (obj instanceof Double) {
if (obj instanceof String) { nbt.setDouble(name, Double.valueOf(obj.toString()));
nbt.setString(name, obj.toString()); } else if (obj instanceof Integer) {
} nbt.setInteger(name, Integer.valueOf(obj.toString()));
else if (obj instanceof Double) { } else if (obj instanceof Long) {
nbt.setDouble(name, Double.valueOf(obj.toString())); nbt.setLong(name, Long.valueOf(obj.toString()));
} } else {
else if (obj instanceof Integer) { nbt.setObject(name, obj);
nbt.setInteger(name, Integer.valueOf(obj.toString())); }
} }
else if (obj instanceof Long) { }
nbt.setLong(name, Long.valueOf(obj.toString())); // 物品属性
} if (section.contains("attributes")) {
else { NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound);
nbt.setObject(name, obj); 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();
if (section.contains("attributes")) { Object num = section.get("attributes." + hand + "." + name);
NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound); if (num.toString().contains("%")) {
for (String hand : section.getConfigurationSection("attributes").getKeys(false)) { _attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D);
for (String name : section.getConfigurationSection("attributes." + hand).getKeys(false)) { _attr.setInteger("Operation", 1);
if (asAttribute(name) != null) { } else {
try { _attr.setDouble("Amount", Double.valueOf(num.toString()));
NBTListCompound _attr = attr.addCompound(); _attr.setInteger("Operation", 0);
Object num = section.get("attributes." + hand + "." + name); }
if (num.toString().contains("%")) { _attr.setString("AttributeName", asAttribute(name));
_attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D); _attr.setInteger("UUIDMost", NumberUtils.getRand().nextInt(Integer.MAX_VALUE));
_attr.setInteger("Operation", 1); _attr.setInteger("UUIDLeast", NumberUtils.getRand().nextInt(Integer.MAX_VALUE));
} _attr.setString("Name", asAttribute(name));
else { if (!hand.equals("all")) {
_attr.setDouble("Amount", Double.valueOf(num.toString())); _attr.setString("Slot", hand);
_attr.setInteger("Operation", 0); }
} } catch (Exception e) {
_attr.setString("AttributeName", asAttribute(name)); MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage());
_attr.setInteger("UUIDMost", NumberUtils.getRand().nextInt(Integer.MAX_VALUE)); }
_attr.setInteger("UUIDLeast", NumberUtils.getRand().nextInt(Integer.MAX_VALUE)); } else {
_attr.setString("Name", asAttribute(name)); MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称");
if (!hand.equals("all")) { MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性");
_attr.setString("Slot", hand); }
} }
} }
catch (Exception e) { }
MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage()); return nbt.getItem();
}
}
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) { public static NBTItem setAttribute(NBTItem nbt, String name, Object num, String hand) {
NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound); NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound);
if (asAttribute(name) != null) { if (asAttribute(name) != null) {
try { try {
NBTListCompound _attr = null; NBTListCompound _attr = null;
for (int i = 0 ; i < attr.size() ; i++) { for (int i = 0; i < attr.size(); i++) {
NBTListCompound nlc = attr.getCompound(i); NBTListCompound nlc = attr.getCompound(i);
if (nlc.getString("AttributeName").equals(asAttribute(name))) { if (nlc.getString("AttributeName").equals(asAttribute(name))) {
_attr = nlc; _attr = nlc;
} }
} }
if (_attr == null) { if (_attr == null) {
_attr = attr.addCompound(); _attr = attr.addCompound();
} }
if (num.toString().contains("%")) { if (num.toString().contains("%")) {
_attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D); _attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D);
_attr.setInteger("Operation", 1); _attr.setInteger("Operation", 1);
} } else {
else { _attr.setDouble("Amount", Double.valueOf(num.toString()));
_attr.setDouble("Amount", Double.valueOf(num.toString())); _attr.setInteger("Operation", 0);
_attr.setInteger("Operation", 0); }
} _attr.setString("AttributeName", asAttribute(name));
_attr.setString("AttributeName", asAttribute(name)); _attr.setInteger("UUIDMost", NumberUtils.getRand().nextInt(Integer.MAX_VALUE));
_attr.setInteger("UUIDMost", NumberUtils.getRand().nextInt(Integer.MAX_VALUE)); _attr.setInteger("UUIDLeast", NumberUtils.getRand().nextInt(Integer.MAX_VALUE));
_attr.setInteger("UUIDLeast", NumberUtils.getRand().nextInt(Integer.MAX_VALUE)); _attr.setString("Name", asAttribute(name));
_attr.setString("Name", asAttribute(name)); if (!hand.equals("all")) {
if (!hand.equals("all")) { _attr.setString("Slot", hand);
_attr.setString("Slot", hand); }
} } catch (Exception e) {
} MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage());
catch (Exception e) { }
MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage()); } else {
} MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称");
} MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性");
else { }
MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称"); return nbt;
MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性");
}
return nbt;
} }
@Deprecated @Deprecated
public static void putO(ItemStack item, Inventory inv, int i) { public static void putO(ItemStack item, Inventory inv, int i) {
inv.setItem(i, item); inv.setItem(i, item);
inv.setItem(i+1, item); inv.setItem(i + 1, item);
inv.setItem(i+2, item); inv.setItem(i + 2, item);
inv.setItem(i+9, item); inv.setItem(i + 9, item);
inv.setItem(i+10, null); inv.setItem(i + 10, null);
inv.setItem(i+11, item); inv.setItem(i + 11, item);
inv.setItem(i+18, item); inv.setItem(i + 18, item);
inv.setItem(i+19, item); inv.setItem(i + 19, item);
inv.setItem(i+20, item); inv.setItem(i + 20, item);
} }
} }

View File

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

View File

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

View File

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

View File

@ -12,12 +12,12 @@ public class NBTItem extends NBTCompound {
} }
@Override @Override
protected Object getCompound() { protected Object getCompound() {
return NBTReflectionUtil.getItemRootNBTTagCompound(NBTReflectionUtil.getNMSItemStack(bukkitItem)); return NBTReflectionUtil.getItemRootNBTTagCompound(NBTReflectionUtil.getNMSItemStack(bukkitItem));
} }
@Override @Override
protected void setCompound(Object compound) { protected void setCompound(Object compound) {
bukkitItem = NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.setNBTTag(compound, NBTReflectionUtil.getNMSItemStack(bukkitItem))); bukkitItem = NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.setNBTTag(compound, NBTReflectionUtil.getNMSItemStack(bukkitItem)));
} }
@ -29,11 +29,11 @@ public class NBTItem extends NBTCompound {
bukkitItem = item; bukkitItem = item;
} }
public static NBTContainer convertItemtoNBT(ItemStack item){ public static NBTContainer convertItemtoNBT(ItemStack item) {
return NBTReflectionUtil.convertNMSItemtoNBTCompound(NBTReflectionUtil.getNMSItemStack(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)); return NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.convertNBTCompoundtoNMSItem(comp));
} }

View File

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

View File

@ -1,10 +1,10 @@
package me.skymc.taboolib.itemnbtapi; package me.skymc.taboolib.itemnbtapi;
import me.skymc.taboolib.message.MsgUtils;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import me.skymc.taboolib.message.MsgUtils;
public class NBTListCompound { public class NBTListCompound {
private NBTList owner; private NBTList owner;
@ -24,7 +24,7 @@ public class NBTListCompound {
compound.getClass().getMethod("setString", String.class, String.class).invoke(compound, key, value); compound.getClass().getMethod("setString", String.class, String.class).invoke(compound, key, value);
owner.save(); owner.save();
} catch (Exception ex) { } 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); compound.getClass().getMethod("setInt", String.class, int.class).invoke(compound, key, value);
owner.save(); owner.save();
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
} }
@ -41,7 +41,7 @@ public class NBTListCompound {
try { try {
return (int) compound.getClass().getMethod("getInt", String.class).invoke(compound, value); return (int) compound.getClass().getMethod("getInt", String.class).invoke(compound, value);
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
return 0; return 0;
} }
@ -51,7 +51,7 @@ public class NBTListCompound {
compound.getClass().getMethod("setDouble", String.class, double.class).invoke(compound, key, value); compound.getClass().getMethod("setDouble", String.class, double.class).invoke(compound, key, value);
owner.save(); owner.save();
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
} }
@ -59,7 +59,7 @@ public class NBTListCompound {
try { try {
return (double) compound.getClass().getMethod("getDouble", String.class).invoke(compound, key); return (double) compound.getClass().getMethod("getDouble", String.class).invoke(compound, key);
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
return 0; return 0;
} }
@ -69,7 +69,7 @@ public class NBTListCompound {
try { try {
return (String) compound.getClass().getMethod("getString", String.class).invoke(compound, key); return (String) compound.getClass().getMethod("getString", String.class).invoke(compound, key);
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
return ""; return "";
} }
@ -78,7 +78,7 @@ public class NBTListCompound {
try { try {
return (boolean) compound.getClass().getMethod("hasKey", String.class).invoke(compound, key); return (boolean) compound.getClass().getMethod("hasKey", String.class).invoke(compound, key);
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
return false; return false;
} }
@ -88,7 +88,7 @@ public class NBTListCompound {
try { try {
return (Set<String>) compound.getClass().getMethod("c").invoke(compound); return (Set<String>) compound.getClass().getMethod("c").invoke(compound);
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
return new HashSet<>(); return new HashSet<>();
} }
@ -97,7 +97,7 @@ public class NBTListCompound {
try { try {
compound.getClass().getMethod("remove", String.class).invoke(compound, key); compound.getClass().getMethod("remove", String.class).invoke(compound, key);
} catch (Exception ex) { } 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; 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.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.InputStream; import java.io.InputStream;
@ -8,16 +17,6 @@ import java.lang.reflect.Method;
import java.util.Set; import java.util.Set;
import java.util.Stack; 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 // TODO: finish codestyle cleanup -sgdc3
public class NBTReflectionUtil { public class NBTReflectionUtil {
@ -29,7 +28,7 @@ public class NBTReflectionUtil {
try { try {
return Class.forName("org.bukkit.craftbukkit." + version + ".inventory.CraftItemStack"); return Class.forName("org.bukkit.craftbukkit." + version + ".inventory.CraftItemStack");
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null; return null;
} }
} }
@ -39,7 +38,7 @@ public class NBTReflectionUtil {
try { try {
return Class.forName("org.bukkit.craftbukkit." + version + ".entity.CraftEntity"); return Class.forName("org.bukkit.craftbukkit." + version + ".entity.CraftEntity");
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null; return null;
} }
} }
@ -49,7 +48,7 @@ public class NBTReflectionUtil {
try { try {
return Class.forName("net.minecraft.server." + version + ".NBTBase"); return Class.forName("net.minecraft.server." + version + ".NBTBase");
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null; return null;
} }
} }
@ -60,7 +59,7 @@ public class NBTReflectionUtil {
return Class.forName("net.minecraft.server." + version + ".NBTTagString"); return Class.forName("net.minecraft.server." + version + ".NBTTagString");
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null; return null;
} }
} }
@ -71,7 +70,7 @@ public class NBTReflectionUtil {
return Class.forName("net.minecraft.server." + version + ".ItemStack"); return Class.forName("net.minecraft.server." + version + ".ItemStack");
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null; return null;
} }
} }
@ -82,7 +81,7 @@ public class NBTReflectionUtil {
return Class.forName("net.minecraft.server." + version + ".NBTTagCompound"); return Class.forName("net.minecraft.server." + version + ".NBTTagCompound");
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null; return null;
} }
} }
@ -93,7 +92,7 @@ public class NBTReflectionUtil {
return Class.forName("net.minecraft.server." + version + ".NBTCompressedStreamTools"); return Class.forName("net.minecraft.server." + version + ".NBTCompressedStreamTools");
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null; return null;
} }
} }
@ -104,7 +103,7 @@ public class NBTReflectionUtil {
return Class.forName("net.minecraft.server." + version + ".MojangsonParser"); return Class.forName("net.minecraft.server." + version + ".MojangsonParser");
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null; return null;
} }
} }
@ -115,7 +114,7 @@ public class NBTReflectionUtil {
return Class.forName("net.minecraft.server." + version + ".TileEntity"); return Class.forName("net.minecraft.server." + version + ".TileEntity");
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null; return null;
} }
} }
@ -126,7 +125,7 @@ public class NBTReflectionUtil {
return Class.forName("org.bukkit.craftbukkit." + version + ".CraftWorld"); return Class.forName("org.bukkit.craftbukkit." + version + ".CraftWorld");
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null; return null;
} }
} }
@ -139,7 +138,7 @@ public class NBTReflectionUtil {
return c.newInstance(); return c.newInstance();
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null; return null;
} }
} }
@ -152,7 +151,7 @@ public class NBTReflectionUtil {
return clazz.getConstructor(int.class, int.class, int.class).newInstance(x, y, z); return clazz.getConstructor(int.class, int.class, int.class).newInstance(x, y, z);
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
return null; return null;
} }
} }
@ -164,7 +163,7 @@ public class NBTReflectionUtil {
method.invoke(NMSItem, NBTTag); method.invoke(NMSItem, NBTTag);
return NMSItem; return NMSItem;
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
return null; return null;
} }
@ -178,7 +177,7 @@ public class NBTReflectionUtil {
method = clazz.getMethod("asNMSCopy", ItemStack.class); method = clazz.getMethod("asNMSCopy", ItemStack.class);
return method.invoke(clazz, item); return method.invoke(clazz, item);
} catch (Exception e) { } catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
} }
return null; return null;
} }
@ -192,7 +191,7 @@ public class NBTReflectionUtil {
method = clazz.getMethod("getHandle"); method = clazz.getMethod("getHandle");
return method.invoke(getCraftEntity().cast(entity)); return method.invoke(getCraftEntity().cast(entity));
} catch (Exception e) { } catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
} }
return null; return null;
} }
@ -206,7 +205,7 @@ public class NBTReflectionUtil {
method = cis.getMethod("parse", String.class); method = cis.getMethod("parse", String.class);
return method.invoke(null, json); return method.invoke(null, json);
} catch (Exception e) { } catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
} }
return null; return null;
} }
@ -220,7 +219,7 @@ public class NBTReflectionUtil {
method = clazz.getMethod("a", InputStream.class); method = clazz.getMethod("a", InputStream.class);
return method.invoke(clazz, stream); return method.invoke(clazz, stream);
} catch (Exception e) { } catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
} }
return null; return null;
} }
@ -234,7 +233,7 @@ public class NBTReflectionUtil {
method = clazz.getMethod("a", getNBTTagCompound(), OutputStream.class); method = clazz.getMethod("a", getNBTTagCompound(), OutputStream.class);
return method.invoke(clazz, nbt, stream); return method.invoke(clazz, nbt, stream);
} catch (Exception e) { } catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
} }
return null; return null;
} }
@ -249,7 +248,7 @@ public class NBTReflectionUtil {
Object answer = method.invoke(clazz, item); Object answer = method.invoke(clazz, item);
return (ItemStack) answer; return (ItemStack) answer;
} catch (Exception e) { } catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
} }
return null; return null;
} }
@ -263,7 +262,7 @@ public class NBTReflectionUtil {
method = clazz.getMethod("getTag"); method = clazz.getMethod("getTag");
return method.invoke(nmsitem); return method.invoke(nmsitem);
} catch (Exception e) { } catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
} }
return null; return null;
} }
@ -275,7 +274,7 @@ public class NBTReflectionUtil {
try { try {
return clazz.getConstructor(getNBTTagCompound()).newInstance(nbtcompound.getCompound()); return clazz.getConstructor(getNBTTagCompound()).newInstance(nbtcompound.getCompound());
} catch (Exception e) { } catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
} }
return null; return null;
} }
@ -290,7 +289,7 @@ public class NBTReflectionUtil {
Object answer = method.invoke(nmsitem, getNewNBTTag()); Object answer = method.invoke(nmsitem, getNewNBTTag());
return new NBTContainer(answer); return new NBTContainer(answer);
} catch (Exception e) { } catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
} }
return null; return null;
} }
@ -308,7 +307,7 @@ public class NBTReflectionUtil {
answer = nbt; answer = nbt;
return answer; return answer;
} catch (Exception e) { } catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
} }
return null; return null;
} }
@ -320,7 +319,7 @@ public class NBTReflectionUtil {
method.invoke(NMSItem, NBTTag); method.invoke(NMSItem, NBTTag);
return NMSItem; return NMSItem;
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
return null; return null;
} }
@ -339,7 +338,7 @@ public class NBTReflectionUtil {
answer = tag; answer = tag;
return answer; return answer;
} catch (Exception e) { } catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
} }
return null; return null;
} }
@ -354,7 +353,7 @@ public class NBTReflectionUtil {
method = getTileEntity().getMethod("a", getNBTTagCompound()); method = getTileEntity().getMethod("a", getNBTTagCompound());
method.invoke(o, comp); method.invoke(o, comp);
} catch (Exception e) { } 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); method = c.getMethod("getCompound", String.class);
return method.invoke(compound, name); return method.invoke(compound, name);
} catch (Exception e) { } catch (Exception e) {
MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + e.getMessage());
} }
return null; return null;
} }
@ -390,7 +389,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, name, getNBTTagCompound().newInstance()); method.invoke(workingtag, name, getNBTTagCompound().newInstance());
comp.setCompound(nbttag); comp.setCompound(nbttag);
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
} }
@ -430,7 +429,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, nbtcompound.getCompound()); method.invoke(workingtag, nbtcompound.getCompound());
comp.setCompound(rootnbttag); comp.setCompound(rootnbttag);
} catch (Exception ex) { } 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); method.invoke(workingtag, key, text);
comp.setCompound(rootnbttag); comp.setCompound(rootnbttag);
} catch (Exception ex) { } 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); method = workingtag.getClass().getMethod("getString", String.class);
return (String) method.invoke(workingtag, key); return (String) method.invoke(workingtag, key);
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
return null; return null;
} }
@ -484,7 +483,7 @@ public class NBTReflectionUtil {
method = workingtag.getClass().getMethod("get", String.class); method = workingtag.getClass().getMethod("get", String.class);
return method.invoke(workingtag, key).toString(); return method.invoke(workingtag, key).toString();
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
return null; return null;
} }
@ -506,7 +505,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, key, i); method.invoke(workingtag, key, i);
comp.setCompound(rootnbttag); comp.setCompound(rootnbttag);
} catch (Exception ex) { } 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); method = workingtag.getClass().getMethod("getInt", String.class);
return (Integer) method.invoke(workingtag, key); return (Integer) method.invoke(workingtag, key);
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
return null; return null;
} }
@ -544,7 +543,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, key, b); method.invoke(workingtag, key, b);
comp.setCompound(rootnbttag); comp.setCompound(rootnbttag);
} catch (Exception ex) { } 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); method = workingtag.getClass().getMethod("getByteArray", String.class);
return (byte[]) method.invoke(workingtag, key); return (byte[]) method.invoke(workingtag, key);
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
return null; return null;
} }
@ -582,7 +581,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, key, i); method.invoke(workingtag, key, i);
comp.setCompound(rootnbttag); comp.setCompound(rootnbttag);
} catch (Exception ex) { } 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); method = workingtag.getClass().getMethod("getIntArray", String.class);
return (int[]) method.invoke(workingtag, key); return (int[]) method.invoke(workingtag, key);
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
return null; return null;
} }
@ -620,7 +619,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, key, f); method.invoke(workingtag, key, f);
comp.setCompound(rootnbttag); comp.setCompound(rootnbttag);
} catch (Exception ex) { } 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); method = workingtag.getClass().getMethod("getFloat", String.class);
return (Float) method.invoke(workingtag, key); return (Float) method.invoke(workingtag, key);
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
return null; return null;
} }
@ -658,7 +657,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, key, f); method.invoke(workingtag, key, f);
comp.setCompound(rootnbttag); comp.setCompound(rootnbttag);
} catch (Exception ex) { } 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); method = workingtag.getClass().getMethod("getLong", String.class);
return (Long) method.invoke(workingtag, key); return (Long) method.invoke(workingtag, key);
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
return null; return null;
} }
@ -696,7 +695,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, key, f); method.invoke(workingtag, key, f);
comp.setCompound(rootnbttag); comp.setCompound(rootnbttag);
} catch (Exception ex) { } 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); method = workingtag.getClass().getMethod("getShort", String.class);
return (Short) method.invoke(workingtag, key); return (Short) method.invoke(workingtag, key);
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
return null; return null;
} }
@ -734,7 +733,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, key, f); method.invoke(workingtag, key, f);
comp.setCompound(rootnbttag); comp.setCompound(rootnbttag);
} catch (Exception ex) { } 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); method = workingtag.getClass().getMethod("getByte", String.class);
return (Byte) method.invoke(workingtag, key); return (Byte) method.invoke(workingtag, key);
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
return null; return null;
} }
@ -772,7 +771,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, key, d); method.invoke(workingtag, key, d);
comp.setCompound(rootnbttag); comp.setCompound(rootnbttag);
} catch (Exception ex) { } 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); method = workingtag.getClass().getMethod("getDouble", String.class);
return (Double) method.invoke(workingtag, key); return (Double) method.invoke(workingtag, key);
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
return null; return null;
} }
@ -805,7 +804,7 @@ public class NBTReflectionUtil {
method = workingtag.getClass().getMethod(MethodNames.getTypeMethodName(), String.class); method = workingtag.getClass().getMethod(MethodNames.getTypeMethodName(), String.class);
return (byte) method.invoke(workingtag, key); return (byte) method.invoke(workingtag, key);
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
return 0; return 0;
} }
@ -827,7 +826,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, key, d); method.invoke(workingtag, key, d);
comp.setCompound(rootnbttag); comp.setCompound(rootnbttag);
} catch (Exception ex) { } 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); method = workingtag.getClass().getMethod("getBoolean", String.class);
return (Boolean) method.invoke(workingtag, key); return (Boolean) method.invoke(workingtag, key);
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
return null; return null;
} }
@ -868,7 +867,7 @@ public class NBTReflectionUtil {
method.invoke(workingtag, key, val); method.invoke(workingtag, key, val);
comp.setCompound(rootnbttag); comp.setCompound(rootnbttag);
} catch (Exception ex) { } 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); method = workingtag.getClass().getMethod("getList", String.class, int.class);
return new NBTList(comp, key, type, method.invoke(workingtag, key, type.getId())); return new NBTList(comp, key, type, method.invoke(workingtag, key, type.getId()));
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
return null; return null;
} }
@ -894,7 +893,7 @@ public class NBTReflectionUtil {
String json = GsonWrapper.getString(value); String json = GsonWrapper.getString(value);
setString(comp, key, json); setString(comp, key, json);
} catch (Exception ex) { } 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); method.invoke(workingtag, key);
comp.setCompound(rootnbttag); comp.setCompound(rootnbttag);
} catch (Exception ex) { } 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); method = workingtag.getClass().getMethod("hasKey", String.class);
return (Boolean) method.invoke(workingtag, key); return (Boolean) method.invoke(workingtag, key);
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
return null; return null;
} }
@ -953,7 +952,7 @@ public class NBTReflectionUtil {
method = workingtag.getClass().getMethod("c"); method = workingtag.getClass().getMethod("c");
return (Set<String>) method.invoke(workingtag); return (Set<String>) method.invoke(workingtag);
} catch (Exception ex) { } catch (Exception ex) {
MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage()); MsgUtils.warn("NBT 操作出现异常: §7" + ex.getMessage());
} }
return null; return null;
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -10,35 +10,35 @@ public class CDL {
c = x.next(); c = x.next();
} while (c == ' ' || c == '\t'); } while (c == ' ' || c == '\t');
switch (c) { switch (c) {
case 0: case 0:
return null; return null;
case '"': case '"':
case '\'': case '\'':
q = c; q = c;
sb = new StringBuffer(); sb = new StringBuffer();
for (;;) { for (; ; ) {
c = x.next(); c = x.next();
if (c == q) { if (c == q) {
break; 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') { return sb.toString();
throw x.syntaxError("Missing close quote '" + q + "'."); case ',':
} x.back();
sb.append(c); return "";
} default:
return sb.toString(); x.back();
case ',': return x.nextTo(',');
x.back();
return "";
default:
x.back();
return x.nextTo(',');
} }
} }
public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException { public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException {
JSONArray ja = new JSONArray(); JSONArray ja = new JSONArray();
for (;;) { for (; ; ) {
String value = getValue(x); String value = getValue(x);
char c = x.next(); char c = x.next();
if (value == null || if (value == null ||
@ -46,16 +46,13 @@ public class CDL {
return null; return null;
} }
ja.put(value); ja.put(value);
for (;;) { while (c != ',') {
if (c == ',') {
break;
}
if (c != ' ') { if (c != ' ') {
if (c == '\n' || c == '\r' || c == 0) { if (c == '\n' || c == '\r' || c == 0) {
return ja; return ja;
} }
throw x.syntaxError("Bad character '" + c + "' (" + throw x.syntaxError("Bad character '" + c + "' (" +
(int)c + ")."); (int) c + ").");
} }
c = x.next(); c = x.next();
} }
@ -65,7 +62,7 @@ public class CDL {
public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x) public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x)
throws JSONException { throws JSONException {
JSONArray ja = rowToJSONArray(x); JSONArray ja = rowToJSONArray(x);
return ja != null ? ja.toJSONObject(names) : null; return ja != null ? ja.toJSONObject(names) : null;
} }
public static String rowToString(JSONArray ja) { public static String rowToString(JSONArray ja) {
@ -117,7 +114,7 @@ public class CDL {
return null; return null;
} }
JSONArray ja = new JSONArray(); JSONArray ja = new JSONArray();
for (;;) { for (; ; ) {
JSONObject jo = rowToJSONObject(names, x); JSONObject jo = rowToJSONObject(names, x);
if (jo == null) { if (jo == null) {
break; break;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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