合并,删除 .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,18 +17,18 @@ 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) {
if (!plugin.equals(Main.getInst())) {
inject(plugin, plugin); inject(plugin, plugin);
} }
}
static void onDisable(Plugin plugin) { static void onDisable(Plugin plugin) {
eject(plugin, plugin); eject(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());
} catch (Exception ignored) {
TLib.getTLib().getLogger().error("无效的语言文件发送形式: &4" + callerClass.getName());
} }
return (JavaPlugin) Main.getInst();
static List<String> asStringList(String path, Class<?> callerClass, String... args) {
return TLocaleLoader.asStringList(getCallerPlugin(callerClass), path, args);
} }
private static void sendTo(String path, CommandSender sender, String[] args, Class<?> callerClass) { 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);
} else {
return "";
}
} }
public static void init() { public static List<String> asStringList(Plugin plugin, String path, String... args) {
ConfigurationSerialization.registerClass(TLocaleText.class, "TEXT"); TLocaleInstance tLocaleInstance = map.get(plugin.getName());
ConfigurationSerialization.registerClass(TLocaleTitle.class, "TITLE"); if (tLocaleInstance != null) {
ConfigurationSerialization.registerClass(TLocaleJson.class, "JSON"); return tLocaleInstance.asStringList(path, args);
ConfigurationSerialization.registerClass(TLocaleActionBar.class, "ACTION"); } else {
return Collections.emptyList();
}
} }
public static void load(Plugin plugin, boolean ignoreLoaded) { /**
* 载入语言文件
*
* @param plugin 载入插件
* @param isCover 是否覆盖
*/
public static void load(Plugin plugin, boolean isCover) {
try { try {
if ((!ignoreLoaded || !map.containsKey(plugin.getName())) && (plugin == Main.getInst() || plugin.getDescription().getDepend().contains("TabooLib") || plugin.getDescription().getSoftDepend().contains("TabooLib"))) { if ((isCover || !isLocaleLoaded(plugin)) && (plugin.equals(Main.getInst()) || isDependWithTabooLib(plugin))) {
InputStream inputStream = null; // 获取文件
File file = null; File localeFile = getLocaleFile(plugin);
String lang = null; if (localeFile == 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; return;
} }
if (!file.exists()) {
file.getParentFile().mkdirs(); // 加载文件
file.createNewFile(); infoLogger("TRY-LOADING-LANG", plugin.getName(), localeFile.getName());
plugin.saveResource("lang/" + lang + ".yml", true); YamlConfiguration localeConfiguration = ConfigUtils.loadYaml(plugin, localeFile);
} YamlConfiguration localeConfigurationAtStream = getLocaleAtStream(plugin, localeFile);
TLib.getTLib().getLogger().info(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("TRY-LOADING-LANG"), plugin.getName(), lang));
{ // 载入配置
YamlConfiguration configuration = ConfigUtils.loadYaml(plugin, file); loadPluginLocale(plugin, localeFile, localeConfiguration, localeConfigurationAtStream);
TLocaleInstance localeInstance = new TLocaleInstance(plugin);
localeInstance.load(configuration); // 注册监听
map.put(plugin.getName(), localeInstance); TLib.getTLib().getConfigWatcher().removeListener(localeFile);
TLib.getTLib().getLogger().info(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("SUCCESS-LOADING-LANG"), TLib.getTLib().getConfigWatcher().addListener(localeFile, null, obj -> {
plugin.getName(), lang, String.valueOf(localeInstance.size()))); infoLogger("RELOADING-LANG", plugin.getName());
} loadPluginLocale(plugin, localeFile, ConfigUtils.loadYaml(plugin, localeFile), getLocaleAtStream(plugin, localeFile));
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) { } catch (Exception e) {
TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getTLib().getInternalLang().getString("ERROR-LOADING-LANG"), errorLogger("ERROR-LOADING-LANG", plugin.getName(), e.toString() + "\n" + e.getStackTrace()[0].toString());
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,20 +1,18 @@
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);
}
} }
} }

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,34 +15,32 @@ 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 HashMap<String, String> isOpen = new HashMap<>();
public static AnvilContainerAPIEvent event; public static AnvilContainerAPIEvent event;
public static void send(Player p, String type, String str, List<String> lorelist) public static void send(Player p, String type, String str, List<String> lorelist) {
{
isOpen.put(p.getName(), type); isOpen.put(p.getName(), type);
AnvilContainer_V1_9_4.openAnvil(p); AnvilContainer_V1_9_4.openAnvil(p);
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
list.clear(); list.clear();
if (lorelist == null) if (lorelist == null) {
{
list.add(""); list.add("");
list.add("§7在上方文本框内输入信息"); list.add("§7在上方文本框内输入信息");
list.add("§7随后点击右侧输出物品"); list.add("§7随后点击右侧输出物品");
} } else {
else
{
list = lorelist; list = lorelist;
} }
meta.setLore(list); meta.setLore(list);
meta.setDisplayName(str); meta.setDisplayName(str);
item.setItemMeta(meta); item.setItemMeta(meta);
@ -55,45 +50,36 @@ public class AnvilContainerAPI implements Listener{
} }
@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()); isOpen.remove(e.getPlayer().getName());
if (e.getInventory().getType() == InventoryType.ANVIL) if (e.getInventory().getType() == InventoryType.ANVIL) {
{
e.getInventory().clear(); 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) if (e.getInventory().getType() != InventoryType.ANVIL) {
{
return; return;
} }
e.setCancelled(true); 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);
@ -101,12 +87,9 @@ public class AnvilContainerAPI implements Listener{
} }
@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")) {
{
if (e.getPlayer().hasPermission("taboolib.admin"))
{
e.setCancelled(true); e.setCancelled(true);
AnvilContainerAPI.send(e.getPlayer(), "EXAMPLE", "在这里输入文本", null); AnvilContainerAPI.send(e.getPlayer(), "EXAMPLE", "在这里输入文本", null);
} }
@ -114,10 +97,8 @@ public class AnvilContainerAPI implements Listener{
} }
@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,25 +1,17 @@
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;
} }
@ -27,9 +19,8 @@ public class AnvilContainer_V1_11_R1 extends ContainerAnvil {
* @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));

View File

@ -1,25 +1,17 @@
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;
} }
@ -27,9 +19,8 @@ public class AnvilContainer_V1_8_R3 extends ContainerAnvil {
* @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));

View File

@ -1,25 +1,17 @@
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;
} }
@ -27,9 +19,8 @@ public class AnvilContainer_V1_9_4 extends ContainerAnvil {
* @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));

View File

@ -1,43 +1,10 @@
package me.skymc.taboolib.bookformatter; package me.skymc.taboolib.bookformatter;
import static org.bukkit.Achievement.ACQUIRE_IRON; import org.bukkit.Achievement;
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 java.util.HashMap;
import org.bukkit.Achievement; import static org.bukkit.Achievement.*;
public final class BookAchievement { public final class BookAchievement {
@ -52,36 +19,37 @@ public final class BookAchievement {
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,6 +108,7 @@ 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
*/ */
@ -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,6 +129,7 @@ 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
*/ */
@ -137,7 +137,7 @@ public final class BookReflection {
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,6 +149,7 @@ 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 player the player
* @param book the book to open * @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
@ -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,6 +194,7 @@ 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
*/ */
@ -202,15 +204,17 @@ public final class BookReflection {
/** /**
* 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
*/ */
@ -241,9 +245,12 @@ public final class BookReflection {
/** /**
* 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,6 +259,7 @@ 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
@ -263,6 +271,7 @@ 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
@ -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,6 +101,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 the item to display * @param entity the item to display
* @return a new HoverAction instance * @return a new HoverAction instance
*/ */
@ -104,6 +111,7 @@ 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 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,6 +121,7 @@ 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
*/ */
@ -122,6 +131,7 @@ public interface HoverAction {
/** /**
* 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,16 +11,38 @@ 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;
@ -31,14 +50,15 @@ public class TextBuilder {
/** /**
* 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,99 +1,66 @@
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;
public class MainCommands implements CommandExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (args.length == 0 || args[0].equalsIgnoreCase("help")) { if (args.length == 0 || args[0].equalsIgnoreCase("help")) {
new HelpCommand(sender, args); TLocale.sendTo(sender, "COMMANDS.TABOOLIB.HELP");
} } else if (args[0].equalsIgnoreCase("save")) {
else if (args[0].equalsIgnoreCase("itemreload") || args[0].equalsIgnoreCase("ireload")) { new SaveCommand(sender, args);
} else if (args[0].equalsIgnoreCase("enchants")) {
new EnchantCommand(sender, args);
} else if (args[0].equalsIgnoreCase("potions")) {
new PotionCommand(sender, args);
} else if (args[0].equalsIgnoreCase("flags")) {
new FlagCommand(sender, args);
} else if (args[0].equalsIgnoreCase("attributes")) {
new AttributesCommand(sender, args);
} else if (args[0].equalsIgnoreCase("slots")) {
new SlotCommand(sender, args);
} else if (args[0].equalsIgnoreCase("importdata")) {
new ImportCommand(sender, args);
} else if (args[0].equalsIgnoreCase("iteminfo")) {
new InfoCommand(sender, args);
} else if (args[0].equalsIgnoreCase("itemlist")) {
new ItemListCommand(sender, args);
} else if (args[0].equalsIgnoreCase("item") || args[0].equalsIgnoreCase("i")) {
new ItemCommand(sender, args);
} else if (args[0].equalsIgnoreCase("setvariable")) {
new VariableSetCommand(sender, args);
} else if (args[0].equalsIgnoreCase("getvariable")) {
new VariableGetCommand(sender, args);
} else if (args[0].equalsIgnoreCase("shell") || args[0].equalsIgnoreCase("s")) {
new ShellCommand(sender, args);
} else if (args[0].equalsIgnoreCase("cycle") || args[0].equalsIgnoreCase("c")) {
new CycleCommand(sender, args);
} else if (args[0].equalsIgnoreCase("sounds")) {
new SoundsCommand(sender, args);
} else if (args[0].equalsIgnoreCase("tagprefix")) {
new TagPrefixCommand(sender, args);
} else if (args[0].equalsIgnoreCase("tagsuffix")) {
new TagSuffixCommand(sender, args);
} else if (args[0].equalsIgnoreCase("tagdelete")) {
new TagDeleteCommand(sender, args);
} else if (args[0].equalsIgnoreCase("itemreload") || args[0].equalsIgnoreCase("ireload")) {
ItemUtils.reloadItemCache(); ItemUtils.reloadItemCache();
ItemUtils.reloadItemName(); ItemUtils.reloadItemName();
MsgUtils.send(sender, "重载成功"); TLocale.sendTo(sender, "COMMANDS.RELOAD.SUCCESS-NORMAL");
} } else {
else if (args[0].equalsIgnoreCase("save")) { TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN");
new SaveCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("enchants")) {
new EnchantCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("potions")) {
new PotionCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("flags")) {
new FlagCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("attributes")) {
new AttributesCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("slots")) {
new SlotCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("importdata")) {
new ImportCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("iteminfo")) {
new InfoCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("itemlist")) {
new ItemListCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("item") || args[0].equalsIgnoreCase("i")) {
new ItemCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("setvariable")) {
new VariableSetCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("getvariable")) {
new VariableGetCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("shell") || args[0].equalsIgnoreCase("s")) {
new ShellCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("cycle") || args[0].equalsIgnoreCase("c")) {
new CycleCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("sounds")) {
new SoundsCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("tagprefix")) {
new TagPrefixCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("tagsuffix")) {
new TagSuffixCommand(sender, args);
}
else if (args[0].equalsIgnoreCase("tagdelete")) {
new TagDeleteCommand(sender, args);
}
else {
MsgUtils.send(sender, "&4指令错误");
} }
return true; return true;
} }

View File

@ -3,6 +3,9 @@ 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;
@ -28,11 +31,6 @@ public abstract class SubCommand {
} }
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
@ -20,23 +21,25 @@ 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");
sender.sendMessage("§f /tloacle send §8[§7玩家/ALL§8] §8[§7语言§8] §8<§7变量§8> §6- §e发送语言提示");
sender.sendMessage("§f /tloacle reload §6- §e重载语言库");
sender.sendMessage("§f");
} else if (args[0].equalsIgnoreCase("send")) {
send(sender, args); send(sender, args);
} } else if (args[0].equalsIgnoreCase("reload")) {
else if (args[0].equalsIgnoreCase("reload")) {
reload(sender); reload(sender);
} } else {
else { MsgUtils.send(sender, "§4参数错误");
TLocale.sendTo(sender, "commands-taboolocale-invalid");
} }
return true; 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;
} }
@ -46,7 +49,7 @@ public class TabooLibLocaleCommand implements CommandExecutor {
} 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);
@ -54,22 +57,20 @@ public class TabooLibLocaleCommand implements CommandExecutor {
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)); target.forEach(x -> TLocale.sendTo(x, args[2], vars));
} else { } else {
target.forEach(x -> TLocale.sendTo(x, args[2])); 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,13 +1,11 @@
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 {
@ -15,21 +13,10 @@ public class EnchantCommand extends SubCommand {
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("正在清空数据库..."); TLocale.sendTo(sender, "COMMANDS.TABOOLIB.IMPORTDATA.CLEARING");
Main.getConnection().truncateTable(Main.getTablePrefix() + "_playerdata"); Main.getConnection().truncateTable(Main.getTablePrefix() + "_playerdata");
MsgUtils.send("开始导入玩家数据..."); if (!Main.getPlayerDataFolder().exists()) {
int size = Main.getPlayerDataFolder().listFiles().length; TLocale.sendTo(sender, "COMMANDS.TABOOLIB.IMPORTDATA.EMPTYDATA");
return;
}
int size = Objects.requireNonNull(Main.getPlayerDataFolder().listFiles()).length;
TLocale.sendTo(sender, "COMMANDS.TABOOLIB.IMPORTDATA.IMPORTING-START", String.valueOf(size));
int loop = 1; int loop = 1;
for (File file : Objects.requireNonNull(Main.getPlayerDataFolder().listFiles())) {
for (File file : Main.getPlayerDataFolder().listFiles()) { Main.getConnection().intoValue(Main.getTablePrefix() + "_playerdata", file.getName().replace(".yml", ""), ConfigUtils.encodeYAML(YamlConfiguration.loadConfiguration(file)));
FileConfiguration conf = YamlConfiguration.loadConfiguration(file); TLocale.sendTo(sender, "COMMANDS.TABOOLIB.IMPORTDATA.IMPORTING-PROGRESS", file.getName().replace(".yml", ""), String.valueOf(loop), String.valueOf(size));
Main.getConnection().intoValue(Main.getTablePrefix() + "_playerdata", file.getName().replace(".yml", ""), ConfigUtils.encodeYAML(conf));
MsgUtils.send("导入玩家: &f" + file.getName().replace(".yml", "") + " &7进度: &f" + loop + "/" + size);
loop++; loop++;
} }
MsgUtils.send("导入完成!");
} TLocale.sendTo(sender, "COMMANDS.TABOOLIB.IMPORTDATA.SUCCESS");
} }
} }

View File

@ -1,50 +1,29 @@
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.entity.Player;
import me.skymc.taboolib.commands.SubCommand; import me.skymc.taboolib.commands.SubCommand;
import me.skymc.taboolib.inventory.ItemUtils; import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.itemnbtapi.NBTItem; import me.skymc.taboolib.itemnbtapi.NBTItem;
import me.skymc.taboolib.jsonformatter.JSONFormatter; import org.bukkit.Material;
import me.skymc.taboolib.jsonformatter.click.SuggestCommandEvent; import org.bukkit.command.CommandSender;
import me.skymc.taboolib.jsonformatter.hover.ShowItemEvent; import org.bukkit.entity.Player;
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)) {
MsgUtils.send(player, "&7请手持正确物品"); TLocale.sendTo(sender, "COMMANDS.TABOOLIB.INFO.INVALID-ITEM");
} } else {
else { NBTItem nbt = new NBTItem(player.getItemInHand());
sender.sendMessage("§f"); TLocale.sendTo(sender, "COMAMNDS.TABOOLIB.INFO.ITEM-INFO",
sender.sendMessage("§b§l----- §3§lItemStack Info §b§l-----"); player.getItemInHand().getType().name(),
sender.sendMessage("§f"); ItemUtils.getCustomName(player.getItemInHand()),
player.getItemInHand().getTypeId() + ":" + player.getItemInHand().getDurability(),
JSONFormatter json = new JSONFormatter(); nbt.toString());
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,36 +1,29 @@
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 {
/**
* /TabooLib item 物品 玩家 数量
*
* @param sender
* @param args
*/
public ItemCommand(CommandSender sender, String[] args) { public ItemCommand(CommandSender sender, String[] args) {
super(sender, 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) { if (ItemUtils.getCacheItem(args[1]) == null) {
MsgUtils.send(sender, "物品 &f" + args[1] + "&7 不存在"); TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEM.INVALID-ITEM", args[1]);
setReturn(false);
return; return;
} }
@ -41,25 +34,20 @@ public class ItemCommand extends SubCommand {
if (args.length > 2) { if (args.length > 2) {
player = Bukkit.getPlayerExact(args[2]); player = Bukkit.getPlayerExact(args[2]);
if (player == null) { if (player == null) {
MsgUtils.send(sender, "玩家 &f" + args[2] + "&7 不在线"); TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEM.INVALID-PLAYER", args[2]);
setReturn(false);
return; return;
} }
} } else if (sender instanceof Player) {
else if (sender instanceof Player) {
player = (Player) sender; player = (Player) sender;
} } else {
else { TLocale.sendTo(sender, "COMMANDS.GLOBAL.ONLY-PLAYER");
MsgUtils.send(sender, "后台不允许这么做");
setReturn(false);
return; return;
} }
if (args.length > 3) { if (args.length > 3) {
amount = NumberUtils.getInteger(args[3]); amount = NumberUtils.getInteger(args[3]);
if (amount < 1) { if (amount < 1) {
MsgUtils.send(sender, "数量必须大于0"); TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEM.INVALID-NUMBER");
setReturn(false);
return; return;
} }
} }
@ -70,8 +58,7 @@ public class ItemCommand extends SubCommand {
player.getWorld().dropItem(player.getLocation(), item); player.getWorld().dropItem(player.getLocation(), item);
} }
MsgUtils.send(sender, "物品已发送至玩家 &f" + player.getName() + " &7的背包中"); TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEM.SUCCESS", player.getName());
setReturn(true); 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);
}
else {
sender.sendMessage(" §7- §f" + type.getId() + ". " + type.getName() + "");
} }
} }
}
sender.sendMessage("§f"); TLocale.sendTo(sender, "COMMANDS.TABOOLIB.POTIONS.FOOT");
} }
} }

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,35 +9,40 @@ 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;
} }
@ -50,36 +50,33 @@ public class SaveCommand extends SubCommand {
@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 {
else {
saveItem(args[1], ((Player) sender).getItemInHand()); saveItem(args[1], ((Player) sender).getItemInHand());
MsgUtils.send(sender, "物品 &f" + args[1] + " &7已保存"); 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);

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,9 +1,8 @@
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 {
@ -12,19 +11,15 @@ public class CycleCommand extends SubCommand {
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")) {
else if (args[1].equalsIgnoreCase("reset")) {
new CycleResetCommand(sender, args); new CycleResetCommand(sender, args);
} } else if (args[1].equalsIgnoreCase("update")) {
else if (args[1].equalsIgnoreCase("update")) {
new CycleUpdateCommand(sender, args); new CycleUpdateCommand(sender, args);
} }
} } else {
else { TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN");
MsgUtils.send(sender, "&4指令错误");
} }
} }

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,17 +12,12 @@ import me.skymc.taboolib.other.NumberUtils;
*/ */
public class ItemListCommand extends SubCommand { public class ItemListCommand extends SubCommand {
/**
* @param sender
* @param args
*/
public ItemListCommand(CommandSender sender, String[] args) { public ItemListCommand(CommandSender sender, String[] args) {
super(sender, args); super(sender, args);
if (isPlayer()) { if (isPlayer()) {
if (args.length == 1) { if (args.length == 1) {
ItemLibraryPatch.openInventory((Player) sender, 1); ItemLibraryPatch.openInventory((Player) sender, 1);
} } else {
else {
ItemLibraryPatch.openInventory((Player) sender, NumberUtils.getInteger(args[1])); 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
@ -33,7 +33,7 @@ public class ItemLibraryPatch implements Listener {
*/ */
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());
@ -44,17 +44,7 @@ public class ItemLibraryPatch implements Listener {
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));
{
ItemMeta meta = item.getItemMeta();
List<String> lore = meta.hasLore() ? meta.getLore() : new ArrayList<>();
lore.add("§f");
lore.add("§f§m ");
lore.add("§f序列号: §8" + name);
meta.setLore(lore);
item.setItemMeta(meta);
inventory.setItem(slot, item);
}
holder.ITEMS_DATA.put(slot, name); holder.ITEMS_DATA.put(slot, name);
} else { } else {
break; break;
@ -64,10 +54,10 @@ public class ItemLibraryPatch implements Listener {
} }
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);
} }
@ -81,20 +71,27 @@ public class ItemLibraryPatch implements Listener {
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);
break; } else {
default:
e.getWhoClicked().getInventory().addItem(ItemUtils.getCacheItem(((ItemLibraryHolder) e.getInventory().getHolder()).ITEMS_DATA.get(e.getRawSlot()))); e.getWhoClicked().getInventory().addItem(ItemUtils.getCacheItem(((ItemLibraryHolder) e.getInventory().getHolder()).ITEMS_DATA.get(e.getRawSlot())));
break;
} }
} }
} }
private static ItemStack getItem(HashMap<String, ItemStack> map, String name) {
ItemStack item = map.get(name).clone();
ItemMeta meta = item.getItemMeta();
List<String> lore = meta.hasLore() ? meta.getLore() : new ArrayList<>();
lore.addAll(TLocale.asStringList("COMMANDS.TABOOLIB.ITEMLIST.MENU.LORE", name));
meta.setLore(lore);
item.setItemMeta(meta);
return item;
}
public static class ItemLibraryHolder implements InventoryHolder { public static class ItemLibraryHolder implements InventoryHolder {
public final int PAGE; public final int PAGE;

View File

@ -1,9 +1,9 @@
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 {
@ -12,13 +12,11 @@ public class ShellCommand extends SubCommand {
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 {
else { TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN");
MsgUtils.send(sender, "&4指令错误");
} }
} }

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,18 +12,15 @@ import me.skymc.taboolib.other.NumberUtils;
*/ */
public class SoundsCommand extends SubCommand { public class SoundsCommand extends SubCommand {
/**
* @param sender
* @param args
*/
public SoundsCommand(CommandSender sender, String[] args) { public SoundsCommand(CommandSender sender, String[] args) {
super(sender, args); super(sender, args);
if (isPlayer()) { if (isPlayer()) {
if (args.length == 1) { if (args.length == 1) {
SoundsLibraryPatch.openInventory((Player) sender, 1); SoundsLibraryPatch.openInventory((Player) sender, 1, null);
} } else if (args.length == 2) {
else { SoundsLibraryPatch.openInventory((Player) sender, NumberUtils.getInteger(args[1]), null);
SoundsLibraryPatch.openInventory((Player) sender, NumberUtils.getInteger(args[1])); } else {
SoundsLibraryPatch.openInventory((Player) sender, NumberUtils.getInteger(args[1]), args[2]);
} }
} }
} }

View File

@ -1,8 +1,11 @@
package me.skymc.taboolib.commands.sub.sounds.listener; 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,29 +30,21 @@ 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
*/ SoundLibraryHolder holder = new SoundLibraryHolder(page, search);
public static void openInventory(Player player, int page) { Inventory inventory = Bukkit.createInventory(holder, 54, TLocale.asString("COMMANDS.TABOOLIB.SOUNDS.MENU.TITLE", String.valueOf(page)));
SoundLibraryHolder holder = new SoundLibraryHolder(page); List<Sound> soundFilter = Arrays.stream(Sound.values()).filter(sound -> search == null || sound.name().contains(search.toUpperCase())).collect(Collectors.toList());
Inventory inventory = Bukkit.createInventory(holder, 54, "音效库 " + page);
int loop = 0; int loop = 0;
for (Sound sound : Arrays.asList(Sound.values())) { for (Sound sound : soundFilter) {
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 = new ItemStack(Material.MAP); inventory.setItem(slot, getSoundItem(sound.name()));
{
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); holder.SOUNDS_DATA.put(slot, sound);
} else { } else {
break; break;
@ -56,10 +54,14 @@ public class SoundsLibraryPatch implements Listener {
} }
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.SOUNDS.MENU.BACK")));
} }
if (((int) Math.ceil(Sound.values().length / 28D)) > page) { if (((int) Math.ceil(Sound.values().length / 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.SOUNDS.MENU.NEXT")));
}
if (!(player.getOpenInventory().getTopInventory().getHolder() instanceof SoundLibraryHolder)) {
TLocale.sendTo(player, "COMMANDS.TABOOLIB.SOUNDS.RESULT.SEARCH", (search == null ? "*" : search), String.valueOf(soundFilter.size()));
} }
player.openInventory(inventory); player.openInventory(inventory);
} }
@ -73,32 +75,43 @@ public class SoundsLibraryPatch implements Listener {
return; return;
} }
switch (e.getRawSlot()) { SoundLibraryHolder soundLibraryHolder = ((SoundLibraryHolder) e.getInventory().getHolder());
case 47: int i = e.getRawSlot();
openInventory((Player) e.getWhoClicked(), ((SoundLibraryHolder) e.getInventory().getHolder()).PAGE - 1); if (i == 47) {
break; openInventory((Player) e.getWhoClicked(), soundLibraryHolder.PAGE - 1, soundLibraryHolder.SEARCH);
case 51: } else if (i == 51) {
openInventory((Player) e.getWhoClicked(), ((SoundLibraryHolder) e.getInventory().getHolder()).PAGE + 1); openInventory((Player) e.getWhoClicked(), soundLibraryHolder.PAGE + 1, soundLibraryHolder.SEARCH);
break; } else {
default: Sound sound = soundLibraryHolder.SOUNDS_DATA.get(e.getRawSlot());
Sound sound = ((SoundLibraryHolder) e.getInventory().getHolder()).SOUNDS_DATA.get(e.getRawSlot());
if (e.getClick().isLeftClick()) { if (e.getClick().isLeftClick()) {
((Player) e.getWhoClicked()).playSound(e.getWhoClicked().getLocation(), sound, 1f, 1f); ((Player) e.getWhoClicked()).playSound(e.getWhoClicked().getLocation(), sound, 1f, 1f);
} else { } else if (e.getClick().isRightClick()) {
((Player) e.getWhoClicked()).playSound(e.getWhoClicked().getLocation(), sound, 1f, 2f); ((Player) e.getWhoClicked()).playSound(e.getWhoClicked().getLocation(), sound, 1f, 2f);
} } else if (e.getClick().isCreativeAction()) {
break; TLocale.sendTo(e.getWhoClicked(), "COMMANDS.TABOOLIB.SOUNDS.RESULT.COPY", sound.name());
} }
} }
} }
}
private static ItemStack getSoundItem(String sound) {
ItemStack item = new ItemStack(Material.MAP);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName("§f§n" + sound);
meta.setLore(TLocale.asStringList("COMMANDS.TABOOLIB.SOUNDS.MENU.LORE"));
item.setItemMeta(meta);
return item;
}
public static class SoundLibraryHolder implements InventoryHolder { public static class SoundLibraryHolder implements InventoryHolder {
public final int PAGE; public final int PAGE;
public final String SEARCH;
public final HashMap<Integer, Sound> SOUNDS_DATA = new HashMap<>(); public final HashMap<Integer, Sound> SOUNDS_DATA = new HashMap<>();
public SoundLibraryHolder(int page) { public SoundLibraryHolder(int page, String search) {
this.PAGE = page; this.PAGE = page;
this.SEARCH = search;
} }
@Override @Override

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') {
@ -987,27 +945,23 @@ public class CsvReader
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;
@ -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,66 +1,53 @@
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(damager, (LivingEntity) victim, damage); dmg(player, (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) {
}
catch (IllegalAccessException|IllegalArgumentException|InvocationTargetException|NoSuchMethodException|SecurityException localIllegalAccessException1)
{
return; 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) {
}
catch (IllegalAccessException|IllegalArgumentException|InvocationTargetException|NoSuchMethodException|SecurityException localIllegalAccessException2)
{
return; return;
} }
try try {
{
Class<?> DamageSource = nmsClass("DamageSource"); Class<?> DamageSource = nmsClass("DamageSource");
Object localObject3 = DamageSource.getDeclaredMethod("playerAttack", new Class[]{nmsClass("EntityHuman")}).invoke(DamageSource, localObject1); Object localObject3 = DamageSource.getDeclaredMethod("playerAttack", 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);

View File

@ -13,8 +13,7 @@ public class 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

@ -13,8 +13,7 @@ public class 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,13 +18,9 @@ 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 {
@ -50,8 +49,7 @@ public class PlayerDataManager implements Listener {
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);
} }
} }
@ -68,8 +66,7 @@ public class PlayerDataManager implements Listener {
} }
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);
} }
} }
@ -84,8 +81,7 @@ public class PlayerDataManager implements Listener {
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("不允许在储存模式为数据库的情况下获取离线玩家数据");
} }
@ -107,8 +103,7 @@ public class PlayerDataManager implements Listener {
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)) {
// 获取数据 // 获取数据
@ -116,15 +111,13 @@ public class PlayerDataManager implements Listener {
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 {
else {
// 创建空数据 // 创建空数据
PLAYER_DATA.put(username, new YamlConfiguration()); PLAYER_DATA.put(username, new YamlConfiguration());
} }
@ -150,8 +143,7 @@ public class PlayerDataManager implements Listener {
// 保存配置 // 保存配置
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
} }
} }
@ -161,8 +153,7 @@ public class PlayerDataManager implements Listener {
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)));
} }
@ -171,8 +162,7 @@ public class PlayerDataManager implements Listener {
Player player; Player player;
if (getUsernameType() == UsernameType.UUID) { if (getUsernameType() == UsernameType.UUID) {
player = Bukkit.getPlayer(UUID.fromString(username)); player = Bukkit.getPlayer(UUID.fromString(username));
} } else {
else {
player = Bukkit.getPlayerExact(username); player = Bukkit.getPlayerExact(username);
} }
// 如果移除数据 玩家不在线 // 如果移除数据 玩家不在线

View File

@ -1,11 +1,10 @@
package me.skymc.taboolib.economy; package me.skymc.taboolib.economy;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.plugin.RegisteredServiceProvider;
import me.skymc.taboolib.Main; import me.skymc.taboolib.Main;
import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.plugin.RegisteredServiceProvider;
public class EcoUtils { public class EcoUtils {

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
* *

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,19 +13,17 @@ 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;
public static Entity getLastSpawnedEntity() {
return lastSpawnedEntity;
}
@EventHandler @EventHandler
public void spawn(EntitySpawnEvent e) { public void spawn(EntitySpawnEvent e) {
lastSpawnedEntity = e.getEntity(); lastSpawnedEntity = e.getEntity();
@ -68,12 +68,11 @@ public class EntityUtils implements Listener {
* @param player * @param player
* @param entity * @param entity
*/ */
public static void addGlow(Player player,Entity entity) { public static void addGlow(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) {
// //
} }
} }
@ -97,7 +96,7 @@ public class EntityUtils implements Listener {
* @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");

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 {
@ -26,8 +26,7 @@ public class DefaultEvent2 extends PlayerEvent
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) {
@ -46,8 +45,7 @@ public class DefaultEvent2 extends PlayerEvent
} }
} }
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 static final HandlerList handlers = new HandlerList();
private boolean isCancelled; private boolean isCancelled;
private Player player; private Player player;
public PlayerJumpEvent(boolean b, Player player) public PlayerJumpEvent(boolean b, Player player) {
{
this.isCancelled = false; this.isCancelled = false;
this.player = player; this.player = player;
} }
public Player getPlayer() public Player getPlayer() {
{
return this.player; return this.player;
} }
@Override @Override
public boolean isCancelled() public boolean isCancelled() {
{
return this.isCancelled; return this.isCancelled;
} }
@Override @Override
public void setCancelled(boolean e) public void setCancelled(boolean e) {
{
this.isCancelled = e; this.isCancelled = e;
} }
@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,13 +1,6 @@
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;

View File

@ -28,8 +28,7 @@ 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) {
catch (Exception e) {
// TODO: handle exception // TODO: handle exception
} }
return "[IP ERROR]"; return "[IP ERROR]";
@ -282,8 +281,7 @@ public class FileUtils {
// 结束 // 结束
fos.close(); fos.close();
inputStream.close(); inputStream.close();
} } catch (Exception e) {
catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -293,11 +291,10 @@ public class FileUtils {
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();
} }

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,13 +1,12 @@
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) {
@ -24,7 +23,7 @@ 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);
} }
@ -32,8 +31,7 @@ public class DropUtils {
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);

View File

@ -1,12 +1,12 @@
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(
@ -103,13 +103,11 @@ public class InventoryUtil {
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 {
else {
amount -= item.getAmount(); amount -= item.getAmount();
inv.setItem(i, null); inv.setItem(i, null);
} }

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,39 +27,48 @@ 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;
}
public static FileConfiguration getItemCache() {
return itemCache;
}
public static File getFinalItemsFolder() {
return finalItemsFolder;
}
public static LinkedHashMap<String, String> getItemlib() {
return itemlib;
}
public static LinkedHashMap<String, ItemStack> getItemCaches() {
return itemCaches;
}
public static LinkedHashMap<String, ItemStack> getItemCachesFinal() {
return itemCachesFinal;
}
/** /**
* 获取物品缓存 * 获取物品缓存
* 检测顺序 * 检测顺序
@ -109,7 +124,7 @@ public class ItemUtils {
finalItemsFolder.mkdir(); finalItemsFolder.mkdir();
} }
// 检查固定物品库中的物品 // 检查固定物品库中的物品
for (File file : finalItemsFolder.listFiles()) { for (File file : Objects.requireNonNull(finalItemsFolder.listFiles())) {
loadItemsFile(file, true); loadItemsFile(file, true);
} }
MsgUtils.send("载入 " + (itemCaches.size() + itemCachesFinal.size()) + " 项缓存物品"); MsgUtils.send("载入 " + (itemCaches.size() + itemCachesFinal.size()) + " 项缓存物品");
@ -193,17 +208,14 @@ public class ItemUtils {
} }
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;
} }
} }
@ -213,19 +225,17 @@ public class ItemUtils {
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;
} }
} }
@ -235,8 +245,7 @@ public class ItemUtils {
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;
} }
} }
@ -244,8 +253,7 @@ public class ItemUtils {
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);
} }
} }
@ -309,7 +317,7 @@ public class ItemUtils {
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);
@ -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;
} }
/** /**
@ -378,13 +379,10 @@ public class ItemUtils {
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();
for (int j = 0 ; j < lore.size() ; j++) { IntStream.range(0, lore.size()).forEach(j -> lore.set(j, lore.get(j).replace(l1, l2)));
lore.set(j, lore.get(j).replace(l1, l2));
}
meta.setLore(lore); meta.setLore(lore);
i.setItemMeta(meta); i.setItemMeta(meta);
} }
@ -425,8 +423,7 @@ public class ItemUtils {
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 查看所有附魔");
} }
@ -438,8 +435,7 @@ public class ItemUtils {
ItemFlag flag = asItemFlag(preFlag); ItemFlag flag = asItemFlag(preFlag);
if (flag != null) { if (flag != null) {
meta.addItemFlags(flag); meta.addItemFlags(flag);
} } else {
else {
MsgUtils.warn("&8" + preFlag + " &c不是一个有效的标签名称"); MsgUtils.warn("&8" + preFlag + " &c不是一个有效的标签名称");
MsgUtils.warn("&c输入 &4/taboolib flags&c 查看所有标签"); MsgUtils.warn("&c输入 &4/taboolib flags&c 查看所有标签");
} }
@ -459,9 +455,8 @@ public class ItemUtils {
potionEffectType, potionEffectType,
NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[0]), NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[0]),
NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[1]) - 1), true); NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[1]) - 1), true);
} } else {
else { MsgUtils.warn("&8" + prePotionName + " &c不是一个有效的药水名称");
MsgUtils.warn("&8" + potionEffectType + " &c不是一个有效的药水名称");
MsgUtils.warn("&c输入 &4/taboolib potions&c 查看所有药水"); MsgUtils.warn("&c输入 &4/taboolib potions&c 查看所有药水");
} }
} }
@ -476,17 +471,13 @@ public class ItemUtils {
Object obj = section.get("nbt." + name); Object obj = section.get("nbt." + name);
if (obj instanceof String) { if (obj instanceof String) {
nbt.setString(name, obj.toString()); nbt.setString(name, obj.toString());
} } else if (obj instanceof Double) {
else if (obj instanceof Double) {
nbt.setDouble(name, Double.valueOf(obj.toString())); nbt.setDouble(name, Double.valueOf(obj.toString()));
} } else if (obj instanceof Integer) {
else if (obj instanceof Integer) {
nbt.setInteger(name, Integer.valueOf(obj.toString())); nbt.setInteger(name, Integer.valueOf(obj.toString()));
} } else if (obj instanceof Long) {
else if (obj instanceof Long) {
nbt.setLong(name, Long.valueOf(obj.toString())); nbt.setLong(name, Long.valueOf(obj.toString()));
} } else {
else {
nbt.setObject(name, obj); nbt.setObject(name, obj);
} }
} }
@ -503,8 +494,7 @@ public class ItemUtils {
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);
} }
@ -515,12 +505,10 @@ public class ItemUtils {
if (!hand.equals("all")) { if (!hand.equals("all")) {
_attr.setString("Slot", hand); _attr.setString("Slot", hand);
} }
} } catch (Exception e) {
catch (Exception e) {
MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage()); MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage());
} }
} } else {
else {
MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称"); MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称");
MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性"); MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性");
} }
@ -535,7 +523,7 @@ public class ItemUtils {
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;
@ -547,8 +535,7 @@ public class ItemUtils {
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);
} }
@ -559,12 +546,10 @@ public class ItemUtils {
if (!hand.equals("all")) { if (!hand.equals("all")) {
_attr.setString("Slot", hand); _attr.setString("Slot", hand);
} }
} } catch (Exception e) {
catch (Exception e) {
MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage()); MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage());
} }
} } else {
else {
MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称"); MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称");
MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性"); MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性");
} }
@ -574,13 +559,13 @@ public class ItemUtils {
@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
@ -27,9 +25,12 @@ public class SpecialItem implements Listener {
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;
}
/** /**
* 构造方法 * 构造方法
*/ */
@ -63,8 +64,7 @@ public class SpecialItem implements Listener {
public void register(AbstractSpecialItem item) { public void register(AbstractSpecialItem item) {
if (contains(item.getName())) { if (contains(item.getName())) {
MsgUtils.warn("特殊物品接口已存在, 检查名称 &4" + item.getName() + " &c是否重复"); MsgUtils.warn("特殊物品接口已存在, 检查名称 &4" + item.getName() + " &c是否重复");
} } else {
else {
ITEM_DATA.add(item); ITEM_DATA.add(item);
if (isLoaded) { if (isLoaded) {
item.onEnable(); item.onEnable();
@ -136,7 +136,7 @@ public class SpecialItem implements Listener {
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;
@ -145,8 +145,11 @@ public class SpecialItem implements Listener {
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);

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,16 +9,16 @@ 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());
} }

View File

@ -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;

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;

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 {

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,16 +1,16 @@
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();
@ -31,8 +31,7 @@ public class JavaScriptUtils {
// TODO run // TODO run
Thread.currentThread().setContextClassLoader(classLoader); Thread.currentThread().setContextClassLoader(classLoader);
} } catch (Exception e) {
catch (Exception e) {
// TODO: handle exception // TODO: handle exception
} }
} }

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

@ -16,7 +16,7 @@ public class CDL {
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;
@ -38,7 +38,7 @@ public class CDL {
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();
} }
@ -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

@ -11,8 +11,8 @@ public class Cookie {
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);
} }
@ -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

@ -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);
@ -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,8 +100,8 @@ 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,8 +112,8 @@ 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.");
@ -123,7 +123,7 @@ public class JSONArray {
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,7 +132,7 @@ 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.");
@ -142,8 +142,8 @@ 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).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.");
@ -153,7 +153,7 @@ public class JSONArray {
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.");
} }
@ -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) {

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,
boolean arrayForm,
JSONArray ja
) throws JSONException {
String attribute; String attribute;
char c; char c;
String closeTag = null; String closeTag;
int i; int i;
JSONArray newja = null; JSONArray newja;
JSONObject newjo = null; JSONObject newjo;
Object token; Object token;
String tagName = null; String tagName;
while (true) { while (true) {
if (!x.more()) { if (!x.more()) {
@ -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,7 +158,7 @@ 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 {
@ -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);
@ -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,13 +6,7 @@ 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 {
@ -61,7 +55,7 @@ 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:
@ -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,8 +225,8 @@ 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,8 +237,8 @@ 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.");
@ -258,7 +248,7 @@ public class JSONObject {
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,8 +267,8 @@ 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,7 +310,7 @@ 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.");
@ -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);
@ -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,18 +664,17 @@ 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.");
} }
@ -743,13 +731,13 @@ public class JSONObject {
} }
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
@ -763,7 +751,7 @@ public class JSONObject {
return object.toString(); return object.toString();
} }
return new JSONObject(object); return new JSONObject(object);
} catch(Exception exception) { } catch (Exception exception) {
return null; return null;
} }
} }

View File

@ -1,12 +1,7 @@
package me.skymc.taboolib.json; package me.skymc.taboolib.json;
import java.io.BufferedReader; import java.io.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
public class JSONTokener { public class JSONTokener {
@ -133,7 +128,7 @@ public class JSONTokener {
} }
public char nextClean() throws JSONException { public char nextClean() throws JSONException {
for (;;) { for (; ; ) {
char c = this.next(); char c = this.next();
if (c == 0 || c > ' ') { if (c == 0 || c > ' ') {
return c; return c;
@ -144,7 +139,7 @@ public class JSONTokener {
public String nextString(char quote) throws JSONException { public String nextString(char quote) throws JSONException {
char c; char c;
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (;;) { for (; ; ) {
c = this.next(); c = this.next();
switch (c) { switch (c) {
case 0: case 0:
@ -170,7 +165,7 @@ public class JSONTokener {
sb.append('\r'); sb.append('\r');
break; break;
case 'u': case 'u':
sb.append((char)Integer.parseInt(this.next(4), 16)); sb.append((char) Integer.parseInt(this.next(4), 16));
break; break;
case '"': case '"':
case '\'': case '\'':
@ -193,7 +188,7 @@ public class JSONTokener {
public String nextTo(char delimiter) throws JSONException { public String nextTo(char delimiter) throws JSONException {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (;;) { for (; ; ) {
char c = this.next(); char c = this.next();
if (c == delimiter || c == 0 || c == '\n' || c == '\r') { if (c == delimiter || c == 0 || c == '\n' || c == '\r') {
if (c != 0) { if (c != 0) {
@ -208,7 +203,7 @@ public class JSONTokener {
public String nextTo(String delimiters) throws JSONException { public String nextTo(String delimiters) throws JSONException {
char c; char c;
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (;;) { for (; ; ) {
c = this.next(); c = this.next();
if (delimiters.indexOf(c) >= 0 || c == 0 || if (delimiters.indexOf(c) >= 0 || c == 0 ||
c == '\n' || c == '\r') { c == '\n' || c == '\r') {

View File

@ -125,15 +125,15 @@ public class XML {
} else if (token instanceof Character) { } else if (token instanceof Character) {
throw x.syntaxError("Misshaped tag"); throw x.syntaxError("Misshaped tag");
} else { } else {
tagName = (String)token; tagName = (String) token;
token = null; token = null;
jsonobject = new JSONObject(); jsonobject = new JSONObject();
for (;;) { for (; ; ) {
if (token == null) { if (token == null) {
token = x.nextToken(); token = x.nextToken();
} }
if (token instanceof String) { if (token instanceof String) {
string = (String)token; string = (String) token;
token = x.nextToken(); token = x.nextToken();
if (token == EQ) { if (token == EQ) {
token = x.nextToken(); token = x.nextToken();
@ -141,7 +141,7 @@ public class XML {
throw x.syntaxError("Missing value"); throw x.syntaxError("Missing value");
} }
jsonobject.accumulate(string, jsonobject.accumulate(string,
XML.stringToValue((String)token)); XML.stringToValue((String) token));
token = null; token = null;
} else { } else {
jsonobject.accumulate(string, ""); jsonobject.accumulate(string, "");
@ -157,7 +157,7 @@ public class XML {
} }
return false; return false;
} else if (token == GT) { } else if (token == GT) {
for (;;) { for (; ; ) {
token = x.nextContent(); token = x.nextContent();
if (token == null) { if (token == null) {
if (tagName != null) { if (tagName != null) {
@ -165,7 +165,7 @@ public class XML {
} }
return false; return false;
} else if (token instanceof String) { } else if (token instanceof String) {
string = (String)token; string = (String) token;
if (string.length() > 0) { if (string.length() > 0) {
jsonobject.accumulate("content", jsonobject.accumulate("content",
XML.stringToValue(string)); XML.stringToValue(string));
@ -248,8 +248,7 @@ public class XML {
return toString(object, null); return toString(object, null);
} }
public static String toString(Object object, String tagName) public static String toString(Object object, String tagName) throws JSONException {
throws JSONException {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
int i; int i;
JSONArray ja; JSONArray ja;
@ -265,7 +264,7 @@ public class XML {
sb.append(tagName); sb.append(tagName);
sb.append('>'); sb.append('>');
} }
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();
@ -273,14 +272,9 @@ public class XML {
if (value == null) { if (value == null) {
value = ""; value = "";
} }
if (value instanceof String) {
string = (String)value;
} else {
string = null;
}
if ("content".equals(key)) { if ("content".equals(key)) {
if (value instanceof JSONArray) { if (value instanceof JSONArray) {
ja = (JSONArray)value; ja = (JSONArray) value;
length = ja.length(); length = ja.length();
for (i = 0; i < length; i += 1) { for (i = 0; i < length; i += 1) {
if (i > 0) { if (i > 0) {
@ -292,7 +286,7 @@ public class XML {
sb.append(escape(value.toString())); sb.append(escape(value.toString()));
} }
} else if (value instanceof JSONArray) { } else if (value instanceof JSONArray) {
ja = (JSONArray)value; ja = (JSONArray) value;
length = ja.length(); length = ja.length();
for (i = 0; i < length; i += 1) { for (i = 0; i < length; i += 1) {
value = ja.get(i); value = ja.get(i);
@ -327,14 +321,14 @@ public class XML {
object = new JSONArray(object); object = new JSONArray(object);
} }
if (object instanceof JSONArray) { if (object instanceof JSONArray) {
ja = (JSONArray)object; ja = (JSONArray) object;
length = ja.length(); length = ja.length();
for (i = 0; i < length; i += 1) { for (i = 0; i < length; i += 1) {
sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName)); sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName));
} }
return sb.toString(); return sb.toString();
} else { } else {
string = (object == null) ? "null" : escape(object.toString()); string = escape(object.toString());
return (tagName == null) ? "\"" + string + "\"" : return (tagName == null) ? "\"" + string + "\"" :
(string.length() == 0) ? "<" + tagName + "/>" : (string.length() == 0) ? "<" + tagName + "/>" :
"<" + tagName + ">" + string + "</" + tagName + ">"; "<" + tagName + ">" + string + "</" + tagName + ">";

View File

@ -22,7 +22,7 @@ public class XMLTokener extends JSONTokener {
char c; char c;
int i; int i;
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (;;) { for (; ; ) {
c = next(); c = next();
if (end()) { if (end()) {
throw syntaxError("Unclosed CDATA"); throw syntaxError("Unclosed CDATA");
@ -50,7 +50,7 @@ public class XMLTokener extends JSONTokener {
return XML.LT; return XML.LT;
} }
sb = new StringBuffer(); sb = new StringBuffer();
for (;;) { for (; ; ) {
if (c == '<' || c == 0) { if (c == '<' || c == 0) {
back(); back();
return sb.toString().trim(); return sb.toString().trim();
@ -66,7 +66,7 @@ public class XMLTokener extends JSONTokener {
public Object nextEntity(char ampersand) throws JSONException { public Object nextEntity(char ampersand) throws JSONException {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (;;) { for (; ; ) {
char c = next(); char c = next();
if (Character.isLetterOrDigit(c) || c == '#') { if (Character.isLetterOrDigit(c) || c == '#') {
sb.append(Character.toLowerCase(c)); sb.append(Character.toLowerCase(c));
@ -105,7 +105,7 @@ public class XMLTokener extends JSONTokener {
case '"': case '"':
case '\'': case '\'':
q = c; q = c;
for (;;) { for (; ; ) {
c = next(); c = next();
if (c == 0) { if (c == 0) {
throw syntaxError("Unterminated string"); throw syntaxError("Unterminated string");
@ -115,7 +115,7 @@ public class XMLTokener extends JSONTokener {
} }
} }
default: default:
for (;;) { for (; ; ) {
c = next(); c = next();
if (Character.isWhitespace(c)) { if (Character.isWhitespace(c)) {
return Boolean.TRUE; return Boolean.TRUE;
@ -163,7 +163,7 @@ public class XMLTokener extends JSONTokener {
case '\'': case '\'':
q = c; q = c;
sb = new StringBuffer(); sb = new StringBuffer();
for (;;) { for (; ; ) {
c = next(); c = next();
if (c == 0) { if (c == 0) {
throw syntaxError("Unterminated string"); throw syntaxError("Unterminated string");
@ -179,7 +179,7 @@ public class XMLTokener extends JSONTokener {
} }
default: default:
sb = new StringBuffer(); sb = new StringBuffer();
for (;;) { for (; ; ) {
sb.append(c); sb.append(c);
c = next(); c = next();
if (Character.isWhitespace(c)) { if (Character.isWhitespace(c)) {
@ -222,7 +222,7 @@ public class XMLTokener extends JSONTokener {
} }
circle[i] = c; circle[i] = c;
} }
for (;;) { for (; ; ) {
j = offset; j = offset;
b = true; b = true;
for (i = 0; i < length; i += 1) { for (i = 0; i < length; i += 1) {

View File

@ -1,61 +1,73 @@
package me.skymc.taboolib.jsonformatter; package me.skymc.taboolib.jsonformatter;
import me.skymc.taboolib.json.JSONArray;
import me.skymc.taboolib.json.JSONObject;
import me.skymc.taboolib.jsonformatter.click.ClickEvent;
import me.skymc.taboolib.jsonformatter.hover.HoverEvent;
import me.skymc.taboolib.nms.NMSUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import me.skymc.taboolib.json.JSONArray;
import me.skymc.taboolib.json.JSONObject;
import me.skymc.taboolib.jsonformatter.click.ClickEvent;
import me.skymc.taboolib.jsonformatter.hover.HoverEvent;
import me.skymc.taboolib.nms.NMSUtils;
public class JSONFormatter { public class JSONFormatter {
public static void sendRawMessage(Player player, String message) {
try {
Object entityplayer = NMSUtils.getHandle(player);
Object ppco = ppc.get(entityplayer);
Object packet = ppocc.newInstance(message);
sp.invoke(ppco, packet);
} catch (Exception e) {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + message);
}
}
private JSONArray ja = new JSONArray(); private JSONArray ja = new JSONArray();
private Builder builder = new Builder(); private Builder builder = new Builder();
private String color = ""; private String color = "";
private List<JSONArray> all = new ArrayList<>(); private List<JSONArray> all = new ArrayList<>();
private boolean newline = true; private boolean newline = true;
public JSONFormatter(){ public JSONFormatter() {
} }
public JSONFormatter(boolean newline){ public JSONFormatter(boolean newline) {
this.newline = newline; this.newline = newline;
} }
public JSONFormatter append(JSONFormatter json){ public JSONFormatter append(JSONFormatter json) {
if(json.ja.length() == 0) if (json.ja.length() == 0)
return this; return this;
try{ try {
if(newline && json.newline){ if (newline && json.newline) {
all.addAll(json.all); all.addAll(json.all);
} }
for(int i = 0; i < json.ja.length(); i++){ for (int i = 0; i < json.ja.length(); i++) {
add(json.ja.get(i)); add(json.ja.get(i));
} }
}catch(Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return this; return this;
} }
public int getSize(){ public int getSize() {
if(newline){ return 1; } if (newline) {
return 1;
}
return all.size() + 1; return all.size() + 1;
} }
public JSONFormatter newLine(){ public JSONFormatter newLine() {
if(newline){ if (newline) {
append("\n"); append("\n");
}else{ } else {
all.add(ja); all.add(ja);
ja = new JSONArray(); ja = new JSONArray();
} }
@ -63,117 +75,117 @@ public class JSONFormatter {
return this; return this;
} }
public JSONFormatter newLine(int amount){ public JSONFormatter newLine(int amount) {
for(int i = 0; i < amount; i++) for (int i = 0; i < amount; i++)
newLine(); newLine();
return this; return this;
} }
public void clear(){ public void clear() {
ja = new JSONArray(); ja = new JSONArray();
builder = new Builder(); builder = new Builder();
color = ""; color = "";
} }
public JSONFormatter resetAll(){ public JSONFormatter resetAll() {
return resetColors().resetModifiers(); return resetColors().resetModifiers();
} }
public JSONFormatter resetColors(){ public JSONFormatter resetColors() {
color = ""; color = "";
return this; return this;
} }
public JSONFormatter resetModifiers(){ public JSONFormatter resetModifiers() {
builder = new Builder(); builder = new Builder();
return this; return this;
} }
public String toJSON(){ public String toJSON() {
JSONObject jo = new JSONObject(); JSONObject jo = new JSONObject();
try{ try {
if(ja.length() > 0) if (ja.length() > 0)
jo.put("extra", ja); jo.put("extra", ja);
jo.put("text", ""); jo.put("text", "");
}catch(Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return jo.toString(); return jo.toString();
} }
public List<String> toJSONList(){ public List<String> toJSONList() {
List<String> list = new ArrayList<>(); List<String> list = new ArrayList<>();
try{ try {
for(JSONArray ja : all){ for (JSONArray ja : all) {
JSONObject jo = new JSONObject(); JSONObject jo = new JSONObject();
if(ja.length() > 0) if (ja.length() > 0)
jo.put("extra", ja); jo.put("extra", ja);
jo.put("text", ""); jo.put("text", "");
list.add(jo.toString()); list.add(jo.toString());
} }
JSONObject jo = new JSONObject(); JSONObject jo = new JSONObject();
if(ja.length() > 0) if (ja.length() > 0)
jo.put("extra", ja); jo.put("extra", ja);
jo.put("text", ""); jo.put("text", "");
list.add(jo.toString()); list.add(jo.toString());
return list; return list;
}catch(Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
public Object toSerialized(){ public Object toSerialized() {
try{ try {
return a.invoke(null, toJSON()); return a.invoke(null, toJSON());
}catch(Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
public List<Object> toSerializedList(){ public List<Object> toSerializedList() {
List<Object> list = new ArrayList<>(); List<Object> list = new ArrayList<>();
try{ try {
for(String s : toJSONList()){ for (String s : toJSONList()) {
list.add(a.invoke(null, s)); list.add(a.invoke(null, s));
} }
return list; return list;
}catch(Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
public JSONFormatter send(Player player){ public JSONFormatter send(Player player) {
JSONFormatter.send(player, this); JSONFormatter.send(player, this);
return this; return this;
} }
private void add(Object jo){ private void add(Object jo) {
if(ja == null) if (ja == null)
ja = new JSONArray(); ja = new JSONArray();
if(jo != null) if (jo != null)
ja.put(jo); ja.put(jo);
} }
private JSONFormatter append(String text, BuilderMaker bm){ private JSONFormatter append(String text, BuilderMaker bm) {
builder = new Builder(builder); builder = new Builder(builder);
for(int i = 0; i < text.length(); i++){ for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i); char c = text.charAt(i);
switch(c){ switch (c) {
case '§':{ case '§': {
if((i + 1) == text.length()){ if ((i + 1) == text.length()) {
builder.append(c); builder.append(c);
continue; continue;
} }
ChatColor cc = ChatColor.getByChar(text.charAt(i + 1)); ChatColor cc = ChatColor.getByChar(text.charAt(i + 1));
if(cc == null){ if (cc == null) {
builder.append(c); builder.append(c);
break; break;
} }
add(bm.make()); add(bm.make());
switch(cc){ switch (cc) {
case BOLD: case BOLD:
builder = new Builder(builder); builder = new Builder(builder);
builder.bold = true; builder.bold = true;
@ -198,7 +210,7 @@ public class JSONFormatter {
builder = new Builder(builder); builder = new Builder(builder);
builder.underline = true; builder.underline = true;
break; break;
default:{ default: {
builder = new Builder(); builder = new Builder();
color = cc.name().toLowerCase(); color = cc.name().toLowerCase();
break; break;
@ -207,7 +219,7 @@ public class JSONFormatter {
i++; i++;
break; break;
} }
default:{ default: {
builder.append(c); builder.append(c);
} }
} }
@ -216,54 +228,54 @@ public class JSONFormatter {
return this; return this;
} }
public JSONFormatter append(String text){ public JSONFormatter append(String text) {
return append(text, new BuilderMaker(){ return append(text, new BuilderMaker() {
@Override @Override
public JSONObject make(){ public JSONObject make() {
return builder.toString(color); return builder.toString(color);
} }
}); });
} }
public JSONFormatter appendHover(String text, final HoverEvent hevent){ public JSONFormatter appendHover(String text, final HoverEvent hevent) {
return append(text, new BuilderMaker(){ return append(text, new BuilderMaker() {
@Override @Override
public JSONObject make(){ public JSONObject make() {
return builder.toStringHover(color, hevent); return builder.toStringHover(color, hevent);
} }
}); });
} }
public JSONFormatter appendClick(String text, final ClickEvent cevent){ public JSONFormatter appendClick(String text, final ClickEvent cevent) {
return append(text, new BuilderMaker(){ return append(text, new BuilderMaker() {
@Override @Override
public JSONObject make(){ public JSONObject make() {
return builder.toStringClick(color, cevent); return builder.toStringClick(color, cevent);
} }
}); });
} }
public JSONFormatter appendHoverClick(String text, final HoverEvent hevent, final ClickEvent cevent){ public JSONFormatter appendHoverClick(String text, final HoverEvent hevent, final ClickEvent cevent) {
return append(text, new BuilderMaker(){ return append(text, new BuilderMaker() {
@Override @Override
public JSONObject make(){ public JSONObject make() {
return builder.toStringHoverClick(color, hevent, cevent); return builder.toStringHoverClick(color, hevent, cevent);
} }
}); });
} }
public Object getPacket(){ public Object getPacket() {
try{ try {
return ppocc.newInstance(toSerialized()); return ppocc.newInstance(toSerialized());
} catch (Exception ignored) { } catch (Exception ignored) {
} }
return null; return null;
} }
public List<Object> getPacketList(){ public List<Object> getPacketList() {
List<Object> list = new ArrayList<>(); List<Object> list = new ArrayList<>();
try{ try {
for(Object o : toSerializedList()){ for (Object o : toSerializedList()) {
list.add(ppocc.newInstance(o)); list.add(ppocc.newInstance(o));
} }
return list; return list;
@ -272,73 +284,77 @@ public class JSONFormatter {
return null; return null;
} }
private static Class<?> cs = NMSUtils.getNMSClassSilent("ChatSerializer", "IChatBaseComponent"), icbc = NMSUtils.getNMSClassSilent("IChatBaseComponent"), ppoc = NMSUtils.getNMSClassSilent("PacketPlayOutChat"), pc = NMSUtils.getNMSClassSilent("PlayerConnection"), private static Class<?> cs = NMSUtils.getNMSClassSilent("ChatSerializer", "IChatBaseComponent");
p = NMSUtils.getNMSClassSilent("Packet"), ep = NMSUtils.getNMSClassSilent("EntityPlayer"); private static Class<?> icbc = NMSUtils.getNMSClassSilent("IChatBaseComponent");
private static Class<?> ppoc = NMSUtils.getNMSClassSilent("PacketPlayOutChat");
private static Class<?> pc = NMSUtils.getNMSClassSilent("PlayerConnection");
private static Class<?> p = NMSUtils.getNMSClassSilent("Packet");
private static Class<?> ep = NMSUtils.getNMSClassSilent("EntityPlayer");
private static Method a = NMSUtils.getMethodSilent(cs, "a", String.class), sp = NMSUtils.getMethodSilent(pc, "sendPacket", p); private static Method a = NMSUtils.getMethodSilent(cs, "a", String.class), sp = NMSUtils.getMethodSilent(pc, "sendPacket", p);
private static Field ppc = NMSUtils.getFieldSilent(ep, "playerConnection"); private static Field ppc = NMSUtils.getFieldSilent(ep, "playerConnection");
private static Constructor<?> ppocc = NMSUtils.getConstructorSilent(ppoc, icbc); private static Constructor<?> ppocc = NMSUtils.getConstructorSilent(ppoc, icbc);
private static boolean b = check(cs, icbc, ppoc, pc, p, ep, a, sp, ppc, ppocc); private static boolean b = check(cs, icbc, ppoc, pc, p, ep, a, sp, ppc, ppocc);
private static boolean check(Object... o){ private static boolean check(Object... o) {
for(Object a : o){ for (Object a : o) {
if(a == null) if (a == null)
return false; return false;
} }
return true; return true;
} }
private static void send(Player player, JSONFormatter jf){ private static void send(Player player, JSONFormatter jf) {
if(!jf.newline){ if (!jf.newline) {
send1(player, jf); send1(player, jf);
}else if(b){ } else if (b) {
try{ try {
Object entityplayer = NMSUtils.getHandle(player); Object entityplayer = NMSUtils.getHandle(player);
Object ppco = ppc.get(entityplayer); Object ppco = ppc.get(entityplayer);
sp.invoke(ppco, jf.getPacket()); sp.invoke(ppco, jf.getPacket());
} catch(Exception e){ } catch (Exception e) {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jf.toJSON()); Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jf.toJSON());
} }
}else{ } else {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jf.toJSON()); Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jf.toJSON());
} }
} }
private static void send1(Player player, JSONFormatter jf){ private static void send1(Player player, JSONFormatter jf) {
if(b){ if (b) {
try{ try {
Object entityplayer = NMSUtils.getHandle(player); Object entityplayer = NMSUtils.getHandle(player);
Object ppco = ppc.get(entityplayer); Object ppco = ppc.get(entityplayer);
List<Object> packets = jf.getPacketList(); List<Object> packets = jf.getPacketList();
List<String> jsons = null; List<String> jsons = null;
for(int i = 0; i < packets.size(); i++){ for (int i = 0; i < packets.size(); i++) {
try{ try {
sp.invoke(ppco, packets.get(i)); sp.invoke(ppco, packets.get(i));
}catch(Exception e){ } catch (Exception e) {
if(jsons == null){ if (jsons == null) {
jsons = jf.toJSONList(); jsons = jf.toJSONList();
} }
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jsons.get(i)); Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jsons.get(i));
} }
} }
}catch(Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
}else{ } else {
for(String json : jf.toJSONList()){ for (String json : jf.toJSONList()) {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + json); Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + json);
} }
} }
} }
private class Builder{ private class Builder {
private StringBuilder sb = new StringBuilder(""); private StringBuilder sb = new StringBuilder("");
private boolean bold = false, italic = false, magic = false, strikethrough = false, underline = false, changed = false; private boolean bold = false, italic = false, magic = false, strikethrough = false, underline = false, changed = false;
public Builder(){ public Builder() {
} }
public Builder(Builder b){ public Builder(Builder b) {
bold = b.bold; bold = b.bold;
italic = b.italic; italic = b.italic;
magic = b.magic; magic = b.magic;
@ -346,74 +362,74 @@ public class JSONFormatter {
underline = b.underline; underline = b.underline;
} }
public void append(char c){ public void append(char c) {
sb.append(c); sb.append(c);
changed = true; changed = true;
} }
private JSONObject toString(String color, BuilderHelper bh){ private JSONObject toString(String color, BuilderHelper bh) {
String string = sb.toString(); String string = sb.toString();
if(!changed) if (!changed)
return null; return null;
if(string.length() == 0) if (string.length() == 0)
return null; return null;
JSONObject jo = new JSONObject(); JSONObject jo = new JSONObject();
try{ try {
if(!color.equals("")) if (!color.equals(""))
jo.put("color", color); jo.put("color", color);
if(bold) if (bold)
jo.put("bold", true); jo.put("bold", true);
if(italic) if (italic)
jo.put("italic", true); jo.put("italic", true);
if(magic) if (magic)
jo.put("obfuscated", true); jo.put("obfuscated", true);
if(strikethrough) if (strikethrough)
jo.put("strikethrough", true); jo.put("strikethrough", true);
if(underline) if (underline)
jo.put("underlined", true); jo.put("underlined", true);
bh.add(jo); bh.add(jo);
jo.put("text", string); jo.put("text", string);
}catch(Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return jo; return jo;
} }
public JSONObject toString(String color){ public JSONObject toString(String color) {
return toString(color, new BuilderHelper(){ return toString(color, new BuilderHelper() {
@Override @Override
public void add(JSONObject jo) { public void add(JSONObject jo) {
} }
}); });
} }
public JSONObject toStringHover(String color, final HoverEvent event){ public JSONObject toStringHover(String color, final HoverEvent event) {
return toString(color, new BuilderHelper(){ return toString(color, new BuilderHelper() {
@Override @Override
public void add(JSONObject jo) throws Exception{ public void add(JSONObject jo) throws Exception {
if(event.getEvent().length() > 1) if (event.getEvent().length() > 1)
jo.put("hoverEvent", event.getEvent()); jo.put("hoverEvent", event.getEvent());
} }
}); });
} }
public JSONObject toStringClick(String color, final ClickEvent event){ public JSONObject toStringClick(String color, final ClickEvent event) {
return toString(color, new BuilderHelper(){ return toString(color, new BuilderHelper() {
@Override @Override
public void add(JSONObject jo) throws Exception{ public void add(JSONObject jo) throws Exception {
if(event.getEvent().length() > 1) if (event.getEvent().length() > 1)
jo.put("clickEvent", event.getEvent()); jo.put("clickEvent", event.getEvent());
} }
}); });
} }
public JSONObject toStringHoverClick(String color, final HoverEvent hevent, final ClickEvent cevent){ public JSONObject toStringHoverClick(String color, final HoverEvent hevent, final ClickEvent cevent) {
return toString(color, new BuilderHelper(){ return toString(color, new BuilderHelper() {
@Override @Override
public void add(JSONObject jo) throws Exception{ public void add(JSONObject jo) throws Exception {
if(hevent.getEvent().length() > 1) if (hevent.getEvent().length() > 1)
jo.put("hoverEvent", hevent.getEvent()); jo.put("hoverEvent", hevent.getEvent());
if(cevent.getEvent().length() > 1) if (cevent.getEvent().length() > 1)
jo.put("clickEvent", cevent.getEvent()); jo.put("clickEvent", cevent.getEvent());
} }
}); });
@ -421,11 +437,11 @@ public class JSONFormatter {
} }
private abstract class BuilderMaker{ private abstract class BuilderMaker {
public abstract JSONObject make(); public abstract JSONObject make();
} }
private abstract class BuilderHelper{ private abstract class BuilderHelper {
public abstract void add(JSONObject jo) throws Exception; public abstract void add(JSONObject jo) throws Exception;
} }
} }

View File

@ -1,7 +1,6 @@
package me.skymc.taboolib.listener; package me.skymc.taboolib.listener;
import java.util.HashMap; import me.skymc.taboolib.events.PlayerJumpEvent;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.Location; import org.bukkit.Location;
@ -13,38 +12,31 @@ import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import me.skymc.taboolib.events.PlayerJumpEvent; import java.util.HashMap;
public class ListenerPlayerJump implements Listener {
public class ListenerPlayerJump
implements Listener
{
public HashMap<Player, Long> cooldown = new HashMap<>(); public HashMap<Player, Long> cooldown = new HashMap<>();
@EventHandler(priority=EventPriority.HIGH) @EventHandler(priority = EventPriority.HIGH)
public void onJump(PlayerMoveEvent event) public void onJump(PlayerMoveEvent event) {
{
if ((!event.getPlayer().isFlying()) && (event.getPlayer().getGameMode() != GameMode.CREATIVE) && (event.getFrom().getY() + 0.5D != event.getTo().getY()) && (event.getFrom().getY() + 0.419D < event.getTo().getY())) { if ((!event.getPlayer().isFlying()) && (event.getPlayer().getGameMode() != GameMode.CREATIVE) && (event.getFrom().getY() + 0.5D != event.getTo().getY()) && (event.getFrom().getY() + 0.419D < event.getTo().getY())) {
Location loc = event.getFrom(); Location loc = event.getFrom();
loc.setY(event.getFrom().getY() - 1.0D); loc.setY(event.getFrom().getY() - 1.0D);
if (loc.getBlock().getType() != Material.AIR) if (loc.getBlock().getType() != Material.AIR) {
{ if (!this.cooldown.containsKey(event.getPlayer())) {
if (!this.cooldown.containsKey(event.getPlayer()))
{
this.cooldown.put(event.getPlayer(), System.currentTimeMillis() + 350L); this.cooldown.put(event.getPlayer(), System.currentTimeMillis() + 350L);
PlayerJumpEvent evt = new PlayerJumpEvent(event.isCancelled(), event.getPlayer()); PlayerJumpEvent evt = new PlayerJumpEvent(event.isCancelled(), event.getPlayer());
Bukkit.getPluginManager().callEvent(evt); Bukkit.getPluginManager().callEvent(evt);
if (evt.isCancelled()) if (evt.isCancelled()) {
{
event.setCancelled(true); event.setCancelled(true);
} }
} else if (this.cooldown.get(event.getPlayer()) <= System.currentTimeMillis()) } else if (this.cooldown.get(event.getPlayer()) <= System.currentTimeMillis()) {
{
this.cooldown.put(event.getPlayer(), System.currentTimeMillis() + 350L); this.cooldown.put(event.getPlayer(), System.currentTimeMillis() + 350L);
PlayerJumpEvent evt = new PlayerJumpEvent(event.isCancelled(), event.getPlayer()); PlayerJumpEvent evt = new PlayerJumpEvent(event.isCancelled(), event.getPlayer());
Bukkit.getPluginManager().callEvent(evt); Bukkit.getPluginManager().callEvent(evt);
if (evt.isCancelled()) if (evt.isCancelled()) {
{
event.setCancelled(true); event.setCancelled(true);
} }
} }
@ -53,8 +45,7 @@ public class ListenerPlayerJump
} }
@EventHandler @EventHandler
public void onQuit(PlayerQuitEvent event) public void onQuit(PlayerQuitEvent event) {
{
this.cooldown.remove(event.getPlayer()); this.cooldown.remove(event.getPlayer());
} }
} }

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