├── .circleci └── config.yml ├── .editorconfig ├── .gitignore ├── LICENSE ├── README.md ├── example ├── config.yml ├── lang │ ├── en-US.yml │ └── zh-CN.yml ├── plugin.yml └── team │ └── unstudio │ └── udpl │ └── example │ ├── ExampleCommand.java │ ├── ExampleConfig.java │ ├── ExamplePlugin.java │ └── MaterialParameterHandler.java ├── pom.xml ├── udplib-common ├── .gitignore ├── pom.xml └── src │ └── main │ └── java │ └── team │ └── unstudio │ └── udpl │ ├── UDPLib.java │ ├── _ui │ ├── Slot.java │ ├── UI.java │ └── UIListener.java │ ├── annotation │ └── Init.java │ ├── area │ ├── Area.java │ ├── AreaDataContainer.java │ ├── AreaListener.java │ ├── AreaManager.java │ ├── WorldAreaManager.java │ └── function │ │ ├── PlayerEnterAreaCallback.java │ │ └── PlayerLeaveAreaCallback.java │ ├── bungeecord │ ├── BungeeChannel.java │ ├── ForwardConsumer.java │ └── ServerLocation.java │ ├── command │ ├── CommandHelper.java │ └── anno │ │ ├── Alias.java │ │ ├── AnnoCommandManager.java │ │ ├── Command.java │ │ ├── CommandHelpImpl.java │ │ ├── CommandNode.java │ │ ├── CommandParameterHandler.java │ │ ├── CommandParameterManager.java │ │ ├── CommandResultHandler.java │ │ ├── CommandWrapper.java │ │ ├── DefaultCommandParameterManager.java │ │ ├── DefaultCommandResultHandler.java │ │ ├── Optional.java │ │ ├── RepeatableAlias.java │ │ ├── Required.java │ │ ├── TabComplete.java │ │ └── TabCompleteWrapper.java │ ├── config │ ├── AutoCharsetYamlConfiguration.java │ ├── ConfigItem.java │ ├── ConfigurationHandler.java │ ├── ConfigurationHelper.java │ ├── DecodedYamlConfiguration.java │ ├── EncodingDetect.java │ ├── SerializationException.java │ └── SerializationHelper.java │ ├── conversation │ ├── Conversation.java │ ├── ConversationState.java │ └── request │ │ ├── Request.java │ │ ├── RequestBase.java │ │ ├── RequestBigDecimal.java │ │ ├── RequestBigInteger.java │ │ ├── RequestBlock.java │ │ ├── RequestChoice.java │ │ ├── RequestChooseItemStack.java │ │ ├── RequestChooseItemStackLarge.java │ │ ├── RequestConfirm.java │ │ ├── RequestCustomRawMessage.java │ │ ├── RequestDouble.java │ │ ├── RequestEntity.java │ │ ├── RequestInteger.java │ │ ├── RequestMultiChoice.java │ │ ├── RequestMultiString.java │ │ ├── RequestPlayer.java │ │ └── RequestString.java │ ├── event │ └── FakeSignUpdateEvent.java │ ├── exception │ └── MemberMappingException.java │ ├── i18n │ ├── BaseI18n.java │ ├── I18n.java │ ├── PropertiesI18n.java │ ├── SLangI18n.java │ ├── YamlI18n.java │ └── slang │ │ ├── CachedSLang.java │ │ ├── SLangAlignment.java │ │ └── SLangSpliter.java │ ├── item │ ├── ItemHelper.java │ └── ItemWrapper.java │ ├── nms │ ├── NMSException.java │ ├── NmsHelper.java │ ├── NmsManager.java │ ├── entity │ │ ├── NmsEntity.java │ │ ├── NmsLivingEntity.java │ │ ├── NmsPlayer.java │ │ └── fake │ │ │ ├── FakeEntity.java │ │ │ └── FakeItem.java │ ├── inventory │ │ └── NmsItemStack.java │ ├── mapping │ │ ├── MappingHelper.java │ │ └── MemberMapping.java │ ├── nbt │ │ ├── NBTBase.java │ │ ├── NBTBaseType.java │ │ ├── NBTNumber.java │ │ ├── NBTTagByte.java │ │ ├── NBTTagByteArray.java │ │ ├── NBTTagCompound.java │ │ ├── NBTTagDouble.java │ │ ├── NBTTagEnd.java │ │ ├── NBTTagFloat.java │ │ ├── NBTTagInt.java │ │ ├── NBTTagIntArray.java │ │ ├── NBTTagList.java │ │ ├── NBTTagLong.java │ │ ├── NBTTagLongArray.java │ │ ├── NBTTagShort.java │ │ ├── NBTTagString.java │ │ ├── NBTUtils.java │ │ └── NmsNBT.java │ ├── network │ │ └── NmsNetwork.java │ ├── tileentity │ │ ├── NmsMobSpawner.java │ │ └── NmsTileEntity.java │ └── util │ │ ├── NmsClassLoader.java │ │ └── NmsClassTransformer.java │ ├── particle │ └── ParticleWrapper.java │ ├── scoreboard │ ├── BiScoreboard.java │ ├── ScoreboardHelper.java │ └── ScoreboardWrapper.java │ ├── ui │ ├── Container.java │ ├── Slot.java │ ├── UI.java │ └── UIFactory.java │ ├── util │ ├── ActionBarUtils.java │ ├── BlockUtils.java │ ├── BookUtils.java │ ├── BukkitVersion.java │ ├── CacheUtils.java │ ├── ChatUtils.java │ ├── EntityUtils.java │ ├── Hologram.java │ ├── PlayerUtils.java │ ├── PluginUtils.java │ ├── ProtocolLibUtils.java │ ├── Result.java │ ├── ServerListPingUtils.java │ ├── ServerUtils.java │ ├── SignUtils.java │ ├── Tab.java │ ├── TitleUtils.java │ ├── asm │ │ ├── AnnotationVisitor.java │ │ ├── AnnotationWriter.java │ │ ├── Attribute.java │ │ ├── ByteVector.java │ │ ├── ClassReader.java │ │ ├── ClassVisitor.java │ │ ├── ClassWriter.java │ │ ├── Context.java │ │ ├── CurrentFrame.java │ │ ├── Edge.java │ │ ├── FieldVisitor.java │ │ ├── FieldWriter.java │ │ ├── Frame.java │ │ ├── Handle.java │ │ ├── Handler.java │ │ ├── Item.java │ │ ├── Label.java │ │ ├── MethodVisitor.java │ │ ├── MethodWriter.java │ │ ├── Opcodes.java │ │ ├── Type.java │ │ ├── TypePath.java │ │ ├── TypeReference.java │ │ ├── commons │ │ │ ├── AdviceAdapter.java │ │ │ ├── AnalyzerAdapter.java │ │ │ ├── AnnotationRemapper.java │ │ │ ├── ClassRemapper.java │ │ │ ├── CodeSizeEvaluator.java │ │ │ ├── FieldRemapper.java │ │ │ ├── GeneratorAdapter.java │ │ │ ├── InstructionAdapter.java │ │ │ ├── JSRInlinerAdapter.java │ │ │ ├── LocalVariablesSorter.java │ │ │ ├── Method.java │ │ │ ├── MethodRemapper.java │ │ │ ├── Remapper.java │ │ │ ├── RemappingAnnotationAdapter.java │ │ │ ├── RemappingClassAdapter.java │ │ │ ├── RemappingFieldAdapter.java │ │ │ ├── RemappingMethodAdapter.java │ │ │ ├── RemappingSignatureAdapter.java │ │ │ ├── SerialVersionUIDAdder.java │ │ │ ├── SignatureRemapper.java │ │ │ ├── SimpleRemapper.java │ │ │ ├── StaticInitMerger.java │ │ │ ├── TableSwitchGenerator.java │ │ │ ├── TryCatchBlockSorter.java │ │ │ └── package.html │ │ ├── package.html │ │ ├── signature │ │ │ ├── SignatureReader.java │ │ │ ├── SignatureVisitor.java │ │ │ ├── SignatureWriter.java │ │ │ └── package.html │ │ ├── tree │ │ │ ├── AbstractInsnNode.java │ │ │ ├── AnnotationNode.java │ │ │ ├── ClassNode.java │ │ │ ├── FieldInsnNode.java │ │ │ ├── FieldNode.java │ │ │ ├── FrameNode.java │ │ │ ├── IincInsnNode.java │ │ │ ├── InnerClassNode.java │ │ │ ├── InsnList.java │ │ │ ├── InsnNode.java │ │ │ ├── IntInsnNode.java │ │ │ ├── InvokeDynamicInsnNode.java │ │ │ ├── JumpInsnNode.java │ │ │ ├── LabelNode.java │ │ │ ├── LdcInsnNode.java │ │ │ ├── LineNumberNode.java │ │ │ ├── LocalVariableAnnotationNode.java │ │ │ ├── LocalVariableNode.java │ │ │ ├── LookupSwitchInsnNode.java │ │ │ ├── MethodInsnNode.java │ │ │ ├── MethodNode.java │ │ │ ├── MultiANewArrayInsnNode.java │ │ │ ├── ParameterNode.java │ │ │ ├── TableSwitchInsnNode.java │ │ │ ├── TryCatchBlockNode.java │ │ │ ├── TypeAnnotationNode.java │ │ │ ├── TypeInsnNode.java │ │ │ ├── VarInsnNode.java │ │ │ ├── analysis │ │ │ │ ├── Analyzer.java │ │ │ │ ├── AnalyzerException.java │ │ │ │ ├── BasicInterpreter.java │ │ │ │ ├── BasicValue.java │ │ │ │ ├── BasicVerifier.java │ │ │ │ ├── Frame.java │ │ │ │ ├── Interpreter.java │ │ │ │ ├── SimpleVerifier.java │ │ │ │ ├── SmallSet.java │ │ │ │ ├── SourceInterpreter.java │ │ │ │ ├── SourceValue.java │ │ │ │ ├── Subroutine.java │ │ │ │ ├── Value.java │ │ │ │ └── package.html │ │ │ └── package.html │ │ ├── util │ │ │ ├── ASMifiable.java │ │ │ ├── ASMifier.java │ │ │ ├── CheckAnnotationAdapter.java │ │ │ ├── CheckClassAdapter.java │ │ │ ├── CheckFieldAdapter.java │ │ │ ├── CheckMethodAdapter.java │ │ │ ├── CheckSignatureAdapter.java │ │ │ ├── Printer.java │ │ │ ├── Textifiable.java │ │ │ ├── Textifier.java │ │ │ ├── TraceAnnotationVisitor.java │ │ │ ├── TraceClassVisitor.java │ │ │ ├── TraceFieldVisitor.java │ │ │ ├── TraceMethodVisitor.java │ │ │ ├── TraceSignatureVisitor.java │ │ │ └── package.html │ │ └── xml │ │ │ ├── ASMContentHandler.java │ │ │ ├── Processor.java │ │ │ ├── SAXAdapter.java │ │ │ ├── SAXAnnotationAdapter.java │ │ │ ├── SAXClassAdapter.java │ │ │ ├── SAXCodeAdapter.java │ │ │ ├── SAXFieldAdapter.java │ │ │ ├── asm-xml.dtd │ │ │ └── package.html │ ├── extra │ │ ├── ASMClassLoader.java │ │ ├── Chunk.java │ │ ├── FileUtils.java │ │ ├── IndexedItemStack.java │ │ └── ZipUtils.java │ ├── lazy │ │ └── Lazy.java │ └── reflect │ │ ├── NMSReflectionUtils.java │ │ ├── ReflectionUtils.java │ │ ├── UnsafeReflections.java │ │ └── UnsafeUtils.java │ └── variable │ ├── SimpleVariableHandler.java │ ├── VariableHandler.java │ └── VariableHelper.java ├── udplib-core ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── team │ │ │ └── unstudio │ │ │ └── udpl │ │ │ └── core │ │ │ ├── UDPLConfiguration.java │ │ │ ├── UDPLI18n.java │ │ │ ├── UDPLib.java │ │ │ ├── command │ │ │ ├── NBTEditor.java │ │ │ ├── PluginManager.java │ │ │ └── UDPLCommand.java │ │ │ ├── inject │ │ │ └── Injector.java │ │ │ └── util │ │ │ ├── AutoUpdate.java │ │ │ └── VersionCheck.java │ └── resources │ │ ├── config.yml │ │ ├── lang │ │ ├── command.slang │ │ ├── en-US.yml │ │ └── zh-CN.yml │ │ ├── mappings │ │ ├── 1.10.2 │ │ │ └── members.csrg │ │ ├── 1.10 │ │ │ └── members.csrg │ │ ├── 1.11.1 │ │ │ └── members.csrg │ │ ├── 1.11.2 │ │ │ └── members.csrg │ │ ├── 1.11 │ │ │ └── members.csrg │ │ ├── 1.12.1 │ │ │ └── members.csrg │ │ ├── 1.12.2 │ │ │ └── members.csrg │ │ ├── 1.12 │ │ │ └── members.csrg │ │ ├── 1.13.1 │ │ │ └── members.csrg │ │ ├── 1.13 │ │ │ └── members.csrg │ │ ├── 1.8.7 │ │ │ └── members.csrg │ │ ├── 1.8.8 │ │ │ └── members.csrg │ │ ├── 1.8 │ │ │ └── members.csrg │ │ ├── 1.9.4 │ │ │ └── members.csrg │ │ └── 1.9 │ │ │ └── members.csrg │ │ └── plugin.yml │ └── test │ ├── java │ └── team │ │ └── unstudio │ │ └── udpl │ │ ├── EncodingDetectTest.java │ │ ├── FileUtilsTest.java │ │ ├── I18nTest.java │ │ ├── MemberMappingTest.java │ │ ├── NBTTest.java │ │ └── SLangTest.java │ └── resources │ └── lang │ ├── properties │ ├── en-US.properties │ └── zh-CN.properties │ ├── slang │ └── general.slang │ └── yaml │ ├── en-US.yml │ └── zh-CN.yml ├── udplib-nms1_11_R1 ├── .gitignore ├── pom.xml └── src │ └── main │ └── java │ └── team │ └── unstudio │ └── udpl │ └── core │ └── nms │ └── v1_11_R1 │ ├── NmsManager.java │ ├── entity │ ├── NmsEntity.java │ ├── NmsLivingEntity.java │ ├── NmsPlayer.java │ └── fake │ │ ├── FakeEntity.java │ │ └── FakeItem.java │ ├── inventory │ └── NmsItemStack.java │ ├── nbt │ └── NmsNBT.java │ ├── network │ └── NmsNetwork.java │ └── tileentity │ ├── NmsMobSpawner.java │ └── NmsTileEntity.java └── udplib-test ├── .gitignore ├── pom.xml └── src └── main └── java └── team └── unstudio └── udpl └── core └── test ├── TestCommand.java ├── TestLoader.java └── TestSerialization.java /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | # Java Maven CircleCI 2.0 configuration file 2 | # 3 | # Check https://circleci.com/docs/2.0/language-java/ for more details 4 | # 5 | version: 2 6 | jobs: 7 | build: 8 | docker: 9 | # specify the version you desire here 10 | - image: circleci/openjdk:8-jdk 11 | 12 | # Specify service dependencies here if necessary 13 | # CircleCI maintains a library of pre-built images 14 | # documented at https://circleci.com/docs/2.0/circleci-images/ 15 | # - image: circleci/postgres:9.4 16 | 17 | working_directory: ~/repo 18 | 19 | environment: 20 | # Customize the JVM maximum heap limit 21 | MAVEN_OPTS: -Xmx3200m 22 | 23 | steps: 24 | - checkout 25 | 26 | # Download and cache dependencies 27 | - restore_cache: 28 | keys: 29 | - v1-dependencies-{{ checksum "pom.xml" }} 30 | # fallback to using the latest cache if no exact match is found 31 | - v1-dependencies- 32 | 33 | - run: mvn clean install package 34 | 35 | - save_cache: 36 | paths: 37 | - ~/.m2 38 | key: v1-dependencies-{{ checksum "pom.xml" }} 39 | 40 | - store_artifacts: 41 | path: /home/circleci/repo/udplib-test/target 42 | destination: udplib 43 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 4 6 | end_of_line = lf 7 | charset = utf-8 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | 11 | [*.md] 12 | trim_trailing_whitespace = false -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | !README.md 4 | !.gitignore 5 | !.editorconfig 6 | !src/ 7 | !pom.xml 8 | !LICENSE 9 | !.circleci/ 10 | !example/ 11 | !udplib-common/ 12 | !udplib-core/ 13 | !udplib-test/ 14 | !udplib-nms1_11_R1/ 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # UDPLib [![CircleCI](https://circleci.com/gh/UnknownStudio/UDPLib.svg?style=svg)](https://circleci.com/gh/UnknownStudio/UDPLib) [![](https://www.jitpack.io/v/UnknownStudio/UDPLib.svg)](https://www.jitpack.io/#UnknownStudio/UDPLib) ![Github All Releases](https://img.shields.io/github/downloads/UnknownStudio/UDPLib/total.svg) 2 | **Unknown Domain Spigot Plugin Library** 3 | 4 | By using this lib, you can easily develop your plugin with the help of such feature: 5 | * Annotation Command Support (Build your command with @Command) 6 | * Inventory UI (Custom behaviors of inventory's slot) 7 | * Area Manager (Allow you to manager area intuitively) 8 | * Item/Block Helper 9 | * NMS Wapper (An easy and safe way to using nms) 10 | * Conversation API 11 | * Utils & Helpers 12 | * .... 13 | 14 | ## Usage 15 | [Document](https://mccraft.cn/document/31/)、[Github Wiki](https://github.com/UnknownStudio/UDPLib/wiki) 16 | 17 | 18 | ## Download 19 | **To get this projectf rom JitPack.io into your build:** 20 | 21 | 22 | Maven: 23 | 1. Add the JitPack repository to your build file 24 | ```xml 25 | 26 | 27 | jitpack.io 28 | https://www.jitpack.io 29 | 30 | 31 | ``` 32 | 33 | 2. Add the dependency 34 | ```xml 35 | 36 | com.github.UnknownStudio 37 | UDPLib 38 |    1.1.1 39 | 40 | ``` 41 | 42 | Gradle: 43 | 1. Add this in your root build.gradle at the end of repositories 44 | ```gradle 45 | allprojects { 46 | repositories { 47 | ... 48 | maven { url 'https://www.jitpack.io' } 49 | } 50 | } 51 | ``` 52 | 53 | 2. Add the dependency 54 | ```gradle 55 | dependencies { 56 |        compile 'com.github.UnknownStudio:UDPLib:1.1.1' 57 | } 58 | ``` 59 | -------------------------------------------------------------------------------- /example/config.yml: -------------------------------------------------------------------------------- 1 | text: "text" 2 | enableExample: false -------------------------------------------------------------------------------- /example/lang/en-US.yml: -------------------------------------------------------------------------------- 1 | example.i18n: Welcome use UDPL I18n API. -------------------------------------------------------------------------------- /example/lang/zh-CN.yml: -------------------------------------------------------------------------------- 1 | example.i18n: 欢迎使用UDPL I18n API。 -------------------------------------------------------------------------------- /example/plugin.yml: -------------------------------------------------------------------------------- 1 | name: Example 2 | version: 1.0.0 3 | main: team.unstudio.udpl.example.ExamplePlugin 4 | commands: 5 | example: -------------------------------------------------------------------------------- /example/team/unstudio/udpl/example/ExampleConfig.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.example; 2 | 3 | import java.io.File; 4 | 5 | import team.unstudio.udpl.config.ConfigItem; 6 | import team.unstudio.udpl.config.ConfigurationHandler; 7 | 8 | public class ExampleConfig extends ConfigurationHandler{ 9 | 10 | /** 11 | * 你可以通过 @ConfigItem 来指定配置文件中对应的键名 12 | */ 13 | @ConfigItem("text") 14 | public String example; 15 | 16 | /** 17 | * 该字段没有 @ConfigItem 注解,则将字段名作为配置文件的键 18 | * 19 | * 该字段的默认值为true 20 | */ 21 | public boolean enableExample = true; 22 | 23 | 24 | public ExampleConfig(File file) { 25 | super(file); 26 | // ConfigurationHandler::reload is used to attempt to set field 27 | // 在初始化后,不会自动加载,需要手动调用 ConfigurationHandler::reload 28 | reload(); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /example/team/unstudio/udpl/example/ExamplePlugin.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.example; 2 | 3 | import java.io.File; 4 | 5 | import org.bukkit.plugin.java.JavaPlugin; 6 | 7 | import team.unstudio.udpl.command.anno.AnnoCommandManager; 8 | import team.unstudio.udpl.i18n.I18n; 9 | import team.unstudio.udpl.i18n.YamlI18n; 10 | import team.unstudio.udpl.util.PluginUtils; 11 | 12 | public class ExamplePlugin extends JavaPlugin{ 13 | 14 | public static I18n I18N; 15 | public static ExampleConfig CONFIG; 16 | 17 | @Override 18 | public void onLoad() { 19 | // save the default config from resource "config.yml" 20 | // 保存默认配置文件 "config.yml" 21 | saveDefaultConfig(); 22 | 23 | // init config 24 | // 初始化配置文件类 25 | CONFIG = new ExampleConfig(new File(getDataFolder(),"config.yml")); 26 | } 27 | 28 | @Override 29 | public void onEnable() { 30 | // 将 Jar 包中的 lang 文件夹全部保存到 JavaPlugin::getDataFolder 中 31 | PluginUtils.saveDirectory(this, "lang", false); 32 | // 使用 YamlI18n 加载语言文件 33 | I18N = YamlI18n.fromFile(new File(getDataFolder(), "lang")); 34 | // 在日志中输出语言项 35 | getLogger().info(ExamplePlugin.I18N.localize("example.i18n")); 36 | 37 | // 使用 AnnoCommandManager 构建命令 38 | AnnoCommandManager 39 | .builder() 40 | .name("example") // 命令名 41 | .plugin(this) // 插件主类 42 | .parameterHandler(new MaterialParameterHandler()) // 参数处理器 43 | .build() // 构建 CommandManager 44 | .addHandler(new ExampleCommand()) // 设置命令处理器 45 | .registerCommand(); // 注册命令 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /example/team/unstudio/udpl/example/MaterialParameterHandler.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.example; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | import org.bukkit.Material; 8 | 9 | import team.unstudio.udpl.command.anno.CommandParameterHandler; 10 | 11 | /** 12 | * 这是一个示例的命令参数处理器,可以自动转换参数为 Material 13 | */ 14 | public class MaterialParameterHandler implements CommandParameterHandler{ 15 | 16 | @Override 17 | public Object transform(String value) { 18 | return Material.valueOf(value); 19 | } 20 | 21 | @Override 22 | public List tabComplete(String value) { 23 | return Arrays.stream(Material.values()) 24 | .map(material->material.name()) 25 | .filter(material->material.startsWith(value)) 26 | .collect(Collectors.toList()); 27 | } 28 | 29 | @Override 30 | public Class getType() { 31 | return Material.class; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /udplib-common/.gitignore: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | !.gitignore 4 | !src/ 5 | !pom.xml -------------------------------------------------------------------------------- /udplib-common/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | team.unstudio 8 | udplib 9 | 1.3.3 10 | 11 | udplib-common 12 | UDPLib-common 13 | 14 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/UDPLib.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl; 2 | 3 | import org.apache.logging.log4j.LogManager; 4 | import org.apache.logging.log4j.Logger; 5 | import org.bukkit.plugin.java.JavaPlugin; 6 | 7 | import team.unstudio.udpl.annotation.Init; 8 | import team.unstudio.udpl.i18n.I18n; 9 | 10 | public final class UDPLib { 11 | 12 | @Init("core_i18n") 13 | private static I18n CORE_I18N; 14 | @Init("core_instance") 15 | private static JavaPlugin instance; 16 | @Init("core_logger") 17 | private static Logger logger; 18 | 19 | private static boolean DEBUG; 20 | 21 | public static I18n getI18n(){ 22 | return CORE_I18N; 23 | } 24 | 25 | public static boolean isDebug(){ 26 | return DEBUG; 27 | } 28 | 29 | public static void setDebug(boolean debug) { 30 | DEBUG = debug; 31 | } 32 | 33 | public static void debug(Throwable e) { 34 | if(isDebug()) 35 | getLogger().warn(e.getMessage(), e); 36 | } 37 | 38 | public static Logger getLogger() { 39 | if (logger == null) { 40 | logger = LogManager.getLogger("UDPLib"); 41 | } 42 | return logger; 43 | } 44 | 45 | public static JavaPlugin getPlugin() { 46 | return instance; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/_ui/Slot.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl._ui; 2 | 3 | import org.bukkit.Material; 4 | import org.bukkit.inventory.ItemStack; 5 | 6 | public abstract class Slot { 7 | /** 8 | * Whether the slot can be changed (put or take ItemStack) 9 | */ 10 | public boolean isEditable() { 11 | return false; 12 | } 13 | 14 | /** 15 | * Get the ItemStack display into Inventory ({@link UI#buildContent()}) 16 | */ 17 | public ItemStack getItemStackForDisplay() { 18 | return new ItemStack(Material.AIR); 19 | } 20 | 21 | public abstract void onClick(); 22 | public abstract void onClose(); 23 | } 24 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/_ui/UIListener.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl._ui; 2 | 3 | import org.bukkit.event.EventHandler; 4 | import org.bukkit.event.Listener; 5 | import org.bukkit.event.inventory.InventoryOpenEvent; 6 | 7 | public class UIListener implements Listener { 8 | @EventHandler 9 | public void onOpen(InventoryOpenEvent event) { 10 | 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/annotation/Init.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.annotation; 2 | 3 | import static java.lang.annotation.ElementType.*; 4 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 5 | 6 | import java.lang.annotation.Retention; 7 | import java.lang.annotation.Target; 8 | 9 | @Retention(RUNTIME) 10 | @Target({METHOD,FIELD}) 11 | public @interface Init { 12 | 13 | String value() default ""; 14 | } 15 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/area/AreaDataContainer.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.area; 2 | 3 | import org.bukkit.configuration.serialization.ConfigurationSerializable; 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | /** 9 | * 区域数据 Map,支持 Yaml 序列化。 10 | */ 11 | public class AreaDataContainer extends HashMap implements ConfigurationSerializable { 12 | 13 | public AreaDataContainer() { 14 | } 15 | 16 | public AreaDataContainer(Map data) { 17 | super(data); 18 | } 19 | 20 | @SuppressWarnings("unchecked") 21 | public T get(String key) { 22 | try { 23 | return (T) super.get(key); 24 | } catch (ClassCastException e) { 25 | return null; 26 | } 27 | } 28 | 29 | @SuppressWarnings("unchecked") 30 | public T get(String key, T def) { 31 | if (!containsKey(key)) 32 | return def; 33 | try { 34 | return (T) super.get(key); 35 | } catch (ClassCastException e) { 36 | return def; 37 | } 38 | } 39 | 40 | @Override 41 | public Map serialize() { 42 | put("==", getClass().getName()); 43 | return this; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/area/function/PlayerEnterAreaCallback.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.area.function; 2 | 3 | import org.bukkit.entity.Player; 4 | import team.unstudio.udpl.area.Area; 5 | 6 | import java.util.function.BiConsumer; 7 | 8 | @FunctionalInterface 9 | public interface PlayerEnterAreaCallback extends BiConsumer { 10 | } 11 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/area/function/PlayerLeaveAreaCallback.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.area.function; 2 | 3 | import org.bukkit.entity.Player; 4 | import team.unstudio.udpl.area.Area; 5 | 6 | import java.util.function.BiConsumer; 7 | 8 | @FunctionalInterface 9 | public interface PlayerLeaveAreaCallback extends BiConsumer { 10 | } 11 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/bungeecord/ForwardConsumer.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.bungeecord; 2 | 3 | import org.bukkit.entity.Player; 4 | 5 | /** 6 | * the forward message consumer 7 | */ 8 | @FunctionalInterface 9 | public interface ForwardConsumer { 10 | /** 11 | * receiving data 12 | */ 13 | void accept(String channel, Player player, byte[] data); 14 | } 15 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/command/CommandHelper.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.command; 2 | 3 | import org.apache.commons.lang.Validate; 4 | import org.bukkit.Bukkit; 5 | import org.bukkit.command.CommandMap; 6 | import org.bukkit.command.PluginCommand; 7 | import org.bukkit.plugin.Plugin; 8 | import javax.annotation.Nonnull; 9 | import java.lang.reflect.Constructor; 10 | import java.lang.reflect.InvocationTargetException; 11 | import java.lang.reflect.Method; 12 | import java.util.Optional; 13 | import java.util.concurrent.atomic.AtomicReference; 14 | import java.util.logging.Level; 15 | 16 | public interface CommandHelper { 17 | 18 | AtomicReference commandMap = new AtomicReference<>(); 19 | AtomicReference> pluginCommandConstructor = new AtomicReference<>(); 20 | 21 | /** 22 | * 不安全的指令注册 23 | * @param name 指令名 24 | * @param plugin 插件主类实例 25 | */ 26 | static Optional unsafeRegisterCommand(@Nonnull String name, @Nonnull Plugin plugin){ 27 | Validate.notEmpty(name); 28 | Validate.notNull(plugin); 29 | try { 30 | if(commandMap.get() == null){ 31 | //noinspection JavaReflectionMemberAccess 32 | Method getCommandMap = Bukkit.getServer().getClass().getDeclaredMethod("getCommandMap"); 33 | commandMap.set((CommandMap) getCommandMap.invoke(Bukkit.getServer())); 34 | } 35 | if(pluginCommandConstructor.get() == null){ 36 | pluginCommandConstructor.set(PluginCommand.class.getDeclaredConstructor(String.class, Plugin.class)); 37 | pluginCommandConstructor.get().setAccessible(true); 38 | } 39 | PluginCommand command = pluginCommandConstructor.get().newInstance(name,plugin); 40 | commandMap.get().register(plugin.getName(), command); 41 | return Optional.of(command); 42 | } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | InstantiationException e) { 43 | Bukkit.getLogger().log(Level.WARNING, e.getMessage(), e); 44 | } 45 | return Optional.empty(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/command/anno/Alias.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.command.anno; 2 | 3 | import static java.lang.annotation.ElementType.METHOD; 4 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 5 | 6 | import java.lang.annotation.Repeatable; 7 | import java.lang.annotation.Retention; 8 | import java.lang.annotation.Target; 9 | 10 | /** 11 | * 指令的别名 12 | */ 13 | @Retention(RUNTIME) 14 | @Target(METHOD) 15 | @Repeatable(RepeatableAlias.class) 16 | public @interface Alias { 17 | String[] value(); 18 | } 19 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/command/anno/Command.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.command.anno; 2 | 3 | import org.bukkit.command.CommandSender; 4 | 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.Target; 7 | 8 | import static java.lang.annotation.ElementType.METHOD; 9 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 10 | 11 | /** 12 | * 标记一个指令执行方法
13 | * 该方法的返回值应为void
14 | * 该方法第一个参数应为CommandSender或其子类,其他参数应先@Required参数再@Optional参数
15 | * 最后一个参数可以为String[]来接收额外输入的参数
16 | * 17 | * 示例如下:
18 | *
19 |  * @Command(value = "example",senders = Player.class,permission = "example.send")
20 |  * public void example(CommandSender sender,@Required Player target,@Optional("default") String message){
21 |  * 	target.sendMessage(message);
22 |  * }
23 |  * 
24 | */ 25 | @Retention(RUNTIME) 26 | @Target(METHOD) 27 | public @interface Command { 28 | 29 | /** 30 | * 指令名 31 | */ 32 | String[] value() default {}; 33 | 34 | /** 35 | * 指令权限 36 | */ 37 | String permission() default ""; 38 | 39 | /** 40 | * 允许的指令发送者 41 | */ 42 | Class[] senders() default {CommandSender.class}; 43 | 44 | /** 45 | * 指令用法 46 | */ 47 | String usage() default ""; 48 | 49 | /** 50 | * 指令描述 51 | */ 52 | String description() default ""; 53 | 54 | /** 55 | * 允许OP无视权限执行指令 56 | */ 57 | boolean allowOp() default true; 58 | 59 | /** 60 | * 精确参数匹配 61 | */ 62 | boolean exactParameterMatching() default false; 63 | 64 | /** 65 | * 隐藏的指令,如果为true,该指令的部分信息将不会显示(例如帮助信息) 66 | */ 67 | boolean hide() default false; 68 | } 69 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/command/anno/CommandHelpImpl.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.command.anno; 2 | 3 | import org.bukkit.command.CommandSender; 4 | 5 | public class CommandHelpImpl { 6 | 7 | private final AnnoCommandManager manager; 8 | 9 | public CommandHelpImpl(AnnoCommandManager manager) { 10 | this.manager = manager; 11 | } 12 | 13 | public AnnoCommandManager getCommandManager() { 14 | return manager; 15 | } 16 | 17 | public void onHelp(CommandSender sender, String... value) { 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/command/anno/CommandNode.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.command.anno; 2 | 3 | import java.util.HashMap; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | import java.util.Map; 7 | import static java.util.Objects.*; 8 | 9 | import java.util.Collection; 10 | 11 | public class CommandNode { 12 | 13 | private final String name; 14 | private final String fullPath; 15 | private final CommandNode parent; 16 | 17 | private final Map children = new HashMap<>(); 18 | 19 | private final List commands = new LinkedList<>(); 20 | private final List tabCompleters = new LinkedList<>(); 21 | 22 | public CommandNode(String name, CommandNode parent) { 23 | this.name = requireNonNull(name).toLowerCase(); 24 | this.parent = parent; 25 | this.fullPath = parent == null ? name : parent.getFullPath() + " " + name; 26 | } 27 | 28 | public String getName() { 29 | return name; 30 | } 31 | 32 | public String getFullPath() { 33 | return fullPath; 34 | } 35 | 36 | public CommandNode getParent() { 37 | return parent; 38 | } 39 | 40 | public CommandNode getChild(String name) { 41 | return children.get(name.toLowerCase()); 42 | } 43 | 44 | public void addChild(CommandNode node) { 45 | children.put(node.getName(), node); 46 | } 47 | 48 | public Collection getChildren() { 49 | return children.values(); 50 | } 51 | 52 | public List getCommands() { 53 | return commands; 54 | } 55 | 56 | public List getTabCompleters() { 57 | return tabCompleters; 58 | } 59 | 60 | public boolean hasCommand() { 61 | return !commands.isEmpty(); 62 | } 63 | 64 | public boolean hasTabCompleter() { 65 | return !tabCompleters.isEmpty(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/command/anno/CommandParameterManager.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.command.anno; 2 | 3 | import java.util.List; 4 | 5 | public interface CommandParameterManager { 6 | 7 | Object transform(Class clazz, String value) throws Exception; 8 | 9 | List tabComplete(Class clazz, String value); 10 | } 11 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/command/anno/CommandResultHandler.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.command.anno; 2 | 3 | import java.util.Set; 4 | 5 | import org.bukkit.command.CommandSender; 6 | 7 | public interface CommandResultHandler { 8 | 9 | void setCommandManager(AnnoCommandManager commandManager); 10 | 11 | void onUnknownCommand(CommandSender sender, String[] args); 12 | 13 | void onWrongSender(CommandNode node, CommandSender sender, String[] args); 14 | 15 | void onNoPermission(CommandWrapper command, CommandSender sender, String[] args); 16 | 17 | void onNoEnoughParameter(CommandWrapper command, CommandSender sender, String[] args); 18 | 19 | void onWrongParameter(CommandWrapper command, CommandSender sender, String[] args, Set wrongParameterIndexs); 20 | 21 | void onRunCommandFailure(CommandWrapper command, CommandSender sender, String[] args, Throwable t); 22 | } 23 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/command/anno/DefaultCommandParameterManager.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.command.anno; 2 | 3 | import java.util.Collection; 4 | import java.util.Collections; 5 | import java.util.HashMap; 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | import com.google.common.base.Strings; 10 | 11 | public class DefaultCommandParameterManager implements CommandParameterManager{ 12 | 13 | protected final Map, CommandParameterHandler> handlers = new HashMap<>(); 14 | 15 | public DefaultCommandParameterManager() { 16 | addHandler(new CommandParameterHandler.BooleanHandler()); 17 | addHandler(new CommandParameterHandler.NumberHandler()); 18 | addHandler(new CommandParameterHandler.PlayerHandler()); 19 | addHandler(new CommandParameterHandler.OfflinePlayerHandler()); 20 | } 21 | 22 | public DefaultCommandParameterManager(CommandParameterHandler... handlers) { 23 | this(); 24 | addHandler(handlers); 25 | } 26 | 27 | public DefaultCommandParameterManager(Collection handlers) { 28 | this(); 29 | addHandler(handlers); 30 | } 31 | 32 | public void addHandler(CommandParameterHandler handler) { 33 | handlers.put(handler.getType(), handler); 34 | } 35 | 36 | public void addHandler(CommandParameterHandler... handlers) { 37 | for(CommandParameterHandler handler : handlers) 38 | addHandler(handler); 39 | } 40 | 41 | public void addHandler(Collection handlers) { 42 | for(CommandParameterHandler handler : handlers) 43 | addHandler(handler); 44 | } 45 | 46 | @Override 47 | public Object transform(Class clazz, String value) { 48 | if (value == null) 49 | return null; 50 | else if (clazz.equals(String.class)) 51 | return value; 52 | else if (clazz.equals(int.class)) 53 | return Integer.parseInt(value); 54 | else if (clazz.equals(float.class)) 55 | return Float.parseFloat(value); 56 | else if (clazz.equals(double.class)) 57 | return Double.parseDouble(value); 58 | else if (clazz.equals(long.class)) 59 | return Long.parseLong(value); 60 | else if (clazz.equals(byte.class)) 61 | return Byte.parseByte(value); 62 | else if (clazz.equals(short.class)) 63 | return Short.parseShort(value); 64 | else if (handlers.containsKey(clazz)) 65 | return handlers.get(clazz).transform(value); 66 | else 67 | throw new IllegalArgumentException( 68 | String.format("Can't transform parameter. Class: %1$s. Value: \"%2$s\".", clazz.getName(), value)); 69 | } 70 | 71 | @Override 72 | public List tabComplete(Class clazz, String value) { 73 | return handlers.containsKey(clazz) 74 | ? handlers.get(clazz).tabComplete(Strings.nullToEmpty(value)) 75 | : Collections.emptyList(); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/command/anno/Optional.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.command.anno; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.Target; 5 | 6 | import static java.lang.annotation.ElementType.PARAMETER; 7 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 8 | 9 | /** 10 | * 可选的指令参数 11 | */ 12 | @Retention(RUNTIME) 13 | @Target(PARAMETER) 14 | public @interface Optional { 15 | /** 16 | * 当无参数输入时的默认值 17 | */ 18 | String value() default ""; 19 | 20 | /** 21 | * 参数名 22 | */ 23 | String name() default ""; 24 | 25 | /** 26 | * 参数用法 27 | */ 28 | String usage() default ""; 29 | 30 | /** 31 | * 自动补全 32 | */ 33 | String[] complete() default {}; 34 | } 35 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/command/anno/RepeatableAlias.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.command.anno; 2 | 3 | import static java.lang.annotation.ElementType.METHOD; 4 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 5 | 6 | import java.lang.annotation.Retention; 7 | import java.lang.annotation.Target; 8 | 9 | @Retention(RUNTIME) 10 | @Target(METHOD) 11 | public @interface RepeatableAlias { 12 | Alias[] value() default {}; 13 | } 14 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/command/anno/Required.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.command.anno; 2 | 3 | import static java.lang.annotation.ElementType.*; 4 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 5 | 6 | import java.lang.annotation.Retention; 7 | import java.lang.annotation.Target; 8 | 9 | @Retention(RUNTIME) 10 | @Target(PARAMETER) 11 | public @interface Required { 12 | /** 13 | * 参数名 14 | */ 15 | String name() default ""; 16 | 17 | /** 18 | * 参数用法 19 | */ 20 | String usage() default ""; 21 | 22 | /** 23 | * 自动补全 24 | */ 25 | String[] complete() default {}; 26 | } 27 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/command/anno/TabComplete.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.command.anno; 2 | 3 | import static java.lang.annotation.ElementType.METHOD; 4 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 5 | 6 | import java.lang.annotation.Retention; 7 | import java.lang.annotation.Target; 8 | 9 | import org.bukkit.command.CommandSender; 10 | 11 | /** 12 | * 自动补全方法注解
13 | * 代码示例 14 | *

15 | * @TabComplete(value = "example") 16 | * public List tabComplete(String[] args){ 17 | * return Arrays.asList("TabComplete"); 18 | * } 19 | *

20 | */ 21 | @Retention(RUNTIME) 22 | @Target(METHOD) 23 | public @interface TabComplete { 24 | 25 | /** 26 | * 补全的名称 27 | */ 28 | String[] value(); 29 | 30 | /** 31 | * 补全权限 32 | */ 33 | String permission() default ""; 34 | 35 | /** 36 | * 允许的发送者 37 | */ 38 | Class[] senders() default {CommandSender.class}; 39 | 40 | /** 41 | * 允许OP无视权限执行补全 42 | */ 43 | boolean allowOp() default true; 44 | } 45 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/config/AutoCharsetYamlConfiguration.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.config; 2 | 3 | import org.apache.commons.lang.Validate; 4 | import org.bukkit.Bukkit; 5 | import org.bukkit.configuration.InvalidConfigurationException; 6 | 7 | import javax.annotation.Nonnull; 8 | import javax.annotation.Nullable; 9 | import java.io.File; 10 | import java.io.IOException; 11 | import java.nio.charset.Charset; 12 | import java.util.logging.Level; 13 | 14 | /** 15 | * 本类使用了 cpDetector,以达到自动识别文件编码的 16 | * cpDetector 官网 17 | */ 18 | public class AutoCharsetYamlConfiguration extends DecodedYamlConfiguration { 19 | public final static Charset defaultCharset = Charset.defaultCharset(); 20 | 21 | private AutoCharsetYamlConfiguration() {} 22 | 23 | /** 24 | * 加载Yaml 同时自动识别文件编码 25 | */ 26 | @Nullable 27 | public static AutoCharsetYamlConfiguration loadConfiguration(@Nonnull File file){ 28 | Validate.notNull(file, "File cannot be null"); 29 | AutoCharsetYamlConfiguration config = new AutoCharsetYamlConfiguration(); 30 | setConfigCharsetName(config,file); 31 | return loadFile(config,file); 32 | } 33 | 34 | private static void setConfigCharsetName(AutoCharsetYamlConfiguration config,File file) { 35 | try{ 36 | config.charset = Charset.forName(EncodingDetect.getJavaEncode(file)); 37 | if (config.charset == null) 38 | config.charset = defaultCharset; 39 | }catch(Exception ignored){} 40 | } 41 | 42 | private static AutoCharsetYamlConfiguration loadFile(AutoCharsetYamlConfiguration config, File file) { 43 | try { 44 | config.load(file); 45 | } catch (IOException | InvalidConfigurationException e) { 46 | Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, e); 47 | } 48 | return config; 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/config/ConfigItem.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.config; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.Target; 5 | 6 | import static java.lang.annotation.ElementType.FIELD; 7 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 8 | 9 | /** 10 | * 注解一个配置项 11 | * value为在配置文件中的key 12 | * 可以为注解的配置项设置一个默认值 13 | */ 14 | @Retention(RUNTIME) 15 | @Target(FIELD) 16 | public @interface ConfigItem{ 17 | String value(); 18 | } 19 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/config/ConfigurationHelper.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.config; 2 | 3 | import org.bukkit.configuration.file.YamlConfiguration; 4 | 5 | import javax.annotation.Nullable; 6 | import java.io.File; 7 | import java.io.IOException; 8 | import java.nio.charset.Charset; 9 | 10 | public interface ConfigurationHelper { 11 | 12 | /** 13 | * 载入配置文件 14 | */ 15 | @Nullable 16 | static YamlConfiguration loadConfiguration(File file){ 17 | if (!file.getAbsoluteFile().getParentFile().exists()) 18 | file.getAbsoluteFile().getParentFile().mkdirs(); 19 | 20 | if (!file.exists()) 21 | try { 22 | file.createNewFile(); 23 | } catch (IOException ignored) {} 24 | 25 | return AutoCharsetYamlConfiguration.loadConfiguration(file); 26 | } 27 | 28 | /** 29 | * 创建空的配配置文件 30 | */ 31 | static YamlConfiguration newConfiguration(){ 32 | return new DecodedYamlConfiguration(); 33 | } 34 | 35 | /** 36 | * 创建空的配配置文件 37 | */ 38 | static YamlConfiguration newConfiguration(Charset charset){ 39 | return new DecodedYamlConfiguration(charset); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/config/DecodedYamlConfiguration.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.config; 2 | 3 | import org.apache.commons.lang.Validate; 4 | import org.bukkit.Bukkit; 5 | import org.bukkit.configuration.InvalidConfigurationException; 6 | import org.bukkit.configuration.file.YamlConfiguration; 7 | 8 | import javax.annotation.Nullable; 9 | import java.io.*; 10 | import java.nio.charset.Charset; 11 | import java.util.logging.Level; 12 | 13 | /** 14 | * 可以指定编码的 YamlConfiguration, 如不指定编码,默认为UTF-8 15 | */ 16 | public class DecodedYamlConfiguration extends YamlConfiguration { 17 | /** 18 | * 文件编码 19 | */ 20 | protected Charset charset; 21 | 22 | public DecodedYamlConfiguration() { 23 | this(Charset.forName("UTF-8")); 24 | } 25 | 26 | public DecodedYamlConfiguration(Charset charset) { 27 | this.charset = charset; 28 | } 29 | 30 | @Nullable 31 | public static DecodedYamlConfiguration loadConfiguration(File file){ 32 | Validate.notNull(file, "File cannot be null"); 33 | DecodedYamlConfiguration config = new DecodedYamlConfiguration(); 34 | try { 35 | config.load(file); 36 | } catch (IOException | InvalidConfigurationException e) { 37 | Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, e); 38 | } 39 | return config; 40 | } 41 | 42 | @Override 43 | public void save(File file) throws IOException { 44 | file.mkdirs(); 45 | String data = this.saveToString(); 46 | try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), getCharset())) { 47 | writer.write(data); 48 | } 49 | } 50 | 51 | @Override 52 | public void load(File file) throws IOException, InvalidConfigurationException { 53 | this.load(new InputStreamReader(new FileInputStream(file), getCharset())); 54 | } 55 | 56 | public Charset getCharset() { 57 | return charset; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/config/SerializationException.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.config; 2 | 3 | public class SerializationException extends RuntimeException{ 4 | 5 | public SerializationException() { 6 | } 7 | 8 | public SerializationException(String message) { 9 | super(message); 10 | } 11 | 12 | public SerializationException(Throwable throwable){ 13 | super(throwable); 14 | } 15 | 16 | public SerializationException(String message,Throwable throwable){ 17 | super(message,throwable); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/config/SerializationHelper.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.config; 2 | 3 | import com.google.common.base.Strings; 4 | import com.google.common.collect.Maps; 5 | import org.apache.commons.lang.Validate; 6 | import org.bukkit.configuration.serialization.ConfigurationSerializable; 7 | 8 | import javax.annotation.Nullable; 9 | import java.lang.reflect.Field; 10 | import java.lang.reflect.Modifier; 11 | import java.util.Map; 12 | 13 | public interface SerializationHelper { 14 | 15 | static Map serialize(@Nullable ConfigurationSerializable obj){ 16 | Validate.notNull(obj); 17 | 18 | Map map = Maps.newLinkedHashMap(); 19 | Class clazz = obj.getClass(); 20 | while(ConfigurationSerializable.class.isAssignableFrom(clazz)){ 21 | for(Field field:clazz.getDeclaredFields()){ 22 | int modifiers = field.getModifiers(); 23 | if(Modifier.isFinal(modifiers)||Modifier.isStatic(modifiers)||Modifier.isTransient(modifiers)) 24 | continue; 25 | 26 | field.setAccessible(true); 27 | 28 | String key = field.getName(); 29 | 30 | ConfigItem setting = field.getAnnotation(ConfigItem.class); 31 | if(setting != null && !Strings.isNullOrEmpty(key)) 32 | key = setting.value(); 33 | 34 | try { 35 | map.put(key, field.get(obj)); 36 | } catch (IllegalArgumentException | IllegalAccessException e) { 37 | throw new SerializationException("Serialize failed.",e); 38 | } 39 | } 40 | clazz = clazz.getSuperclass(); 41 | } 42 | 43 | return map; 44 | } 45 | 46 | static T deserialize(T obj, Map map){ 47 | Validate.notNull(obj); 48 | Validate.notNull(map); 49 | 50 | Class clazz = obj.getClass(); 51 | while(ConfigurationSerializable.class.isAssignableFrom(clazz)){ 52 | for(Field field:clazz.getDeclaredFields()){ 53 | int modifiers = field.getModifiers(); 54 | if(Modifier.isFinal(modifiers)||Modifier.isStatic(modifiers)||Modifier.isTransient(modifiers)) 55 | continue; 56 | 57 | field.setAccessible(true); 58 | 59 | String key = field.getName(); 60 | 61 | ConfigItem setting = field.getAnnotation(ConfigItem.class); 62 | if(setting != null && !Strings.isNullOrEmpty(key)) 63 | key = setting.value(); 64 | 65 | if(map.containsKey(key)){ 66 | try { 67 | field.set(obj, map.get(key)); 68 | } catch (IllegalArgumentException | IllegalAccessException e) { 69 | throw new SerializationException("Deserialize failed.",e); 70 | } 71 | } 72 | } 73 | clazz = clazz.getSuperclass(); 74 | } 75 | 76 | return obj; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/conversation/ConversationState.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.conversation; 2 | 3 | public enum ConversationState { 4 | UNSTARTED, 5 | STARTED, 6 | CANCELLED, 7 | COMPLETED; 8 | } 9 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/conversation/request/RequestBigDecimal.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.conversation.request; 2 | 3 | import org.bukkit.Bukkit; 4 | import org.bukkit.event.EventHandler; 5 | import org.bukkit.event.EventPriority; 6 | import org.bukkit.event.Listener; 7 | import org.bukkit.event.player.AsyncPlayerChatEvent; 8 | import org.bukkit.event.player.PlayerCommandPreprocessEvent; 9 | 10 | import team.unstudio.udpl.util.PluginUtils; 11 | 12 | import java.math.BigDecimal; 13 | import java.util.Optional; 14 | 15 | public class RequestBigDecimal extends RequestBase{ 16 | 17 | public static RequestBigDecimal newRequestBigDecimal(){ 18 | return new RequestBigDecimal(); 19 | } 20 | 21 | public static RequestBigDecimal create(){ 22 | return new RequestBigDecimal(); 23 | } 24 | 25 | private final Listener listener = new RequestListener(); 26 | 27 | private BigDecimal result; 28 | 29 | @Override 30 | public void start() { 31 | super.start(); 32 | PluginUtils.registerEvents(listener, getConversation().getPlugin()); 33 | setStarted(true); 34 | sendPrompt(); 35 | } 36 | 37 | @Override 38 | public void dispose() { 39 | super.dispose(); 40 | AsyncPlayerChatEvent.getHandlerList().unregister(listener); 41 | PlayerCommandPreprocessEvent.getHandlerList().unregister(listener); 42 | } 43 | 44 | @Override 45 | public void reset() { 46 | result = null; 47 | } 48 | 49 | @Override 50 | public Optional getResult() { 51 | if(!isCompleted()) 52 | return Optional.empty(); 53 | return Optional.of(result); 54 | } 55 | 56 | private class RequestListener implements Listener{ 57 | @EventHandler(priority = EventPriority.LOWEST) 58 | public void onChat(AsyncPlayerChatEvent event) { 59 | if(!event.getPlayer().equals(getConversation().getPlayer())) 60 | return; 61 | 62 | event.setCancelled(true); 63 | 64 | try{ 65 | BigDecimal invalidate = new BigDecimal(event.getMessage()); 66 | 67 | if(!validate(invalidate)) 68 | return; 69 | 70 | result = invalidate; 71 | Bukkit.getScheduler().runTask(getConversation().getPlugin(), () -> setCompleted(true)); 72 | }catch(NumberFormatException ignored){ 73 | } 74 | } 75 | 76 | @EventHandler(priority = EventPriority.LOWEST) 77 | public void onCommand(PlayerCommandPreprocessEvent event) { 78 | if(!event.getPlayer().equals(getConversation().getPlayer())) 79 | return; 80 | 81 | event.setCancelled(true); 82 | 83 | try{ 84 | BigDecimal invalidate = new BigDecimal(event.getMessage()); 85 | 86 | if(!validate(invalidate)) 87 | return; 88 | 89 | result = invalidate; 90 | setCompleted(true); 91 | }catch(NumberFormatException ignored){ 92 | } 93 | } 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/conversation/request/RequestBigInteger.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.conversation.request; 2 | 3 | import org.bukkit.Bukkit; 4 | import org.bukkit.event.EventHandler; 5 | import org.bukkit.event.EventPriority; 6 | import org.bukkit.event.Listener; 7 | import org.bukkit.event.player.AsyncPlayerChatEvent; 8 | import org.bukkit.event.player.PlayerCommandPreprocessEvent; 9 | 10 | import team.unstudio.udpl.util.PluginUtils; 11 | 12 | import java.math.BigInteger; 13 | import java.util.Optional; 14 | 15 | public class RequestBigInteger extends RequestBase{ 16 | 17 | public static RequestBigInteger newRequestBigInteger(){ 18 | return new RequestBigInteger(); 19 | } 20 | 21 | public static RequestBigInteger create(){ 22 | return new RequestBigInteger(); 23 | } 24 | 25 | private final Listener listener = new RequestListener(); 26 | 27 | private BigInteger result; 28 | 29 | @Override 30 | public void start() { 31 | super.start(); 32 | PluginUtils.registerEvents(listener, getConversation().getPlugin()); 33 | setStarted(true); 34 | sendPrompt(); 35 | } 36 | 37 | @Override 38 | public void dispose() { 39 | super.dispose(); 40 | AsyncPlayerChatEvent.getHandlerList().unregister(listener); 41 | PlayerCommandPreprocessEvent.getHandlerList().unregister(listener); 42 | } 43 | 44 | @Override 45 | public void reset() { 46 | result = null; 47 | } 48 | 49 | @Override 50 | public Optional getResult() { 51 | if(!isCompleted()) 52 | return Optional.empty(); 53 | return Optional.of(result); 54 | } 55 | 56 | private class RequestListener implements Listener{ 57 | @EventHandler(priority = EventPriority.LOWEST) 58 | public void onChat(AsyncPlayerChatEvent event) { 59 | if(!event.getPlayer().equals(getConversation().getPlayer())) 60 | return; 61 | 62 | event.setCancelled(true); 63 | 64 | try{ 65 | BigInteger invalidate = new BigInteger(event.getMessage()); 66 | 67 | if(!validate(invalidate)) 68 | return; 69 | 70 | result = invalidate; 71 | Bukkit.getScheduler().runTask(getConversation().getPlugin(), () -> setCompleted(true)); 72 | }catch(NumberFormatException ignored){ 73 | } 74 | } 75 | 76 | @EventHandler(priority = EventPriority.LOWEST) 77 | public void onCommand(PlayerCommandPreprocessEvent event) { 78 | if(!event.getPlayer().equals(getConversation().getPlayer())) 79 | return; 80 | 81 | event.setCancelled(true); 82 | 83 | try{ 84 | BigInteger invalidate = new BigInteger(event.getMessage()); 85 | 86 | if(!validate(invalidate)) 87 | return; 88 | 89 | result = invalidate; 90 | setCompleted(true); 91 | }catch(NumberFormatException ignored){ 92 | } 93 | } 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/conversation/request/RequestBlock.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.conversation.request; 2 | 3 | import java.util.Optional; 4 | 5 | import org.bukkit.block.Block; 6 | import org.bukkit.event.EventHandler; 7 | import org.bukkit.event.EventPriority; 8 | import org.bukkit.event.Listener; 9 | import org.bukkit.event.player.PlayerInteractEvent; 10 | 11 | import team.unstudio.udpl.util.PluginUtils; 12 | 13 | public class RequestBlock extends RequestBase{ 14 | 15 | public static RequestBlock newRequestBlock(){ 16 | return new RequestBlock(); 17 | } 18 | 19 | public static RequestBlock create(){ 20 | return new RequestBlock(); 21 | } 22 | 23 | private final Listener listener = new RequestListener(); 24 | 25 | private Block result; 26 | 27 | @Override 28 | public void start() { 29 | super.start(); 30 | PluginUtils.registerEvents(listener, getConversation().getPlugin()); 31 | setStarted(true); 32 | sendPrompt(); 33 | } 34 | 35 | @Override 36 | public void dispose() { 37 | super.dispose(); 38 | PlayerInteractEvent.getHandlerList().unregister(listener); 39 | } 40 | 41 | @Override 42 | public void reset() { 43 | result = null; 44 | } 45 | 46 | @Override 47 | public Optional getResult() { 48 | if(!isCompleted()) 49 | return Optional.empty(); 50 | return Optional.of(result); 51 | } 52 | 53 | private class RequestListener implements Listener{ 54 | 55 | @EventHandler(priority = EventPriority.LOWEST) 56 | public void onInteract(PlayerInteractEvent event){ 57 | if(!event.getPlayer().equals(getConversation().getPlayer())) 58 | return; 59 | 60 | event.setCancelled(true); 61 | 62 | Block invalidate = event.getClickedBlock(); 63 | 64 | if (!validate(invalidate)) 65 | return; 66 | 67 | result = invalidate; 68 | setCompleted(true); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/conversation/request/RequestConfirm.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.conversation.request; 2 | 3 | import java.util.Optional; 4 | 5 | import org.bukkit.Bukkit; 6 | import org.bukkit.event.EventHandler; 7 | import org.bukkit.event.EventPriority; 8 | import org.bukkit.event.Listener; 9 | import org.bukkit.event.player.AsyncPlayerChatEvent; 10 | import org.bukkit.event.player.PlayerCommandPreprocessEvent; 11 | 12 | import team.unstudio.udpl.util.PluginUtils; 13 | 14 | public class RequestConfirm extends RequestBase{ 15 | 16 | public static RequestConfirm newRequestConfirm(){ 17 | return new RequestConfirm(); 18 | } 19 | 20 | public static RequestConfirm create(){ 21 | return new RequestConfirm(); 22 | } 23 | 24 | private final Listener listener = new RequestListener(); 25 | 26 | private boolean result; 27 | 28 | @Override 29 | public void start() { 30 | super.start(); 31 | PluginUtils.registerEvents(listener, getConversation().getPlugin()); 32 | setStarted(true); 33 | sendPrompt(); 34 | } 35 | 36 | @Override 37 | public void dispose() { 38 | super.dispose(); 39 | AsyncPlayerChatEvent.getHandlerList().unregister(listener); 40 | PlayerCommandPreprocessEvent.getHandlerList().unregister(listener); 41 | } 42 | 43 | @Override 44 | public Optional getResult() { 45 | if(!isCompleted()) 46 | return Optional.empty(); 47 | return Optional.of(result); 48 | } 49 | 50 | @Override 51 | public void reset() { 52 | result = false; 53 | } 54 | 55 | private class RequestListener implements Listener{ 56 | @EventHandler(priority = EventPriority.LOWEST) 57 | public void onChat(AsyncPlayerChatEvent event) { 58 | if(!event.getPlayer().equals(getConversation().getPlayer())) 59 | return; 60 | 61 | event.setCancelled(true); 62 | 63 | result = "confirm".equals(event.getMessage().toLowerCase()); 64 | Bukkit.getScheduler().runTask(getConversation().getPlugin(), ()->setCompleted(true)); 65 | } 66 | 67 | @EventHandler(priority = EventPriority.LOWEST) 68 | public void onCommand(PlayerCommandPreprocessEvent event) { 69 | if(!event.getPlayer().equals(getConversation().getPlayer())) 70 | return; 71 | 72 | event.setCancelled(true); 73 | 74 | result = "/confirm".equals(event.getMessage().toLowerCase()); 75 | setCompleted(true); 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/conversation/request/RequestCustomRawMessage.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.conversation.request; 2 | 3 | public class RequestCustomRawMessage { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/conversation/request/RequestDouble.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.conversation.request; 2 | 3 | import org.bukkit.Bukkit; 4 | import org.bukkit.event.EventHandler; 5 | import org.bukkit.event.EventPriority; 6 | import org.bukkit.event.Listener; 7 | import org.bukkit.event.player.AsyncPlayerChatEvent; 8 | import org.bukkit.event.player.PlayerCommandPreprocessEvent; 9 | 10 | import team.unstudio.udpl.util.PluginUtils; 11 | 12 | import java.util.Optional; 13 | 14 | public class RequestDouble extends RequestBase{ 15 | 16 | public static RequestDouble newRequestDouble(){ 17 | return new RequestDouble(); 18 | } 19 | 20 | public static RequestDouble create(){ 21 | return new RequestDouble(); 22 | } 23 | 24 | private final Listener listener = new RequestListener(); 25 | 26 | private Double result; 27 | 28 | @Override 29 | public void start() { 30 | super.start(); 31 | PluginUtils.registerEvents(listener, getConversation().getPlugin()); 32 | setStarted(true); 33 | sendPrompt(); 34 | } 35 | 36 | @Override 37 | public void dispose() { 38 | super.dispose(); 39 | AsyncPlayerChatEvent.getHandlerList().unregister(listener); 40 | PlayerCommandPreprocessEvent.getHandlerList().unregister(listener); 41 | } 42 | 43 | @Override 44 | public Optional getResult() { 45 | if(!isCompleted()) 46 | return Optional.empty(); 47 | return Optional.of(result); 48 | } 49 | 50 | @Override 51 | public void reset() { 52 | result = null; 53 | } 54 | 55 | private class RequestListener implements Listener{ 56 | @EventHandler(priority = EventPriority.LOWEST) 57 | public void onChat(AsyncPlayerChatEvent event) { 58 | if(!event.getPlayer().equals(getConversation().getPlayer())) 59 | return; 60 | 61 | event.setCancelled(true); 62 | 63 | try{ 64 | Double invalidate = Double.valueOf(event.getMessage()); 65 | 66 | if(!validate(invalidate)) 67 | return; 68 | 69 | result = invalidate; 70 | Bukkit.getScheduler().runTask(getConversation().getPlugin(), () -> setCompleted(true)); 71 | }catch(NumberFormatException ignored){ 72 | } 73 | } 74 | 75 | @EventHandler(priority = EventPriority.LOWEST) 76 | public void onCommand(PlayerCommandPreprocessEvent event) { 77 | if(!event.getPlayer().equals(getConversation().getPlayer())) 78 | return; 79 | 80 | event.setCancelled(true); 81 | 82 | try{ 83 | Double invalidate = Double.valueOf(event.getMessage()); 84 | 85 | if(!validate(invalidate)) 86 | return; 87 | 88 | result = invalidate; 89 | setCompleted(true); 90 | }catch(NumberFormatException ignored){ 91 | } 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/conversation/request/RequestEntity.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.conversation.request; 2 | 3 | import java.util.Optional; 4 | 5 | import org.bukkit.entity.Entity; 6 | import org.bukkit.event.EventHandler; 7 | import org.bukkit.event.EventPriority; 8 | import org.bukkit.event.Listener; 9 | import org.bukkit.event.entity.EntityDamageByEntityEvent; 10 | import org.bukkit.event.player.PlayerInteractEntityEvent; 11 | 12 | import team.unstudio.udpl.util.PluginUtils; 13 | 14 | public class RequestEntity extends RequestBase{ 15 | 16 | public static RequestEntity newRequestEntity(){ 17 | return new RequestEntity(); 18 | } 19 | 20 | public static RequestEntity create(){ 21 | return new RequestEntity(); 22 | } 23 | 24 | private final Listener listener = new RequestListener(); 25 | 26 | private Entity result; 27 | 28 | @Override 29 | public void start() { 30 | super.start(); 31 | PluginUtils.registerEvents(listener, getConversation().getPlugin()); 32 | setStarted(true); 33 | sendPrompt(); 34 | } 35 | 36 | @Override 37 | public void dispose() { 38 | super.dispose(); 39 | EntityDamageByEntityEvent.getHandlerList().unregister(listener); 40 | PlayerInteractEntityEvent.getHandlerList().unregister(listener); 41 | } 42 | 43 | @Override 44 | public Optional getResult() { 45 | if(!isCompleted()) 46 | return Optional.empty(); 47 | return Optional.of(result); 48 | } 49 | 50 | @Override 51 | public void reset() { 52 | result = null; 53 | } 54 | 55 | private class RequestListener implements Listener{ 56 | 57 | @EventHandler(priority = EventPriority.LOWEST) 58 | public void onClick(EntityDamageByEntityEvent event){ 59 | if(!event.getDamager().equals(getConversation().getPlayer())) 60 | return; 61 | 62 | event.setCancelled(true); 63 | 64 | Entity invalidate = event.getEntity(); 65 | 66 | if (!validate(invalidate)) 67 | return; 68 | 69 | result = invalidate; 70 | setCompleted(true); 71 | } 72 | 73 | @EventHandler(priority = EventPriority.LOWEST) 74 | public void onInteractEntity(PlayerInteractEntityEvent event){ 75 | if(!event.getPlayer().equals(getConversation().getPlayer())) 76 | return; 77 | 78 | event.setCancelled(true); 79 | 80 | Entity invalidate = event.getRightClicked(); 81 | 82 | if (!validate(invalidate)) 83 | return; 84 | 85 | result = invalidate; 86 | setCompleted(true); 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/conversation/request/RequestInteger.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.conversation.request; 2 | 3 | import org.bukkit.Bukkit; 4 | import org.bukkit.event.EventHandler; 5 | import org.bukkit.event.EventPriority; 6 | import org.bukkit.event.Listener; 7 | import org.bukkit.event.player.AsyncPlayerChatEvent; 8 | import org.bukkit.event.player.PlayerCommandPreprocessEvent; 9 | 10 | import team.unstudio.udpl.util.PluginUtils; 11 | 12 | import java.util.Optional; 13 | 14 | public class RequestInteger extends RequestBase{ 15 | 16 | public static RequestInteger newRequestInteger(){ 17 | return new RequestInteger(); 18 | } 19 | 20 | public static RequestInteger create(){ 21 | return new RequestInteger(); 22 | } 23 | 24 | private final Listener listener = new RequestListener(); 25 | 26 | private Integer result; 27 | 28 | @Override 29 | public void start() { 30 | super.start(); 31 | PluginUtils.registerEvents(listener, getConversation().getPlugin()); 32 | setStarted(true); 33 | sendPrompt(); 34 | } 35 | 36 | @Override 37 | public void dispose() { 38 | super.dispose(); 39 | AsyncPlayerChatEvent.getHandlerList().unregister(listener); 40 | PlayerCommandPreprocessEvent.getHandlerList().unregister(listener); 41 | } 42 | 43 | @Override 44 | public void reset() { 45 | result = null; 46 | } 47 | 48 | @Override 49 | public Optional getResult() { 50 | if(!isCompleted()) 51 | return Optional.empty(); 52 | return Optional.of(result); 53 | } 54 | 55 | private class RequestListener implements Listener{ 56 | @EventHandler(priority = EventPriority.LOWEST) 57 | public void onChat(AsyncPlayerChatEvent event) { 58 | if(!event.getPlayer().equals(getConversation().getPlayer())) 59 | return; 60 | 61 | event.setCancelled(true); 62 | 63 | try{ 64 | Integer invalidate = Integer.valueOf(event.getMessage()); 65 | 66 | if(!validate(invalidate)) 67 | return; 68 | 69 | result = invalidate; 70 | Bukkit.getScheduler().runTask(getConversation().getPlugin(), () -> setCompleted(true)); 71 | }catch(NumberFormatException ignored){ 72 | } 73 | } 74 | 75 | @EventHandler(priority = EventPriority.LOWEST) 76 | public void onCommand(PlayerCommandPreprocessEvent event) { 77 | if(!event.getPlayer().equals(getConversation().getPlayer())) 78 | return; 79 | 80 | event.setCancelled(true); 81 | 82 | try{ 83 | Integer invalidate = Integer.valueOf(event.getMessage()); 84 | 85 | if(!validate(invalidate)) 86 | return; 87 | 88 | result = invalidate; 89 | setCompleted(true); 90 | }catch(NumberFormatException ignored){ 91 | } 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/conversation/request/RequestPlayer.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.conversation.request; 2 | 3 | import java.util.Optional; 4 | 5 | import org.bukkit.Bukkit; 6 | import org.bukkit.entity.Player; 7 | import org.bukkit.event.EventHandler; 8 | import org.bukkit.event.EventPriority; 9 | import org.bukkit.event.Listener; 10 | import org.bukkit.event.player.AsyncPlayerChatEvent; 11 | 12 | import team.unstudio.udpl.util.PluginUtils; 13 | 14 | public class RequestPlayer extends RequestBase{ 15 | 16 | public static RequestPlayer newRequestPlayer(){ 17 | return new RequestPlayer(); 18 | } 19 | 20 | public static RequestPlayer create(){ 21 | return new RequestPlayer(); 22 | } 23 | 24 | private final Listener listener = new RequestListener(); 25 | 26 | private Player result; 27 | 28 | @Override 29 | public void start() { 30 | super.start(); 31 | PluginUtils.registerEvents(listener, getConversation().getPlugin()); 32 | setStarted(true); 33 | sendPrompt(); 34 | } 35 | 36 | @Override 37 | public void dispose() { 38 | super.dispose(); 39 | AsyncPlayerChatEvent.getHandlerList().unregister(listener); 40 | } 41 | 42 | @Override 43 | public Optional getResult() { 44 | if(!isCompleted()) 45 | return Optional.empty(); 46 | return Optional.of(result); 47 | } 48 | 49 | @Override 50 | public void reset() { 51 | result = null; 52 | } 53 | 54 | private class RequestListener implements Listener{ 55 | @EventHandler(priority = EventPriority.LOWEST) 56 | public void onChat(AsyncPlayerChatEvent event) { 57 | if(!event.getPlayer().equals(getConversation().getPlayer())) 58 | return; 59 | 60 | event.setCancelled(true); 61 | 62 | Player result = Bukkit.getPlayerExact(event.getMessage()); 63 | if(result == null) 64 | callValidateFailed(); 65 | 66 | if(!validate(result)) 67 | return; 68 | 69 | RequestPlayer.this.result = result; 70 | Bukkit.getScheduler().runTask(getConversation().getPlugin(), ()->setCompleted(true)); 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/conversation/request/RequestString.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.conversation.request; 2 | 3 | import java.util.Optional; 4 | 5 | import org.bukkit.Bukkit; 6 | import org.bukkit.event.EventHandler; 7 | import org.bukkit.event.EventPriority; 8 | import org.bukkit.event.Listener; 9 | import org.bukkit.event.player.AsyncPlayerChatEvent; 10 | import org.bukkit.event.player.PlayerCommandPreprocessEvent; 11 | 12 | import team.unstudio.udpl.util.PluginUtils; 13 | 14 | public class RequestString extends RequestBase{ 15 | 16 | public static RequestString newRequestString(){ 17 | return new RequestString(); 18 | } 19 | 20 | public static RequestString create(){ 21 | return new RequestString(); 22 | } 23 | 24 | private final Listener listener = new RequestListener(); 25 | 26 | private String result; 27 | 28 | @Override 29 | public void start() { 30 | super.start(); 31 | PluginUtils.registerEvents(listener, getConversation().getPlugin()); 32 | setStarted(true); 33 | sendPrompt(); 34 | } 35 | 36 | @Override 37 | public void dispose() { 38 | super.dispose(); 39 | AsyncPlayerChatEvent.getHandlerList().unregister(listener); 40 | PlayerCommandPreprocessEvent.getHandlerList().unregister(listener); 41 | } 42 | 43 | @Override 44 | public void reset() { 45 | result = null; 46 | } 47 | 48 | @Override 49 | public Optional getResult() { 50 | if(!isCompleted()) 51 | return Optional.empty(); 52 | return Optional.of(result); 53 | } 54 | 55 | private class RequestListener implements Listener{ 56 | @EventHandler(priority = EventPriority.LOWEST) 57 | public void onChat(AsyncPlayerChatEvent event) { 58 | if(!event.getPlayer().equals(getConversation().getPlayer())) 59 | return; 60 | 61 | event.setCancelled(true); 62 | 63 | if(!validate(event.getMessage())) 64 | return; 65 | 66 | result = event.getMessage(); 67 | Bukkit.getScheduler().runTask(getConversation().getPlugin(), ()->setCompleted(true)); 68 | } 69 | 70 | @EventHandler(priority = EventPriority.LOWEST) 71 | public void onCommand(PlayerCommandPreprocessEvent event) { 72 | if(!event.getPlayer().equals(getConversation().getPlayer())) 73 | return; 74 | 75 | event.setCancelled(true); 76 | 77 | if(!validate(event.getMessage())) 78 | return; 79 | 80 | result = event.getMessage(); 81 | setCompleted(true); 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/event/FakeSignUpdateEvent.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.event; 2 | 3 | import org.bukkit.entity.Player; 4 | import org.bukkit.event.HandlerList; 5 | import org.bukkit.event.player.PlayerEvent; 6 | 7 | public class FakeSignUpdateEvent extends PlayerEvent{ 8 | 9 | private final String[] lines; 10 | 11 | public FakeSignUpdateEvent(Player who,String[] lines) { 12 | super(who); 13 | this.lines = lines; 14 | } 15 | 16 | public String[] getLines() { 17 | return lines; 18 | } 19 | 20 | private static final HandlerList HANDLER_LIST = new HandlerList(); 21 | 22 | @Override 23 | public HandlerList getHandlers() { 24 | return HANDLER_LIST; 25 | } 26 | 27 | public static HandlerList getHandlerList() { 28 | return HANDLER_LIST; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/exception/MemberMappingException.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.exception; 2 | 3 | import java.io.IOException; 4 | import java.security.PrivilegedActionException; 5 | 6 | public class MemberMappingException extends IOException { 7 | /** 8 | * Constructs an {@code IOException} with {@code null} 9 | * as its error detail message. 10 | */ 11 | public MemberMappingException() { 12 | } 13 | 14 | /** 15 | * Constructs an {@code IOException} with the specified detail message. 16 | * 17 | * @param message The detail message (which is saved for later retrieval 18 | * by the {@link #getMessage()} method) 19 | */ 20 | public MemberMappingException(String message) { 21 | super(message); 22 | } 23 | 24 | /** 25 | * Constructs an {@code IOException} with the specified detail message 26 | * and cause. 27 | *

28 | *

Note that the detail message associated with {@code cause} is 29 | * not automatically incorporated into this exception's detail 30 | * message. 31 | * 32 | * @param message The detail message (which is saved for later retrieval 33 | * by the {@link #getMessage()} method) 34 | * @param cause The cause (which is saved for later retrieval by the 35 | * {@link #getCause()} method). (A null value is permitted, 36 | * and indicates that the cause is nonexistent or unknown.) 37 | * @since 1.6 38 | */ 39 | public MemberMappingException(String message, Throwable cause) { 40 | super(message, cause); 41 | } 42 | 43 | /** 44 | * Constructs an {@code IOException} with the specified cause and a 45 | * detail message of {@code (cause==null ? null : cause.toString())} 46 | * (which typically contains the class and detail message of {@code cause}). 47 | * This constructor is useful for IO exceptions that are little more 48 | * than wrappers for other throwables. 49 | * 50 | * @param cause The cause (which is saved for later retrieval by the 51 | * {@link #getCause()} method). (A null value is permitted, 52 | * and indicates that the cause is nonexistent or unknown.) 53 | * @since 1.6 54 | */ 55 | public MemberMappingException(Throwable cause) { 56 | super(cause); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/i18n/BaseI18n.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.i18n; 2 | 3 | import java.util.Locale; 4 | 5 | public abstract class BaseI18n implements I18n { 6 | /** 7 | * default locale from {@link Locale#getDefault()} 8 | */ 9 | private Locale defaultLocale = Locale.getDefault(); 10 | 11 | private I18n parent; 12 | 13 | @Override 14 | public I18n getParent() { 15 | return parent; 16 | } 17 | 18 | @Override 19 | public void setParent(I18n parent) { 20 | this.parent = parent; 21 | } 22 | 23 | @Override 24 | public Locale getDefaultLocale() { 25 | return defaultLocale; 26 | } 27 | 28 | @Override 29 | public void setDefaultLocale(Locale defaultLocale) { 30 | this.defaultLocale = defaultLocale; 31 | } 32 | 33 | @Override 34 | public void setDefaultLocale(String defaultLocale) { 35 | this.defaultLocale = Locale.forLanguageTag(defaultLocale); 36 | } 37 | 38 | 39 | } 40 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/i18n/YamlI18n.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.i18n; 2 | 3 | import org.apache.commons.lang3.ArrayUtils; 4 | import org.bukkit.Bukkit; 5 | import org.bukkit.configuration.Configuration; 6 | import team.unstudio.udpl.UDPLib; 7 | import team.unstudio.udpl.config.ConfigurationHelper; 8 | import javax.annotation.Nonnull; 9 | import java.io.File; 10 | import java.net.URL; 11 | import java.util.Collections; 12 | import java.util.HashMap; 13 | import java.util.Locale; 14 | import java.util.Map; 15 | import java.util.logging.Level; 16 | 17 | public class YamlI18n extends BaseI18n { 18 | protected final Map cache; 19 | 20 | public YamlI18n(@Nonnull Map map) { 21 | this.cache = map; 22 | } 23 | 24 | @Override 25 | public String localize(Locale locale, String key){ 26 | if(cache.containsKey(locale)) 27 | return cache.get(locale).getString(key, key); 28 | else if(cache.containsKey(getDefaultLocale())) 29 | return cache.get(getDefaultLocale()).getString(key, key); 30 | else if(getParent() != null) 31 | return getParent().localize(locale, key); 32 | else 33 | return key; 34 | } 35 | 36 | @SuppressWarnings("ConstantConditions") 37 | public static YamlI18n fromFile(@Nonnull File path) { 38 | if(!path.exists()) 39 | throw new IllegalArgumentException("Path isn't exist."); 40 | if(!path.isDirectory()) 41 | throw new IllegalArgumentException("Path isn't directory."); 42 | 43 | Map map = new HashMap<>(); 44 | 45 | for(File file:path.listFiles((file,name)->name.endsWith(".yml"))){ 46 | Locale locale = Locale.forLanguageTag(file.getName().substring(0, file.getName().lastIndexOf('.')).replaceAll("_", "-")); 47 | Configuration config = ConfigurationHelper.loadConfiguration(file); 48 | if(config != null) 49 | map.put(locale, config); 50 | } 51 | return new YamlI18n(map); 52 | } 53 | 54 | public static YamlI18n fromClassLoader(@Nonnull ClassLoader classLoader, @Nonnull String path) { 55 | Map map = new HashMap<>(); 56 | 57 | try { 58 | for (URL url : Collections.list(classLoader.getResources(path))) { 59 | File filePath = new File(url.toURI()); 60 | for (File file : (File[]) ArrayUtils.nullToEmpty(filePath.listFiles((file, name) -> name.endsWith(".yml")))) { 61 | Locale locale = Locale.forLanguageTag(file.getName().substring(0, file.getName().lastIndexOf('.')).replaceAll("_", "-")); 62 | Configuration config = ConfigurationHelper.loadConfiguration(file); 63 | if(config != null) 64 | map.put(locale, config); 65 | } 66 | } 67 | } catch (Exception e) { 68 | UDPLib.getLogger().error("Cannot read language file from class path", e); 69 | } 70 | 71 | return new YamlI18n(map); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/i18n/slang/CachedSLang.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.i18n.slang; 2 | 3 | import java.util.HashMap; 4 | import java.util.Locale; 5 | import java.util.Map; 6 | 7 | /** 8 | * Created by trychen on 17/7/11. 9 | */ 10 | public class CachedSLang { 11 | /** 12 | * 语言 13 | */ 14 | public final Locale locale; 15 | 16 | /** 17 | * 数据 18 | */ 19 | protected final Map map = new HashMap<>(); 20 | 21 | /** 22 | * 通过语言初始化一个 CachedSLang 23 | */ 24 | public CachedSLang(Locale locale) { 25 | this.locale = locale; 26 | } 27 | 28 | /** 29 | * 获取本地化文本 30 | */ 31 | public String get(String key){ 32 | String s = map.get(key); 33 | if (s == null) return key; 34 | else return s; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/i18n/slang/SLangSpliter.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.i18n.slang; 2 | 3 | import java.util.Arrays; 4 | import java.util.Locale; 5 | import java.util.stream.Collectors; 6 | 7 | /** 8 | * Created by trychen on 17/7/11. 9 | */ 10 | public interface SLangSpliter { 11 | /** 12 | * 分隔符 13 | */ 14 | String DEFAULT_SPLITER = "|"; 15 | 16 | /** 17 | * 使用默认的分割符号分割文本到 CachedSLang 18 | * 19 | * @param list 要分割的文本 20 | */ 21 | static CachedSLang[] split(String[] list) { 22 | return split(DEFAULT_SPLITER, list); 23 | } 24 | 25 | /** 26 | * 分割文本到 CachedSLang 27 | * 28 | * @param separator 分割符 (Regex) 29 | * @param list 文本行数据 30 | */ 31 | static CachedSLang[] split(String separator, String[] list) { 32 | // 清理注释 33 | list = Arrays.stream(list).filter(it -> !it.startsWith("#")).collect(Collectors.toList()).toArray(new String[0]); 34 | 35 | // clean 36 | if (list.length < 2) return new CachedSLang[0]; 37 | 38 | // the first line's string array 39 | String[] locals = list[0].split(separator); 40 | String[][] data = new String[list.length][locals.length]; 41 | 42 | data[0] = locals; 43 | 44 | // init data array 45 | for (int i = 1; i < list.length; i++) 46 | data[i] = Arrays.stream(list[i].split(separator)).map(String::trim).toArray(String[]::new); 47 | 48 | 49 | // get the head key or locale 50 | CachedSLang[] langs = new CachedSLang[locals.length]; 51 | for (int i = 0; i < locals.length; i++) 52 | if (!locals[i].trim().equalsIgnoreCase("key")) 53 | langs[i] = new CachedSLang(Locale.forLanguageTag(locals[i].trim().replaceAll("_", "-"))); 54 | 55 | for (int i = 1; i < data.length; i++) 56 | for (int j = 1; j < data[i].length; j++) { 57 | // check if trim 58 | String lang = data[i][j]; 59 | if (lang.endsWith("∞")) lang = lang.substring(0, lang.length() - 1); 60 | langs[j].map.put(data[i][0], lang); 61 | } 62 | 63 | 64 | CachedSLang[] newLangs; 65 | if (langs[0] == null) { 66 | newLangs = new CachedSLang[langs.length - 1]; 67 | System.arraycopy(langs, 1, newLangs, 0, langs.length - 1); 68 | } else newLangs = langs; 69 | 70 | return newLangs; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/item/ItemHelper.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.item; 2 | 3 | import static team.unstudio.udpl.util.reflect.NMSReflectionUtils.*; 4 | import org.bukkit.inventory.ItemStack; 5 | 6 | import team.unstudio.udpl.UDPLib; 7 | import javax.annotation.Nullable; 8 | 9 | public interface ItemHelper { 10 | 11 | /** 12 | * 转换为JSON格式 13 | * @param itemStack 物品 14 | */ 15 | @Nullable 16 | static String toJson(ItemStack itemStack) { 17 | try { 18 | return ItemStack$save() 19 | .invoke(CraftItemStack$asNMSCopy().invoke(null, itemStack), NBTTagCompound$init().newInstance()) 20 | .toString(); 21 | } catch (ReflectiveOperationException e) { 22 | UDPLib.debug(e); 23 | } 24 | return null; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/NMSException.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms; 2 | 3 | public class NMSException extends RuntimeException { 4 | public NMSException() { 5 | } 6 | 7 | public NMSException(String message) { 8 | super(message); 9 | } 10 | 11 | public NMSException(Throwable throwable) { 12 | super(throwable); 13 | } 14 | 15 | public NMSException(String message, Throwable throwable) { 16 | super(message, throwable); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/NmsHelper.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms; 2 | 3 | import org.bukkit.block.BlockState; 4 | import org.bukkit.entity.Entity; 5 | import org.bukkit.inventory.ItemStack; 6 | 7 | import team.unstudio.udpl.annotation.Init; 8 | import team.unstudio.udpl.nms.entity.NmsEntity; 9 | import team.unstudio.udpl.nms.inventory.NmsItemStack; 10 | import team.unstudio.udpl.nms.nbt.NmsNBT; 11 | import team.unstudio.udpl.nms.tileentity.NmsTileEntity; 12 | 13 | public final class NmsHelper { 14 | 15 | private NmsHelper(){} 16 | 17 | @Init("nms_manager") 18 | private static NmsManager NMS_MANAGER; 19 | 20 | /** 21 | * 获取 {@link net.minecraft.server} 与 {@link team.unstudio.udpl.nms.nbt} 的帮助类实例 22 | */ 23 | public static NmsNBT getNmsNBT(){ 24 | checkNmsSupported(); 25 | return NMS_MANAGER.getNmsNBT(); 26 | } 27 | 28 | 29 | /** 30 | * 创建一个{@link NmsItemStack}对象 31 | */ 32 | public static NmsItemStack createNmsItemStack(ItemStack itemStack){ 33 | checkNmsSupported(); 34 | return NMS_MANAGER.createNmsItemStack(itemStack); 35 | } 36 | 37 | /** 38 | * 创建一个{@link NmsEntity}对象 39 | */ 40 | public static NmsEntity createNmsEntity(Entity entity){ 41 | checkNmsSupported(); 42 | return NMS_MANAGER.createNmsEntity(entity); 43 | } 44 | 45 | /** 46 | * 创建一个{@link NmsTileEntity}对象 47 | */ 48 | public static NmsTileEntity createNmsTileEntity(BlockState blockState){ 49 | checkNmsSupported(); 50 | return NMS_MANAGER.createNmsTileEntity(blockState); 51 | } 52 | 53 | /** 54 | * 获取是否支持Nms操作 55 | */ 56 | public static boolean isNmsSupported() { 57 | return NMS_MANAGER != null; 58 | } 59 | 60 | private static void checkNmsSupported() { 61 | if(!isNmsSupported()) 62 | throw new NMSException("Unsupported Nms."); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/NmsManager.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms; 2 | 3 | import org.bukkit.block.BlockState; 4 | import org.bukkit.entity.Entity; 5 | import org.bukkit.inventory.ItemStack; 6 | 7 | import team.unstudio.udpl.nms.entity.NmsEntity; 8 | import team.unstudio.udpl.nms.inventory.NmsItemStack; 9 | import team.unstudio.udpl.nms.nbt.NmsNBT; 10 | import team.unstudio.udpl.nms.tileentity.NmsTileEntity; 11 | 12 | public interface NmsManager { 13 | NmsNBT getNmsNBT(); 14 | 15 | NmsItemStack createNmsItemStack(ItemStack itemStack); 16 | 17 | NmsEntity createNmsEntity(Entity entity); 18 | 19 | NmsTileEntity createNmsTileEntity(BlockState state); 20 | } 21 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/entity/NmsEntity.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.entity; 2 | 3 | import java.util.Set; 4 | 5 | import org.bukkit.entity.Entity; 6 | import team.unstudio.udpl.nms.NmsHelper; 7 | import team.unstudio.udpl.nms.nbt.NBTTagCompound; 8 | 9 | public interface NmsEntity { 10 | 11 | Entity getBukkitEntity(); 12 | 13 | NBTTagCompound save(); 14 | 15 | void load(NBTTagCompound nbt); 16 | 17 | Set getScoreboardTags(); 18 | 19 | boolean addScoreboardTag(String tag); 20 | 21 | boolean removeScoreboardTag(String tag); 22 | 23 | static NmsEntity createNmsEntity(Entity entity){ 24 | return NmsHelper.createNmsEntity(entity); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/entity/NmsLivingEntity.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.entity; 2 | 3 | import org.bukkit.entity.LivingEntity; 4 | 5 | public interface NmsLivingEntity extends NmsEntity{ 6 | 7 | LivingEntity getBukkitEntity(); 8 | } 9 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/entity/NmsPlayer.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.entity; 2 | 3 | import org.bukkit.entity.Player; 4 | 5 | import java.util.Locale; 6 | 7 | public interface NmsPlayer extends NmsLivingEntity{ 8 | 9 | Player getBukkitEntity(); 10 | 11 | Locale getLocale(); 12 | 13 | /** 14 | * 发送一个包 15 | */ 16 | void sendPacket(Object packet); 17 | 18 | /** 19 | * 发送一个ActionBar 20 | */ 21 | void sendActionBar(String message); 22 | 23 | /** 24 | * 发送一个Title 25 | */ 26 | void sendTitle(String title, String subtitle); 27 | 28 | /** 29 | * 重置Title 30 | */ 31 | void resetTitle(); 32 | } 33 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/entity/fake/FakeEntity.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.entity.fake; 2 | 3 | public interface FakeEntity { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/entity/fake/FakeItem.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.entity.fake; 2 | 3 | public interface FakeItem { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/inventory/NmsItemStack.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.inventory; 2 | 3 | import org.bukkit.inventory.ItemStack; 4 | import team.unstudio.udpl.nms.NmsHelper; 5 | import team.unstudio.udpl.nms.nbt.NBTTagCompound; 6 | 7 | /** 8 | * {@link NmsHelper#createNmsItemStack(ItemStack)} 9 | */ 10 | public interface NmsItemStack { 11 | 12 | /** 13 | * 获取{@link ItemStack}实例 14 | */ 15 | ItemStack getBukkitItemStack(); 16 | 17 | /** 18 | * 获取ItemStack的NBT数据 19 | * {@link NmsItemStack#setTag(NBTTagCompound)} 20 | */ 21 | NBTTagCompound getTag(); 22 | 23 | /** 24 | * 设置ItemStack的NBT数据 25 | * {@link NmsItemStack#getTag()} 26 | */ 27 | void setTag(NBTTagCompound nbt); 28 | 29 | /** 30 | * 是否存在NBT数据 31 | * [{@link NmsItemStack#getTag()} 32 | */ 33 | boolean hasTag(); 34 | 35 | /** 36 | * 从NBT数据载入ItemStack 37 | * {@link NmsItemStack#save()} 38 | */ 39 | void load(NBTTagCompound nbt); 40 | 41 | /** 42 | * 保持ItemStack为NBT数据 43 | * {@link NmsItemStack#load(NBTTagCompound)} 44 | */ 45 | NBTTagCompound save(); 46 | 47 | /** 48 | * 创建一个NmsItemStack对象 49 | */ 50 | static NmsItemStack createNmsItemStack(ItemStack itemStack){ 51 | return NmsHelper.createNmsItemStack(itemStack); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/mapping/MappingHelper.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.mapping; 2 | 3 | import team.unstudio.udpl.UDPLib; 4 | import team.unstudio.udpl.annotation.Init; 5 | import team.unstudio.udpl.exception.MemberMappingException; 6 | import team.unstudio.udpl.util.ServerUtils; 7 | 8 | public final class MappingHelper { 9 | 10 | private MappingHelper() { 11 | } 12 | 13 | private static MemberMapping memberMapping; 14 | 15 | public static MemberMapping getMemberMapping() { 16 | return memberMapping; 17 | } 18 | 19 | @Init 20 | public static void loadMapping() { 21 | loadMapping(ServerUtils.getMinecraftVersion()); 22 | } 23 | 24 | private static void loadMapping(String version) { 25 | try { 26 | memberMapping = MemberMapping.fromClassLoader(version); 27 | UDPLib.getLogger().info("Loaded mapping " + version); 28 | } catch (MemberMappingException e) { 29 | UDPLib.debug(e); 30 | memberMapping = null; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/nbt/NBTBase.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.nbt; 2 | 3 | import org.bukkit.configuration.serialization.ConfigurationSerializable; 4 | 5 | public abstract class NBTBase implements ConfigurationSerializable{ 6 | private NBTBaseType type; 7 | 8 | protected NBTBase(NBTBaseType type) { 9 | this.type = type; 10 | } 11 | 12 | public final NBTBaseType getType() { 13 | return this.type; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/nbt/NBTBaseType.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.nbt; 2 | 3 | public enum NBTBaseType { 4 | STRING, 5 | BYTE, 6 | DOUBLE, 7 | FLOAT, 8 | INTEGER, 9 | INTARRAY, 10 | BYTEARRAY, 11 | LONGARRAY, 12 | COMPOUND, 13 | LIST, 14 | LONG, 15 | SHORT, 16 | END; 17 | } 18 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/nbt/NBTNumber.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.nbt; 2 | 3 | public abstract class NBTNumber extends NBTBase{ 4 | 5 | protected NBTNumber(NBTBaseType type) { 6 | super(type); 7 | } 8 | 9 | public abstract byte getByte(); 10 | 11 | public abstract short getShort(); 12 | 13 | public abstract int getInt(); 14 | 15 | public abstract long getLong(); 16 | 17 | public abstract float getFloat(); 18 | 19 | public abstract double getDouble(); 20 | } 21 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/nbt/NBTTagByte.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.nbt; 2 | 3 | import com.google.common.collect.Maps; 4 | 5 | import java.util.Map; 6 | 7 | public final class NBTTagByte extends NBTNumber { 8 | private byte value; 9 | 10 | public NBTTagByte(byte value) { 11 | super(NBTBaseType.BYTE); 12 | this.value = value; 13 | } 14 | 15 | public byte getValue() { 16 | return this.value; 17 | } 18 | 19 | public String toString() { 20 | return Byte.toString(this.value)+"B"; 21 | } 22 | 23 | @Override 24 | public byte getByte() { 25 | return value; 26 | } 27 | 28 | @Override 29 | public short getShort() { 30 | return value; 31 | } 32 | 33 | @Override 34 | public int getInt() { 35 | return value; 36 | } 37 | 38 | @Override 39 | public long getLong() { 40 | return value; 41 | } 42 | 43 | @Override 44 | public float getFloat() { 45 | return value; 46 | } 47 | 48 | @Override 49 | public double getDouble() { 50 | return value; 51 | } 52 | 53 | @Override 54 | public Map serialize() { 55 | Map map = Maps.newLinkedHashMap(); 56 | map.put("==", getClass().getName()); 57 | map.put("value", getValue()); 58 | return map; 59 | } 60 | 61 | public static NBTTagByte deserialize(Map map){ 62 | return new NBTTagByte(((Number)map.get("value")).byteValue()); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/nbt/NBTTagByteArray.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.nbt; 2 | 3 | import com.google.common.collect.Lists; 4 | import com.google.common.collect.Maps; 5 | 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | public final class NBTTagByteArray extends NBTBase { 10 | private byte[] value; 11 | 12 | public NBTTagByteArray(byte[] value) { 13 | super(NBTBaseType.BYTEARRAY); 14 | this.value = value; 15 | } 16 | 17 | public NBTTagByteArray(Byte[] value) { 18 | super(NBTBaseType.BYTEARRAY); 19 | this.value = new byte[value.length]; 20 | for (int i = 0, size = value.length; i < size; i++) 21 | this.value[i] = value[i]; 22 | } 23 | 24 | public byte[] getValue() { 25 | return this.value; 26 | } 27 | 28 | public String toString() { 29 | StringBuilder builder = new StringBuilder("[B;"); 30 | for (byte aValue : value) builder.append(aValue).append(','); 31 | 32 | if(builder.charAt(builder.length()-1)==',') 33 | builder.deleteCharAt(builder.length()-1); 34 | 35 | return builder.append(']').toString(); 36 | } 37 | 38 | @Override 39 | public Map serialize() { 40 | Map map = Maps.newLinkedHashMap(); 41 | map.put("==", getClass().getName()); 42 | List values = Lists.newLinkedList(); 43 | for(byte value:getValue()) values.add(value); 44 | map.put("value", values); 45 | return map; 46 | } 47 | 48 | @SuppressWarnings("unchecked") 49 | public static NBTTagByteArray deserialize(Map map){ 50 | List list = (List) map.get("value"); 51 | byte[] bytes = new byte[list.size()]; 52 | for (int i = 0, size = list.size(); i < size; i++) 53 | bytes[i] = list.get(i).byteValue(); 54 | return new NBTTagByteArray(bytes); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/nbt/NBTTagDouble.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.nbt; 2 | 3 | import com.google.common.collect.Maps; 4 | 5 | import java.util.Map; 6 | 7 | public final class NBTTagDouble extends NBTNumber { 8 | private double value; 9 | 10 | public NBTTagDouble(double value) { 11 | super(NBTBaseType.DOUBLE); 12 | this.value = value; 13 | } 14 | 15 | public double getValue() { 16 | return this.value; 17 | } 18 | 19 | public String toString() { 20 | return Double.toString(this.value)+"D"; 21 | } 22 | 23 | @Override 24 | public byte getByte() { 25 | return (byte) value; 26 | } 27 | 28 | @Override 29 | public short getShort() { 30 | return (short) value; 31 | } 32 | 33 | @Override 34 | public int getInt() { 35 | return (int) value; 36 | } 37 | 38 | @Override 39 | public long getLong() { 40 | return (long) value; 41 | } 42 | 43 | @Override 44 | public float getFloat() { 45 | return (float) value; 46 | } 47 | 48 | @Override 49 | public double getDouble() { 50 | return value; 51 | } 52 | 53 | @Override 54 | public Map serialize() { 55 | Map map = Maps.newLinkedHashMap(); 56 | map.put("==", getClass().getName()); 57 | map.put("value", getValue()); 58 | return map; 59 | } 60 | 61 | public static NBTTagDouble deserialize(Map map){ 62 | return new NBTTagDouble(((Number)map.get("value")).doubleValue()); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/nbt/NBTTagEnd.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.nbt; 2 | 3 | import com.google.common.collect.Maps; 4 | 5 | import java.util.Map; 6 | 7 | public class NBTTagEnd extends NBTBase { 8 | 9 | public static final NBTTagEnd INSTANCE = new NBTTagEnd(); 10 | 11 | private NBTTagEnd() { 12 | super(NBTBaseType.END); 13 | } 14 | 15 | public String toString() { 16 | return "End"; 17 | } 18 | 19 | @Override 20 | public Map serialize() { 21 | Map map = Maps.newLinkedHashMap(); 22 | map.put("==", getClass().getName()); 23 | return map; 24 | } 25 | 26 | public static NBTTagEnd deserialize(Map map){ 27 | return INSTANCE; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/nbt/NBTTagFloat.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.nbt; 2 | 3 | import com.google.common.collect.Maps; 4 | 5 | import java.util.Map; 6 | 7 | public final class NBTTagFloat extends NBTNumber { 8 | private float value; 9 | 10 | public NBTTagFloat(float value) { 11 | super(NBTBaseType.FLOAT); 12 | this.value = value; 13 | } 14 | 15 | public float getValue() { 16 | return this.value; 17 | } 18 | 19 | public String toString() { 20 | return Float.toString(this.value)+"F"; 21 | } 22 | 23 | @Override 24 | public byte getByte() { 25 | return (byte) value; 26 | } 27 | 28 | @Override 29 | public short getShort() { 30 | return (short) value; 31 | } 32 | 33 | @Override 34 | public int getInt() { 35 | return (int) value; 36 | } 37 | 38 | @Override 39 | public long getLong() { 40 | return (long) value; 41 | } 42 | 43 | @Override 44 | public float getFloat() { 45 | return value; 46 | } 47 | 48 | @Override 49 | public double getDouble() { 50 | return value; 51 | } 52 | 53 | @Override 54 | public Map serialize() { 55 | Map map = Maps.newLinkedHashMap(); 56 | map.put("==", getClass().getName()); 57 | map.put("value", getValue()); 58 | return map; 59 | } 60 | 61 | public static NBTTagFloat deserialize(Map map){ 62 | return new NBTTagFloat(((Number)map.get("value")).floatValue()); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/nbt/NBTTagInt.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.nbt; 2 | 3 | import com.google.common.collect.Maps; 4 | 5 | import java.util.Map; 6 | 7 | public final class NBTTagInt extends NBTNumber { 8 | private int value; 9 | 10 | public NBTTagInt(int value) { 11 | super(NBTBaseType.INTEGER); 12 | this.value = value; 13 | } 14 | 15 | public int getValue() { 16 | return this.value; 17 | } 18 | 19 | public String toString() { 20 | return Integer.toString(this.value); 21 | } 22 | 23 | @Override 24 | public byte getByte() { 25 | return (byte) value; 26 | } 27 | 28 | @Override 29 | public short getShort() { 30 | return (short) value; 31 | } 32 | 33 | @Override 34 | public int getInt() { 35 | return value; 36 | } 37 | 38 | @Override 39 | public long getLong() { 40 | return value; 41 | } 42 | 43 | @Override 44 | public float getFloat() { 45 | return value; 46 | } 47 | 48 | @Override 49 | public double getDouble() { 50 | return value; 51 | } 52 | 53 | @Override 54 | public Map serialize() { 55 | Map map = Maps.newLinkedHashMap(); 56 | map.put("==", getClass().getName()); 57 | map.put("value", getValue()); 58 | return map; 59 | } 60 | 61 | public static NBTTagInt deserialize(Map map){ 62 | return new NBTTagInt(((Number)map.get("value")).intValue()); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/nbt/NBTTagIntArray.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.nbt; 2 | 3 | import com.google.common.collect.Lists; 4 | import com.google.common.collect.Maps; 5 | 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | public final class NBTTagIntArray extends NBTBase { 10 | private int[] value; 11 | 12 | public NBTTagIntArray(int[] value) { 13 | super(NBTBaseType.INTARRAY); 14 | this.value = value; 15 | } 16 | 17 | public NBTTagIntArray(Integer[] value) { 18 | super(NBTBaseType.INTARRAY); 19 | this.value = new int[value.length]; 20 | for (int i = 0, size = value.length; i < size; i++) 21 | this.value[i] = value[i]; 22 | } 23 | 24 | public int[] getValue() { 25 | return this.value; 26 | } 27 | 28 | public String toString() { 29 | StringBuilder builder = new StringBuilder("[I;"); 30 | for (int aValue : value) builder.append(aValue).append(','); 31 | 32 | if(builder.charAt(builder.length()-1)==',') 33 | builder.deleteCharAt(builder.length()-1); 34 | 35 | return builder.append(']').toString(); 36 | } 37 | 38 | @Override 39 | public Map serialize() { 40 | Map map = Maps.newLinkedHashMap(); 41 | map.put("==", getClass().getName()); 42 | List values = Lists.newLinkedList(); 43 | for(int value:getValue()) values.add(value); 44 | map.put("value", values); 45 | return map; 46 | } 47 | 48 | @SuppressWarnings("unchecked") 49 | public static NBTTagIntArray deserialize(Map map){ 50 | return new NBTTagIntArray(((List)map.get("value")).toArray(new Integer[0])); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/nbt/NBTTagList.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.nbt; 2 | 3 | import com.google.common.collect.Lists; 4 | import com.google.common.collect.Maps; 5 | 6 | import java.util.*; 7 | import java.util.stream.Stream; 8 | 9 | public final class NBTTagList extends NBTBase implements Iterable{ 10 | private final List list = Lists.newLinkedList(); 11 | 12 | public NBTTagList() { 13 | super(NBTBaseType.LIST); 14 | } 15 | 16 | public NBTTagList(Collection list) { 17 | this(); 18 | this.list.addAll(list); 19 | } 20 | 21 | public NBTTagList(NBTBase... bases){ 22 | this(); 23 | Collections.addAll(list, bases); 24 | } 25 | 26 | public NBTBase get(int index) { 27 | return this.list.get(index); 28 | } 29 | 30 | public NBTTagList add(NBTBase value) { 31 | if(value.getType() != NBTBaseType.END) 32 | this.list.add(value); 33 | return this; 34 | } 35 | 36 | public int size() { 37 | return this.list.size(); 38 | } 39 | 40 | public NBTTagList remove(int index) { 41 | this.list.remove(index); 42 | return this; 43 | } 44 | 45 | public NBTTagList set(int index, NBTBase value) { 46 | this.list.set(index, value); 47 | return this; 48 | } 49 | 50 | public NBTTagList clear() { 51 | this.list.clear(); 52 | return this; 53 | } 54 | 55 | public Iterator iterator(){ 56 | return list.iterator(); 57 | } 58 | 59 | public Stream stream(){ 60 | return list.stream(); 61 | } 62 | 63 | public String toString() { 64 | StringBuilder builder = new StringBuilder("["); 65 | for (NBTBase aList : list) builder.append(aList).append(','); 66 | 67 | if(builder.charAt(builder.length()-1)==',') 68 | builder.deleteCharAt(builder.length()-1); 69 | 70 | return builder.append(']').toString(); 71 | } 72 | 73 | @Override 74 | public Map serialize() { 75 | Map map = Maps.newLinkedHashMap(); 76 | map.put("==", getClass().getName()); 77 | map.put("value", this.list); 78 | return map; 79 | } 80 | 81 | @SuppressWarnings("unchecked") 82 | public static NBTTagList deserialize(Map map){ 83 | return new NBTTagList((List) map.get("value")); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/nbt/NBTTagLong.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.nbt; 2 | 3 | import com.google.common.collect.Maps; 4 | 5 | import java.util.Map; 6 | 7 | public final class NBTTagLong extends NBTNumber { 8 | private long value; 9 | 10 | public NBTTagLong(long value) { 11 | super(NBTBaseType.LONG); 12 | this.value = value; 13 | } 14 | 15 | public long getValue() { 16 | return this.value; 17 | } 18 | 19 | public String toString() { 20 | return Long.toString(this.value)+"L"; 21 | } 22 | 23 | @Override 24 | public byte getByte() { 25 | return (byte) value; 26 | } 27 | 28 | @Override 29 | public short getShort() { 30 | return (short) value; 31 | } 32 | 33 | @Override 34 | public int getInt() { 35 | return (int) value; 36 | } 37 | 38 | @Override 39 | public long getLong() { 40 | return value; 41 | } 42 | 43 | @Override 44 | public float getFloat() { 45 | return value; 46 | } 47 | 48 | @Override 49 | public double getDouble() { 50 | return value; 51 | } 52 | 53 | @Override 54 | public Map serialize() { 55 | Map map = Maps.newLinkedHashMap(); 56 | map.put("==", getClass().getName()); 57 | map.put("value", getValue()); 58 | return map; 59 | } 60 | 61 | public static NBTTagLong deserialize(Map map){ 62 | return new NBTTagLong(((Number)map.get("value")).longValue()); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/nbt/NBTTagLongArray.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.nbt; 2 | 3 | import com.google.common.collect.Lists; 4 | import com.google.common.collect.Maps; 5 | 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | public final class NBTTagLongArray extends NBTBase { 10 | private long[] value; 11 | 12 | public NBTTagLongArray(long[] value) { 13 | super(NBTBaseType.LONGARRAY); 14 | this.value = value; 15 | } 16 | 17 | public NBTTagLongArray(Long[] value) { 18 | super(NBTBaseType.LONGARRAY); 19 | this.value = new long[value.length]; 20 | for (int i = 0, size = value.length; i < size; i++) 21 | this.value[i] = value[i]; 22 | } 23 | 24 | public long[] getValue() { 25 | return this.value; 26 | } 27 | 28 | public String toString() { 29 | StringBuilder builder = new StringBuilder("[L;"); 30 | for (long aValue : value) builder.append(aValue).append(','); 31 | 32 | if(builder.charAt(builder.length()-1)==',') 33 | builder.deleteCharAt(builder.length()-1); 34 | 35 | return builder.append(']').toString(); 36 | } 37 | 38 | @Override 39 | public Map serialize() { 40 | Map map = Maps.newLinkedHashMap(); 41 | map.put("==", getClass().getName()); 42 | List values = Lists.newLinkedList(); 43 | for(long value:getValue()) values.add(value); 44 | map.put("value", values); 45 | return map; 46 | } 47 | 48 | @SuppressWarnings("unchecked") 49 | public static NBTTagLongArray deserialize(Map map){ 50 | return new NBTTagLongArray(((List)map.get("value")).toArray(new Long[0])); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/nbt/NBTTagShort.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.nbt; 2 | 3 | import com.google.common.collect.Maps; 4 | 5 | import java.util.Map; 6 | 7 | public final class NBTTagShort extends NBTNumber { 8 | private short value; 9 | 10 | public NBTTagShort(short value) { 11 | super(NBTBaseType.DOUBLE); 12 | this.value = value; 13 | } 14 | 15 | public short getValue() { 16 | return this.value; 17 | } 18 | 19 | public String toString() { 20 | return Short.toString(this.value)+"S"; 21 | } 22 | 23 | @Override 24 | public byte getByte() { 25 | return (byte) value; 26 | } 27 | 28 | @Override 29 | public short getShort() { 30 | return value; 31 | } 32 | 33 | @Override 34 | public int getInt() { 35 | return value; 36 | } 37 | 38 | @Override 39 | public long getLong() { 40 | return value; 41 | } 42 | 43 | @Override 44 | public float getFloat() { 45 | return value; 46 | } 47 | 48 | @Override 49 | public double getDouble() { 50 | return value; 51 | } 52 | 53 | @Override 54 | public Map serialize() { 55 | Map map = Maps.newLinkedHashMap(); 56 | map.put("==", getClass().getName()); 57 | map.put("value", getValue()); 58 | return map; 59 | } 60 | 61 | public static NBTTagShort deserialize(Map map){ 62 | return new NBTTagShort(((Number)map.get("value")).shortValue()); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/nbt/NBTTagString.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.nbt; 2 | 3 | import com.google.common.collect.Maps; 4 | 5 | import java.util.Map; 6 | 7 | public final class NBTTagString extends NBTBase { 8 | private String value; 9 | 10 | public NBTTagString(String value) { 11 | super(NBTBaseType.STRING); 12 | this.value = value; 13 | } 14 | 15 | public String getValue() { 16 | return this.value; 17 | } 18 | 19 | public String toString() { 20 | return "\""+this.value+"\""; 21 | } 22 | 23 | @Override 24 | public Map serialize() { 25 | Map map = Maps.newLinkedHashMap(); 26 | map.put("==", getClass().getName()); 27 | map.put("value", getValue()); 28 | return map; 29 | } 30 | 31 | public static NBTTagString deserialize(Map map){ 32 | return new NBTTagString((String) map.get("value")); 33 | } 34 | } -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/nbt/NmsNBT.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.nbt; 2 | 3 | import team.unstudio.udpl.nms.NmsHelper; 4 | 5 | /** 6 | * NBT的转换接口 7 | */ 8 | public interface NmsNBT { 9 | 10 | /** 11 | * 转换为Compound 12 | */ 13 | NBTTagCompound toCompound(Object nbt); 14 | 15 | /** 16 | * 转换为List 17 | */ 18 | NBTTagList toList(Object nbt); 19 | 20 | /** 21 | * 转换为Byte 22 | */ 23 | NBTTagByte toByte(Object nbt); 24 | 25 | /** 26 | * 转换为Short 27 | */ 28 | NBTTagShort toShort(Object nbt); 29 | 30 | /** 31 | * 转换为Int 32 | */ 33 | NBTTagInt toInt(Object nbt); 34 | 35 | /** 36 | * 转换为Long 37 | */ 38 | NBTTagLong toLong(Object nbt); 39 | 40 | /** 41 | * 转换为Float 42 | */ 43 | NBTTagFloat toFloat(Object nbt); 44 | 45 | /** 46 | * 转换为Double 47 | */ 48 | NBTTagDouble toDouble(Object nbt); 49 | 50 | /** 51 | * 转换为String 52 | */ 53 | NBTTagString toString(Object nbt); 54 | 55 | /** 56 | * 转换为ByteArray 57 | */ 58 | NBTTagByteArray toByteArray(Object nbt); 59 | 60 | /** 61 | * 转换为IntArray 62 | */ 63 | NBTTagIntArray toIntArray(Object nbt); 64 | 65 | /** 66 | * 转换为NBTBase 67 | */ 68 | NBTBase toNBTBase(Object nbt); 69 | 70 | /** 71 | * 转换为 {@link net.minecraft.server} 的NBT类 72 | */ 73 | Object toNmsNBT(NBTBase nbt); 74 | 75 | /** 76 | * 转换为NBT的Json格式 77 | */ 78 | String toNBTJson(NBTTagCompound nbt); 79 | 80 | /** 81 | * 从NBT的Json格式读取 82 | */ 83 | NBTTagCompound parseNBTJson(String json); 84 | 85 | static NmsNBT getInstance(){ 86 | return NmsHelper.getNmsNBT(); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/network/NmsNetwork.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.network; 2 | 3 | import org.bukkit.entity.Player; 4 | 5 | public interface NmsNetwork { 6 | 7 | void inject(Player player); 8 | } 9 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/tileentity/NmsMobSpawner.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.tileentity; 2 | 3 | import org.bukkit.block.CreatureSpawner; 4 | import org.bukkit.entity.Entity; 5 | import team.unstudio.udpl.nms.NmsHelper; 6 | import team.unstudio.udpl.nms.nbt.NBTTagCompound; 7 | import team.unstudio.udpl.nms.nbt.NBTTagList; 8 | 9 | public interface NmsMobSpawner extends NmsTileEntity{ 10 | 11 | CreatureSpawner getBukkitBlockState(); 12 | 13 | NBTTagList getSpawnEntities(); 14 | 15 | void addSpawnEntities(NBTTagCompound nbt, int weight); 16 | 17 | default void addSpawnEntities(Entity entity, int weight){ 18 | NBTTagCompound entityNbt = NmsHelper.createNmsEntity(entity).save(); 19 | entityNbt.remove("Pos"); 20 | entityNbt.remove("Motion"); 21 | entityNbt.remove("Rotation"); 22 | addSpawnEntities(entityNbt, weight); 23 | } 24 | 25 | NBTTagCompound getSpawnEntity(); 26 | 27 | void setSpawnEntity(NBTTagCompound nbt); 28 | 29 | default void setDisplayEntity(Entity entity){ 30 | NBTTagCompound entityNbt = NmsHelper.createNmsEntity(entity).save(); 31 | entityNbt.remove("Pos"); 32 | entityNbt.remove("Motion"); 33 | entityNbt.remove("Rotation"); 34 | setSpawnEntity(entityNbt); 35 | } 36 | 37 | short getSpawnCount(); 38 | 39 | void setSpawnCount(short count); 40 | 41 | short getSpawnRange(); 42 | 43 | void setSpawnRange(short range); 44 | 45 | short getDelay(); 46 | 47 | void setDelay(short delay); 48 | 49 | short getMinSpawnDelay(); 50 | 51 | void setMinSpawnDelay(short minDelay); 52 | 53 | short getMaxSpawnDelay(); 54 | 55 | void setMaxSpawnDelay(short maxDelay); 56 | 57 | short getMaxNearbyEntities(); 58 | 59 | void setMaxNearbyEntities(short value); 60 | 61 | short getRequiredPlayerRange(); 62 | 63 | void setRequiredPlayerRange(short range); 64 | } 65 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/tileentity/NmsTileEntity.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.tileentity; 2 | 3 | import org.bukkit.block.BlockState; 4 | import team.unstudio.udpl.nms.NmsHelper; 5 | import team.unstudio.udpl.nms.nbt.NBTTagCompound; 6 | 7 | public interface NmsTileEntity { 8 | 9 | BlockState getBukkitBlockState(); 10 | 11 | NBTTagCompound save(); 12 | 13 | void load(NBTTagCompound nbt); 14 | 15 | static NmsTileEntity createNmsTileEntity(BlockState blockState){ 16 | return NmsHelper.createNmsTileEntity(blockState); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/nms/util/NmsClassLoader.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.nms.util; 2 | 3 | import team.unstudio.udpl.util.BukkitVersion; 4 | import team.unstudio.udpl.util.ServerUtils; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.security.SecureClassLoader; 8 | 9 | public class NmsClassLoader extends SecureClassLoader { 10 | 11 | private final NmsClassTransformer transformer; 12 | 13 | public NmsClassLoader(){ 14 | this(BukkitVersion.getCurrentBukkitVersion().getPackageName(), ServerUtils.getMinecraftVersion()); 15 | } 16 | 17 | public NmsClassLoader(String targetNmsVersion, String targetMinecraftVersion) { 18 | transformer = new NmsClassTransformer(targetNmsVersion, targetMinecraftVersion); 19 | } 20 | 21 | public NmsClassLoader(ClassLoader parent) { 22 | this(parent, BukkitVersion.getCurrentBukkitVersion().getPackageName(), ServerUtils.getMinecraftVersion()); 23 | } 24 | 25 | public NmsClassLoader(ClassLoader parent, String targetNmsVersion, String targetMinecraftVersion) { 26 | super(parent); 27 | transformer = new NmsClassTransformer(targetNmsVersion, targetMinecraftVersion); 28 | } 29 | 30 | public Class loadClass(InputStream input, String bukkitVersion, String minecraftVersion) throws IOException{ 31 | byte[] b = transformer.transform(input, bukkitVersion, minecraftVersion); 32 | return loadClass(null, b, 0, b.length); 33 | } 34 | 35 | public Class loadClass(byte[] bytes, String bukkitVersion, String minecraftVersion) throws IOException{ 36 | byte[] b = transformer.transform(bytes, bukkitVersion, minecraftVersion); 37 | return loadClass(null, b, 0, b.length); 38 | } 39 | 40 | public Class loadClass(String name, byte[] b, int off, int len) { 41 | return defineClass(name, b, off, len); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/scoreboard/BiScoreboard.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.scoreboard; 2 | 3 | import com.google.common.collect.BiMap; 4 | import com.google.common.collect.HashBiMap; 5 | import org.bukkit.Bukkit; 6 | import org.bukkit.scoreboard.DisplaySlot; 7 | 8 | import java.util.Collection; 9 | import java.util.Map; 10 | import java.util.Set; 11 | 12 | /** 13 | * 一个名称与分数唯一对应的计分板 14 | */ 15 | public class BiScoreboard extends ScoreboardWrapper { 16 | 17 | private final BiMap keyToScore = HashBiMap.create(); 18 | 19 | public BiScoreboard(){ 20 | scoreboard = Bukkit.getScoreboardManager().getNewScoreboard(); 21 | objective = scoreboard.registerNewObjective("ScoreboardAPI", "dummy"); 22 | objective.setDisplaySlot(DisplaySlot.SIDEBAR); 23 | } 24 | 25 | @Override 26 | public void put(String key, int score){ 27 | String oldKey = getKey(score); 28 | if(oldKey != null) 29 | scoreboard.resetScores(oldKey); 30 | objective.getScore(key).setScore(score); 31 | keyToScore.forcePut(key, score); 32 | } 33 | 34 | public void put(int score, String key){ 35 | this.put(key, score); 36 | } 37 | 38 | public void putAll(Map map){ 39 | map.forEach(this::put); 40 | } 41 | 42 | public void putAllInverse(Map map){ 43 | map.forEach(this::put); 44 | } 45 | 46 | @Override 47 | public void remove(String key){ 48 | super.remove(key); 49 | keyToScore.remove(key); 50 | } 51 | 52 | public void remove(int score){ 53 | BiMap scoreToKey = keyToScore.inverse(); 54 | if(scoreToKey.containsKey(score)){ 55 | super.remove(scoreToKey.get(score)); 56 | scoreToKey.remove(score); 57 | } 58 | } 59 | 60 | public void removeAllInverse(Collection scores){ 61 | scores.forEach(this::remove); 62 | } 63 | 64 | @Override 65 | public Set getKeys(){ 66 | return keyToScore.keySet(); 67 | } 68 | 69 | public Set getScores(){ 70 | return keyToScore.inverse().keySet(); 71 | } 72 | 73 | public String getKey(int score){ 74 | return keyToScore.inverse().get(score); 75 | } 76 | 77 | public int getScore(String key){ 78 | return keyToScore.get(key); 79 | } 80 | 81 | public boolean containKey(String key){ 82 | return keyToScore.containsKey(key); 83 | } 84 | 85 | public boolean containScore(int score){ 86 | return keyToScore.inverse().containsKey(score); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/scoreboard/ScoreboardHelper.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.scoreboard; 2 | 3 | import org.bukkit.Bukkit; 4 | import org.bukkit.entity.Player; 5 | import org.bukkit.scoreboard.Scoreboard; 6 | 7 | public interface ScoreboardHelper { 8 | static void setPlayerScoreboard(Player player, Scoreboard scoreboard){ 9 | player.setScoreboard(scoreboard); 10 | } 11 | 12 | static void clear(Player player){ 13 | player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); 14 | } 15 | 16 | static void reset(Player player){ 17 | player.setScoreboard(Bukkit.getScoreboardManager().getMainScoreboard()); 18 | } 19 | 20 | static Scoreboard getNewScoreboard(){ 21 | return Bukkit.getScoreboardManager().getNewScoreboard(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/scoreboard/ScoreboardWrapper.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.scoreboard; 2 | 3 | import org.bukkit.Bukkit; 4 | import org.bukkit.entity.Player; 5 | import org.bukkit.scoreboard.DisplaySlot; 6 | import org.bukkit.scoreboard.Objective; 7 | import org.bukkit.scoreboard.Scoreboard; 8 | 9 | import java.util.Collection; 10 | import java.util.Map; 11 | import java.util.Set; 12 | import java.util.stream.Collectors; 13 | 14 | public class ScoreboardWrapper { 15 | 16 | protected Scoreboard scoreboard; 17 | protected Objective objective; 18 | 19 | public ScoreboardWrapper() { 20 | } 21 | 22 | public ScoreboardWrapper(Scoreboard scoreboard, Objective objective){ 23 | this.scoreboard = scoreboard; 24 | this.objective = objective; 25 | } 26 | 27 | public ScoreboardWrapper(Objective objective) { 28 | this(Bukkit.getScoreboardManager().getNewScoreboard(), objective); 29 | } 30 | 31 | public Scoreboard getScoreboard(){ 32 | return scoreboard; 33 | } 34 | 35 | public Objective getObjective(){ 36 | return objective; 37 | } 38 | 39 | public void setDisplayerSlot(DisplaySlot slot){ 40 | objective.setDisplaySlot(slot); 41 | } 42 | 43 | public String getDisplayName(){ 44 | return objective.getDisplayName(); 45 | } 46 | 47 | public void setDisplayName(String name){ 48 | objective.setDisplayName(name); 49 | } 50 | 51 | public void put(String key,int score){ 52 | objective.getScore(key).setScore(score); 53 | } 54 | 55 | public void putAll(Map map){ 56 | map.forEach((key, value) -> put(key, value)); 57 | } 58 | 59 | public void remove(String key){ 60 | scoreboard.resetScores(key); 61 | } 62 | 63 | public void removeAll(Collection keys){ 64 | keys.forEach(this::remove); 65 | } 66 | 67 | public Set getKeys(){ 68 | return scoreboard.getEntries(); 69 | } 70 | 71 | public Set getKeys(int score){ 72 | return getKeys().stream().filter(key->getScore(key) == score).collect(Collectors.toSet()); 73 | } 74 | 75 | public int getScore(String key){ 76 | return objective.getScore(key).getScore(); 77 | } 78 | 79 | public void display(Player player){ 80 | player.setScoreboard(getScoreboard()); 81 | } 82 | 83 | public void reset(Player player){ 84 | player.setScoreboard(Bukkit.getScoreboardManager().getMainScoreboard()); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/ui/UIFactory.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.ui; 2 | 3 | import org.bukkit.Bukkit; 4 | import org.bukkit.event.inventory.InventoryType; 5 | 6 | /** 7 | * 界面的工厂类 8 | * @author AAA 9 | * 10 | */ 11 | public interface UIFactory { 12 | 13 | /** 14 | * 创建一个界面 15 | * @param size 界面大小(9的倍数,即槽数量) 16 | * @param title 标题 17 | */ 18 | static UI createUI(int size, String title){ 19 | return new UI(Bukkit.createInventory(null,size,title)); 20 | } 21 | 22 | /** 23 | * 创建一个界面 24 | * @param type 界面类型 25 | * @param title 标题 26 | */ 27 | static UI createUI(InventoryType type, String title){ 28 | return new UI(Bukkit.createInventory(null, type, title)); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/ActionBarUtils.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.util; 2 | 3 | import com.comphenix.protocol.PacketType; 4 | import com.comphenix.protocol.ProtocolManager; 5 | import com.comphenix.protocol.events.PacketContainer; 6 | import com.comphenix.protocol.wrappers.EnumWrappers; 7 | import com.comphenix.protocol.wrappers.WrappedChatComponent; 8 | import org.bukkit.entity.Player; 9 | 10 | /** 11 | * An action bar helper with ProtocolLib, 12 | * also called overlay message in client. 13 | */ 14 | public interface ActionBarUtils { 15 | /** 16 | * sending an action bar to a player 17 | * 18 | * @param player the player to send 19 | * @param text the message to send 20 | */ 21 | static Result send(Player player, String text){ 22 | PacketContainer container = ProtocolLibUtils.of(PacketType.Play.Server.CHAT); 23 | container.getChatComponents().write(0, WrappedChatComponent.fromJson("{\"text\": \"" + text + "\"}")); 24 | if (container.getBytes().size() > 0) { 25 | container.getBytes().write(0, (byte) 2); 26 | } else if (container.getEnumModifier(EnumWrappers.ChatType.class, 2).size() > 0) { 27 | container.getEnumModifier(EnumWrappers.ChatType.class, 2).write(0, EnumWrappers.ChatType.GAME_INFO); 28 | } 29 | 30 | return ProtocolLibUtils.send(player, container); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/BlockUtils.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.util; 2 | 3 | import com.comphenix.protocol.PacketType; 4 | import com.comphenix.protocol.ProtocolLibrary; 5 | import com.comphenix.protocol.ProtocolManager; 6 | import com.comphenix.protocol.events.PacketContainer; 7 | import com.comphenix.protocol.wrappers.BlockPosition; 8 | import org.bukkit.Location; 9 | import org.bukkit.entity.Player; 10 | 11 | import java.lang.reflect.InvocationTargetException; 12 | 13 | public interface BlockUtils { 14 | ProtocolManager PROTOCOL_MANAGER = ProtocolLibrary.getProtocolManager(); 15 | 16 | /** 17 | * 0–9 are the displayable destroy stages and each other number means that there is no animation on this coordinate.
18 | * Block break animations can still be applied on air; the animation will remain visible although there is no block being broken. However, if this is applied to a transparent block, odd graphical effects may happen, including water losing its transparency. (An effect similar to this can be seen in normal gameplay when breaking ice blocks)
19 | * If you need to display several break animations at the same time you have to give each of them a unique Entity ID.
20 | */ 21 | static Result sendBlockBreakAnimation(Player player, Location location, byte state) { 22 | return sendBlockBreakAnimation(player, player.getEntityId(), location, state); 23 | } 24 | 25 | /** 26 | * 0–9 are the displayable destroy stages and each other number means that there is no animation on this coordinate.
27 | * Block break animations can still be applied on air; the animation will remain visible although there is no block being broken. However, if this is applied to a transparent block, odd graphical effects may happen, including water losing its transparency. (An effect similar to this can be seen in normal gameplay when breaking ice blocks)
28 | * If you need to display several break animations at the same time you have to give each of them a unique Entity ID.
29 | */ 30 | static Result sendBlockBreakAnimation(Player player, int entityId, Location location, byte state) { 31 | PacketContainer container = PROTOCOL_MANAGER.createPacket(PacketType.Play.Server.BLOCK_BREAK_ANIMATION); 32 | container.getIntegers().write(0, entityId); 33 | container.getBlockPositionModifier().write(0, 34 | new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ())); 35 | container.getIntegers().write(1, (int) state); 36 | 37 | try { 38 | PROTOCOL_MANAGER.sendServerPacket(player, container); 39 | return Result.success(); 40 | } catch (InvocationTargetException e) { 41 | return Result.failure(e); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/BukkitVersion.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.util; 2 | 3 | import team.unstudio.udpl.util.reflect.ReflectionUtils; 4 | 5 | /** 6 | * Bukkit version checker 7 | */ 8 | public enum BukkitVersion { 9 | 10 | V1_13_R2("v1_13_R2","1.13.1"), 11 | V1_13_R1("v1_13_R1","1.13"), 12 | V1_12_R1("v1_12_R1","1.12.2"), 13 | V1_11_R1("v1_11_R1","1.11.2"), 14 | V1_10_R1("v1_10_R1","1.10.2"), 15 | V1_9_R2("v1_9_R2","1.9.4"), 16 | V1_9_R1("v1_9_R1","1.9"), 17 | V1_8_R3("v1_8_R3","1.8.7"), 18 | V1_8_R2("v1_8_R2","1.8.3"), 19 | V1_8_R1("v1_8_R1","1.8"), 20 | UNKNOWN(ReflectionUtils.PackageType.getServerVersion(), ServerUtils.getMinecraftVersion()); 21 | 22 | private final String packetName; 23 | private final String lastMinecraftVersion; 24 | 25 | BukkitVersion(String packetName,String lastMinecraftVersion) { 26 | this.packetName = packetName; 27 | this.lastMinecraftVersion = lastMinecraftVersion; 28 | } 29 | 30 | /** 31 | * if version equal or newer than the version you gave 32 | * {@code V1_12_R1.isAbove(V1_8_R1) == true} 33 | * 34 | * @param value the version to check 35 | * @return true if newer or the same 36 | */ 37 | public boolean isAbove(BukkitVersion value){ 38 | return compareTo(value) <= 0; 39 | } 40 | 41 | 42 | /** 43 | * if version equal or older than the version you gave. 44 | * {@code V1_8_R1.isBelow(V1_12_R1) == true} 45 | * 46 | * @param value the version to check 47 | * @return true if older or the same 48 | */ 49 | public boolean isBelow(BukkitVersion value){ 50 | return compareTo(value) >= 0; 51 | } 52 | 53 | /** 54 | * if version equal the current version. 55 | * In version 1.12.2, you will get 56 | * {@code V1_12_R1.isCurrent() == true} 57 | * 58 | * @return true if equal the current version 59 | */ 60 | public boolean isCurrent() { 61 | return this == getCurrentBukkitVersion(); 62 | } 63 | 64 | /** 65 | * get package name like "v1_12_R1" 66 | */ 67 | public String getPackageName(){ 68 | return packetName; 69 | } 70 | 71 | public String getLastMinecraftVersion(){ 72 | return lastMinecraftVersion; 73 | } 74 | 75 | private static BukkitVersion CURRENT_BUKKIT_VERSION; 76 | 77 | /** 78 | * get current bukkit version 79 | */ 80 | public static BukkitVersion getCurrentBukkitVersion(){ 81 | if(CURRENT_BUKKIT_VERSION == null){ 82 | CURRENT_BUKKIT_VERSION = valueOf(ReflectionUtils.PackageType.getServerVersion().toUpperCase()); 83 | if(CURRENT_BUKKIT_VERSION == null) 84 | CURRENT_BUKKIT_VERSION = BukkitVersion.UNKNOWN; 85 | } 86 | return CURRENT_BUKKIT_VERSION; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/ChatUtils.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.util; 2 | 3 | import org.apache.commons.lang3.NotImplementedException; 4 | import org.bukkit.ChatColor; 5 | import org.bukkit.command.CommandSender; 6 | import org.bukkit.entity.Player; 7 | 8 | public interface ChatUtils { 9 | 10 | String SPLITTER = translateColorCodes("&l&m----------------------------------------------------------------"); 11 | char DEFAULT_COLOR_CHAR = '&'; 12 | 13 | /** 14 | * Send splitter line.
15 | * 发送分割线 16 | */ 17 | static void sendSplitter(CommandSender sender){ 18 | sender.sendMessage(SPLITTER); 19 | } 20 | 21 | /** 22 | * Send blank line.
23 | * 发送空行 24 | */ 25 | static void sendEmpty(CommandSender sender){ 26 | sender.sendMessage(""); 27 | } 28 | 29 | /** 30 | * 发送清屏消息 31 | */ 32 | static void sendCleanScreen(CommandSender sender) { 33 | for (int i = 0; i < 20; i++) sendEmpty(sender); 34 | } 35 | 36 | /** 37 | * 将文本中'&'转换为颜色字符 38 | */ 39 | static String translateColorCodes(String textToTranslate){ 40 | return ChatColor.translateAlternateColorCodes(DEFAULT_COLOR_CHAR, textToTranslate); 41 | } 42 | 43 | /** 44 | * 玩家停止接收消息
45 | * 该方法将会将发送给玩家的消息拦截并缓存,直到调用{@link ChatUtils#startReceiveChat(Player)}方法。 46 | * @see ChatUtils#startReceiveChat(Player) 47 | */ 48 | static void stopReceiveChat(Player player) { 49 | throw new NotImplementedException(""); 50 | } 51 | 52 | /** 53 | * 玩家开始接收消息
54 | * 该方法将会将已拦截的玩家消息发送,并且该发送是逐步的,使玩家可以阅读未读的消息。 55 | * @see ChatUtils#stopReceiveChat(Player) 56 | */ 57 | static void startReceiveChat(Player player) { 58 | throw new NotImplementedException(""); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/EntityUtils.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.util; 2 | 3 | import com.comphenix.protocol.PacketType; 4 | import com.comphenix.protocol.ProtocolManager; 5 | import com.comphenix.protocol.events.PacketContainer; 6 | import com.comphenix.protocol.wrappers.WrappedDataWatcher; 7 | import com.google.common.base.Strings; 8 | import org.bukkit.Location; 9 | import org.bukkit.entity.Player; 10 | import org.bukkit.inventory.ItemStack; 11 | 12 | import javax.annotation.Nonnull; 13 | import javax.annotation.Nullable; 14 | import java.util.UUID; 15 | import java.util.concurrent.atomic.AtomicInteger; 16 | 17 | public interface EntityUtils { 18 | AtomicInteger nextEntityID = new AtomicInteger(Integer.MAX_VALUE); 19 | 20 | @Deprecated 21 | static Result sendFakeItemEntity(@Nonnull Player player, @Nonnull ItemStack itemStack, @Nonnull Location location, @Nullable String displayName){ 22 | int entityID = nextEntityID.getAndDecrement(); 23 | PacketContainer spawnEntityLiving = ProtocolLibUtils.of(PacketType.Play.Server.SPAWN_ENTITY_LIVING); 24 | spawnEntityLiving.getIntegers().write(0, entityID); //Entity ID 25 | spawnEntityLiving.getUUIDs().write(0, UUID.randomUUID()); //Entity UUID 26 | spawnEntityLiving.getIntegers().write(1, 2); //Entity Type 27 | spawnEntityLiving.getDoubles().write(0, location.getX()) 28 | .write(1, location.getY()) 29 | .write(2, location.getZ()); 30 | spawnEntityLiving.getIntegers().write(2, 0) //Pitch 31 | .write(3, 0) //Yaw 32 | //Data 33 | .write(4, 1) 34 | //Velocity(X,Y,Z) 35 | .write(5, 0) 36 | .write(6, 0) 37 | .write(7, 0); 38 | 39 | PacketContainer entityMetadata = ProtocolLibUtils.of(PacketType.Play.Server.ENTITY_METADATA); 40 | entityMetadata.getIntegers().write(0, entityID); 41 | WrappedDataWatcher dataWatcher = new WrappedDataWatcher(); 42 | dataWatcher.setObject(0, (byte) 0); 43 | dataWatcher.setObject(1, 300); 44 | dataWatcher.setObject(2, Strings.nullToEmpty(displayName)); 45 | dataWatcher.setObject(3, !Strings.isNullOrEmpty(displayName)); 46 | dataWatcher.setObject(4, false); 47 | dataWatcher.setObject(5, true); 48 | dataWatcher.setObject(6, itemStack); 49 | entityMetadata.getWatchableCollectionModifier().write(0, dataWatcher.getWatchableObjects()); 50 | 51 | return ProtocolLibUtils.send(player, spawnEntityLiving, entityMetadata); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/Hologram.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.util; 2 | 3 | import org.apache.commons.lang3.NotImplementedException; 4 | 5 | /** 6 | * Hologram Util haven't been developed. 7 | */ 8 | public interface Hologram { 9 | } 10 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/PluginUtils.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.util; 2 | 3 | import org.apache.commons.lang.Validate; 4 | import org.bukkit.Bukkit; 5 | import org.bukkit.event.Cancellable; 6 | import org.bukkit.event.Event; 7 | import org.bukkit.event.Listener; 8 | import org.bukkit.plugin.Plugin; 9 | import org.bukkit.plugin.java.JavaPlugin; 10 | 11 | import javax.annotation.Nonnull; 12 | import java.io.IOException; 13 | import java.net.JarURLConnection; 14 | import java.net.URL; 15 | import java.util.Enumeration; 16 | import java.util.jar.JarEntry; 17 | import java.util.jar.JarFile; 18 | 19 | public interface PluginUtils { 20 | /** 21 | * 将 Jar 包中的文件夹,复制到插件的数据目录中 22 | * 23 | * @param plugin 插件实例 24 | * @param resourcePath 文件在 Jar 包中的路径 25 | * @param replace 是否替换文件 26 | */ 27 | static void saveDirectory(@Nonnull JavaPlugin plugin, @Nonnull String resourcePath, boolean replace){ 28 | Validate.notNull(plugin); 29 | Validate.notEmpty(resourcePath); 30 | resourcePath = resourcePath.replace('\\', '/'); 31 | 32 | plugin.getLogger().info("Plugin save directory. Path: " + resourcePath); 33 | 34 | URL url = plugin.getClass().getClassLoader().getResource(resourcePath); 35 | if(url == null) 36 | throw new IllegalArgumentException("Directory isn't found. Path: "+resourcePath); 37 | 38 | JarURLConnection jarConn; 39 | try { 40 | jarConn = (JarURLConnection) url.openConnection(); 41 | JarFile jarFile = jarConn.getJarFile(); 42 | Enumeration entrys = jarFile.entries(); 43 | while(entrys.hasMoreElements()){ 44 | JarEntry entry = entrys.nextElement(); 45 | if(entry.getName().startsWith(resourcePath)&&!entry.isDirectory()) 46 | plugin.saveResource(entry.getName(), replace); 47 | } 48 | } catch (IOException e) { 49 | plugin.getLogger().warning("Plugin save directory failed. Path: " + resourcePath); 50 | e.printStackTrace(); 51 | } 52 | } 53 | 54 | static void registerEvents(Listener listener, Plugin plugin){ 55 | Bukkit.getPluginManager().registerEvents(listener, plugin); 56 | } 57 | 58 | /** 59 | * Call event. 60 | */ 61 | static T callEvent(T event) { 62 | Bukkit.getPluginManager().callEvent(event); 63 | return event; 64 | } 65 | 66 | /** 67 | * Call event. 68 | * 69 | * @param event the event to be call 70 | * @return event.isCancelled() or false 71 | */ 72 | static boolean callEventIsCancelled(Event event) { 73 | Bukkit.getPluginManager().callEvent(event); 74 | return event instanceof Cancellable && ((Cancellable) event).isCancelled(); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/Result.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.util; 2 | 3 | import com.google.common.base.Strings; 4 | 5 | import javax.annotation.Nullable; 6 | 7 | public final class Result { 8 | 9 | private static final Result SUCCESS_RESULT = new Result(true); 10 | 11 | public static Result success() { 12 | return SUCCESS_RESULT; 13 | } 14 | 15 | public static Result failure() { 16 | return new Result(false); 17 | } 18 | 19 | public static Result failure(String message) { 20 | return new Result(false, message); 21 | } 22 | 23 | public static Result failure(Throwable throwable) { 24 | return new Result(false, throwable); 25 | } 26 | 27 | public static Result failure(String message, Throwable throwable) { 28 | return new Result(false, message, throwable); 29 | } 30 | 31 | private final boolean success; 32 | private final String message; 33 | private final Throwable throwable; 34 | 35 | private Result(boolean success) { 36 | this(success, null, null); 37 | } 38 | 39 | private Result(boolean success, String message) { 40 | this(success, message, null); 41 | } 42 | 43 | private Result(boolean success, Throwable throwable) { 44 | this(success, null, throwable); 45 | } 46 | 47 | private Result(boolean success, String message, Throwable throwable) { 48 | this.success = success; 49 | this.message = Strings.nullToEmpty(message); 50 | this.throwable = throwable; 51 | } 52 | 53 | public boolean isSuccess() { 54 | return success; 55 | } 56 | 57 | public boolean isFailure() { 58 | return !success; 59 | } 60 | 61 | public String getMessage() { 62 | return message; 63 | } 64 | 65 | @Nullable 66 | public Throwable getThrowable() { 67 | return throwable; 68 | } 69 | 70 | @Override 71 | public String toString() { 72 | return String.format("team.unstudio.udpl.util.Result[success: %b, message: %s, throwable: %s]", success, message == null ? "null" : message, throwable == null ? "null" : throwable.toString()); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/ServerUtils.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.util; 2 | 3 | import org.bukkit.Bukkit; 4 | import org.bukkit.entity.HumanEntity; 5 | import team.unstudio.udpl.UDPLib; 6 | import team.unstudio.udpl.util.reflect.ReflectionUtils; 7 | 8 | import java.util.List; 9 | import java.util.concurrent.atomic.AtomicReference; 10 | import java.util.function.Predicate; 11 | import java.util.stream.Collectors; 12 | 13 | /** 14 | * Server util to quickly 15 | */ 16 | public interface ServerUtils { 17 | 18 | /** 19 | * get online players' name 20 | */ 21 | static List getOnlinePlayerNames(){ 22 | return Bukkit.getOnlinePlayers().stream().map(HumanEntity::getName).collect(Collectors.toList()); 23 | } 24 | 25 | /** 26 | * get all online players' name with a filter 27 | */ 28 | static List getOnlinePlayerNamesWithFilter(Predicate filter){ 29 | return Bukkit.getOnlinePlayers().stream().map(HumanEntity::getName).filter(filter).collect(Collectors.toList()); 30 | } 31 | 32 | /** 33 | * cached minecraft version 34 | */ 35 | AtomicReference MINECRAFT_VERSION = new AtomicReference<>(); 36 | 37 | /** 38 | * get minecraft version like "1.11.2" 39 | */ 40 | static String getMinecraftVersion() { 41 | if (MINECRAFT_VERSION.get() == null) { 42 | try { 43 | MINECRAFT_VERSION.set((String) ReflectionUtils.invokeMethod( 44 | ReflectionUtils.getValue(Bukkit.getServer(), true, "console"), "getVersion", false)); 45 | } catch (ReflectiveOperationException e) { 46 | UDPLib.debug(e); 47 | String bukkitVersion = Bukkit.getBukkitVersion(); 48 | int index = Bukkit.getBukkitVersion().indexOf("-"); 49 | MINECRAFT_VERSION.set(bukkitVersion.substring(0, index == -1 ? bukkitVersion.length() : index)); 50 | } 51 | } 52 | return MINECRAFT_VERSION.get(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/asm/CurrentFrame.java: -------------------------------------------------------------------------------- 1 | /*** 2 | * ASM: a very small and fast Java bytecode manipulation framework 3 | * Copyright (c) 2000-2011 INRIA, France Telecom 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions 8 | * are met: 9 | * 1. Redistributions of source code must retain the above copyright 10 | * notice, this list of conditions and the following disclaimer. 11 | * 2. Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * 3. Neither the name of the copyright holders nor the names of its 15 | * contributors may be used to endorse or promote products derived from 16 | * this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | 31 | package team.unstudio.udpl.util.asm; 32 | 33 | /** 34 | * Information about the input stack map frame at the "current" instruction of a 35 | * method. This is implemented as a Frame subclass for a "basic block" 36 | * containing only one instruction. 37 | * 38 | * @author Eric Bruneton 39 | */ 40 | class CurrentFrame extends Frame { 41 | 42 | /** 43 | * Sets this CurrentFrame to the input stack map frame of the next "current" 44 | * instruction, i.e. the instruction just after the given one. It is assumed 45 | * that the value of this object when this method is called is the stack map 46 | * frame status just before the given instruction is executed. 47 | */ 48 | @Override 49 | void execute(int opcode, int arg, ClassWriter cw, Item item) { 50 | super.execute(opcode, arg, cw, item); 51 | Frame successor = new Frame(); 52 | merge(cw, successor, 0); 53 | set(successor); 54 | owner.inputStackTop = 0; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/asm/commons/TableSwitchGenerator.java: -------------------------------------------------------------------------------- 1 | /*** 2 | * ASM: a very small and fast Java bytecode manipulation framework 3 | * Copyright (c) 2000-2011 INRIA, France Telecom 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions 8 | * are met: 9 | * 1. Redistributions of source code must retain the above copyright 10 | * notice, this list of conditions and the following disclaimer. 11 | * 2. Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * 3. Neither the name of the copyright holders nor the names of its 15 | * contributors may be used to endorse or promote products derived from 16 | * this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | package team.unstudio.udpl.util.asm.commons; 31 | 32 | import team.unstudio.udpl.util.asm.Label; 33 | 34 | /** 35 | * A code generator for switch statements. 36 | * 37 | * @author Juozas Baliuka 38 | * @author Chris Nokleberg 39 | * @author Eric Bruneton 40 | */ 41 | public interface TableSwitchGenerator { 42 | 43 | /** 44 | * Generates the code for a switch case. 45 | * 46 | * @param key 47 | * the switch case key. 48 | * @param end 49 | * a label that corresponds to the end of the switch statement. 50 | */ 51 | void generateCase(int key, Label end); 52 | 53 | /** 54 | * Generates the code for the default switch case. 55 | */ 56 | void generateDefault(); 57 | } 58 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/asm/signature/package.html: -------------------------------------------------------------------------------- 1 | 2 | 31 | 32 | Provides support for type signatures. 33 | 34 | @since ASM 2.0 35 | 36 | 37 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/asm/tree/LabelNode.java: -------------------------------------------------------------------------------- 1 | /*** 2 | * ASM: a very small and fast Java bytecode manipulation framework 3 | * Copyright (c) 2000-2011 INRIA, France Telecom 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions 8 | * are met: 9 | * 1. Redistributions of source code must retain the above copyright 10 | * notice, this list of conditions and the following disclaimer. 11 | * 2. Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * 3. Neither the name of the copyright holders nor the names of its 15 | * contributors may be used to endorse or promote products derived from 16 | * this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | package team.unstudio.udpl.util.asm.tree; 31 | 32 | import java.util.Map; 33 | 34 | import team.unstudio.udpl.util.asm.Label; 35 | import team.unstudio.udpl.util.asm.MethodVisitor; 36 | 37 | /** 38 | * An {@link AbstractInsnNode} that encapsulates a {@link Label}. 39 | */ 40 | public class LabelNode extends AbstractInsnNode { 41 | 42 | private Label label; 43 | 44 | public LabelNode() { 45 | super(-1); 46 | } 47 | 48 | public LabelNode(final Label label) { 49 | super(-1); 50 | this.label = label; 51 | } 52 | 53 | @Override 54 | public int getType() { 55 | return LABEL; 56 | } 57 | 58 | public Label getLabel() { 59 | if (label == null) { 60 | label = new Label(); 61 | } 62 | return label; 63 | } 64 | 65 | @Override 66 | public void accept(final MethodVisitor cv) { 67 | cv.visitLabel(getLabel()); 68 | } 69 | 70 | @Override 71 | public AbstractInsnNode clone(final Map labels) { 72 | return labels.get(this); 73 | } 74 | 75 | public void resetLabel() { 76 | label = null; 77 | } 78 | } -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/asm/tree/analysis/AnalyzerException.java: -------------------------------------------------------------------------------- 1 | /*** 2 | * ASM: a very small and fast Java bytecode manipulation framework 3 | * Copyright (c) 2000-2011 INRIA, France Telecom 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions 8 | * are met: 9 | * 1. Redistributions of source code must retain the above copyright 10 | * notice, this list of conditions and the following disclaimer. 11 | * 2. Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * 3. Neither the name of the copyright holders nor the names of its 15 | * contributors may be used to endorse or promote products derived from 16 | * this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | package team.unstudio.udpl.util.asm.tree.analysis; 31 | 32 | import team.unstudio.udpl.util.asm.tree.AbstractInsnNode; 33 | 34 | /** 35 | * Thrown if a problem occurs during the analysis of a method. 36 | * 37 | * @author Bing Ran 38 | * @author Eric Bruneton 39 | */ 40 | @SuppressWarnings("serial") 41 | public class AnalyzerException extends Exception { 42 | 43 | public final AbstractInsnNode node; 44 | 45 | public AnalyzerException(final AbstractInsnNode node, final String msg) { 46 | super(msg); 47 | this.node = node; 48 | } 49 | 50 | public AnalyzerException(final AbstractInsnNode node, final String msg, 51 | final Throwable exception) { 52 | super(msg, exception); 53 | this.node = node; 54 | } 55 | 56 | public AnalyzerException(final AbstractInsnNode node, final String msg, 57 | final Object expected, final Value encountered) { 58 | super((msg == null ? "Expected " : msg + ": expected ") + expected 59 | + ", but found " + encountered); 60 | this.node = node; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/asm/tree/analysis/Value.java: -------------------------------------------------------------------------------- 1 | /*** 2 | * ASM: a very small and fast Java bytecode manipulation framework 3 | * Copyright (c) 2000-2011 INRIA, France Telecom 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions 8 | * are met: 9 | * 1. Redistributions of source code must retain the above copyright 10 | * notice, this list of conditions and the following disclaimer. 11 | * 2. Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * 3. Neither the name of the copyright holders nor the names of its 15 | * contributors may be used to endorse or promote products derived from 16 | * this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | package team.unstudio.udpl.util.asm.tree.analysis; 31 | 32 | /** 33 | * An immutable symbolic value for semantic interpretation of bytecode. 34 | * 35 | * @author Eric Bruneton 36 | */ 37 | public interface Value { 38 | 39 | /** 40 | * Returns the size of this value in words. 41 | * 42 | * @return either 1 or 2. 43 | */ 44 | int getSize(); 45 | } 46 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/asm/tree/analysis/package.html: -------------------------------------------------------------------------------- 1 | 2 | 31 | 32 | 33 |

34 | Provides a framework for static code analysis based on the asm.tree package. 35 |

36 | 37 |

38 | Basic usage: 39 |

40 | 41 |
42 | ClassReader cr = new ClassReader(bytecode);
43 | ClassNode cn = new ClassNode();
44 | cr.accept(cn, ClassReader.SKIP_DEBUG);
45 | 
46 | List methods = cn.methods;
47 | for (int i = 0; i < methods.size(); ++i) {
48 |     MethodNode method = (MethodNode) methods.get(i);
49 |     if (method.instructions.size() > 0) {
50 |         Analyzer a = new Analyzer(new BasicInterpreter());
51 |         a.analyze(cn.name, method);
52 |         Frame[] frames = a.getFrames();
53 |         // Elements of the frames arrray now contains info for each instruction
54 |         // from the analyzed method. BasicInterpreter creates BasicValue, that
55 |         // is using simplified type system that distinguishes the UNINITIALZED,
56 |         // INT, FLOAT, LONG, DOUBLE, REFERENCE and RETURNADDRESS types.
57 |         ...
58 |     }
59 | }
60 | 
61 | 62 |

63 | @since ASM 1.4.3 64 |

65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/asm/util/ASMifiable.java: -------------------------------------------------------------------------------- 1 | /** 2 | * ASM: a very small and fast Java bytecode manipulation framework 3 | * Copyright (c) 2000-2011 INRIA, France Telecom 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions 8 | * are met: 9 | * 1. Redistributions of source code must retain the above copyright 10 | * notice, this list of conditions and the following disclaimer. 11 | * 2. Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * 3. Neither the name of the copyright holders nor the names of its 15 | * contributors may be used to endorse or promote products derived from 16 | * this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | package team.unstudio.udpl.util.asm.util; 31 | 32 | import java.util.Map; 33 | 34 | import team.unstudio.udpl.util.asm.Label; 35 | 36 | /** 37 | * An {@link team.unstudio.udpl.util.asm.Attribute Attribute} that can print the ASM code 38 | * to create an equivalent attribute. 39 | * 40 | * @author Eugene Kuleshov 41 | */ 42 | public interface ASMifiable { 43 | 44 | /** 45 | * Prints the ASM code to create an attribute equal to this attribute. 46 | * 47 | * @param buf 48 | * a buffer used for printing Java code. 49 | * @param varName 50 | * name of the variable in a printed code used to store attribute 51 | * instance. 52 | * @param labelNames 53 | * map of label instances to their names. 54 | */ 55 | void asmify(StringBuffer buf, String varName, Map labelNames); 56 | } 57 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/asm/util/Textifiable.java: -------------------------------------------------------------------------------- 1 | /** 2 | * ASM: a very small and fast Java bytecode manipulation framework 3 | * Copyright (c) 2000-2011 INRIA, France Telecom 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions 8 | * are met: 9 | * 1. Redistributions of source code must retain the above copyright 10 | * notice, this list of conditions and the following disclaimer. 11 | * 2. Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * 3. Neither the name of the copyright holders nor the names of its 15 | * contributors may be used to endorse or promote products derived from 16 | * this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | package team.unstudio.udpl.util.asm.util; 31 | 32 | import java.util.Map; 33 | 34 | import team.unstudio.udpl.util.asm.Label; 35 | 36 | /** 37 | * An {@link team.unstudio.udpl.util.asm.Attribute Attribute} that can print a readable 38 | * representation of itself. 39 | * 40 | * Implementations should construct readable output from an attribute data 41 | * structure. Such representation could be used in unit test assertions. 42 | * 43 | * @author Eugene Kuleshov 44 | */ 45 | public interface Textifiable { 46 | 47 | /** 48 | * Build a human readable representation of this attribute. 49 | * 50 | * @param buf 51 | * a buffer used for printing Java code. 52 | * @param labelNames 53 | * map of label instances to their names. 54 | */ 55 | void textify(StringBuffer buf, Map labelNames); 56 | } 57 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/asm/util/package.html: -------------------------------------------------------------------------------- 1 | 2 | 31 | 32 | Provides ASM visitors that can be useful for programming and 33 | debugging purposes. These class visitors are normally not used by applications 34 | at runtime. This is why they are bundled in an optional asm-util.jar 35 | library that is separated from (but requires) the asm.jar library, 36 | which contains the core ASM framework. 37 | 38 | @since ASM 1.3.2 39 | 40 | 41 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/extra/ASMClassLoader.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.util.extra; 2 | 3 | public class ASMClassLoader extends ClassLoader { 4 | 5 | public ASMClassLoader() { 6 | } 7 | 8 | public ASMClassLoader(ClassLoader parent) { 9 | super(parent); 10 | } 11 | 12 | public Class loadClass(byte[] b) { 13 | return loadClass(null, b); 14 | } 15 | 16 | public Class loadClass(String name, byte[] b) { 17 | return defineClass(name, b, 0, b.length); 18 | } 19 | 20 | public Class loadClass(String name, byte[] b, int off, int len) { 21 | return defineClass(name, b, off, len); 22 | } 23 | 24 | public boolean hasClass(String name) { 25 | try { 26 | Class.forName(name); 27 | return true; 28 | } catch (ClassNotFoundException e) { 29 | return false; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/extra/Chunk.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.util.extra; 2 | 3 | import org.bukkit.Location; 4 | import org.bukkit.World; 5 | 6 | public final class Chunk { 7 | private final World world; 8 | private final int chunkX, chunkZ; 9 | 10 | public Chunk(Location location) { 11 | world = location.getWorld(); 12 | chunkX = location.getBlockX() >> 4; 13 | chunkZ = location.getBlockZ() >> 4; 14 | } 15 | 16 | public Chunk(World world, int chunkX, int chunkZ) { 17 | this.world = world; 18 | this.chunkX = chunkX; 19 | this.chunkZ = chunkZ; 20 | } 21 | 22 | public World getWorld() { 23 | return world; 24 | } 25 | 26 | public int getChunkX() { 27 | return chunkX; 28 | } 29 | 30 | public int getChunkZ() { 31 | return chunkZ; 32 | } 33 | 34 | @Override 35 | public boolean equals(Object obj) { 36 | if (obj == null) return false; 37 | 38 | if (!(obj instanceof Chunk)) return false; 39 | 40 | Chunk other = (Chunk) obj; 41 | 42 | if (!world.equals(other.world)) return false; 43 | 44 | if (chunkX != other.chunkX) return false; 45 | 46 | //noinspection RedundantIfStatement 47 | if (chunkZ != other.chunkZ) return false; 48 | 49 | return true; 50 | } 51 | 52 | @Override 53 | public int hashCode() { 54 | return world.hashCode() * 37 * 37 + chunkX * 37 + chunkZ; 55 | } 56 | 57 | @Override 58 | public String toString() { 59 | return String.format("{world:%s,chunkx:%s,chunkz:%s}", getWorld().getName(), getChunkX(), getChunkZ()); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/extra/IndexedItemStack.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.util.extra; 2 | 3 | import org.bukkit.inventory.ItemStack; 4 | 5 | import java.util.Objects; 6 | 7 | public final class IndexedItemStack { 8 | 9 | private final ItemStack itemStack; 10 | private final int index; 11 | 12 | public IndexedItemStack(ItemStack itemStack, int index) { 13 | this.itemStack = itemStack; 14 | this.index = index; 15 | } 16 | 17 | public ItemStack getItemStack() { 18 | return itemStack; 19 | } 20 | 21 | public int getIndex() { 22 | return index; 23 | } 24 | 25 | @Override 26 | public boolean equals(Object obj) { 27 | if(obj == null) 28 | return false; 29 | 30 | if(!(obj instanceof IndexedItemStack)) 31 | return false; 32 | 33 | IndexedItemStack value = (IndexedItemStack) obj; 34 | if(getIndex() != value.getIndex()) 35 | return false; 36 | 37 | //noinspection RedundantIfStatement 38 | if(!getItemStack().equals(value.getItemStack())) 39 | return false; 40 | 41 | return true; 42 | } 43 | 44 | @Override 45 | public int hashCode() { 46 | return Objects.hash(getItemStack(),getIndex()); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/extra/ZipUtils.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.util.extra; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileNotFoundException; 6 | import java.io.FileOutputStream; 7 | import java.io.IOException; 8 | import java.io.InputStream; 9 | import java.nio.file.Files; 10 | import java.nio.file.Path; 11 | import java.util.stream.Collectors; 12 | import java.util.zip.ZipEntry; 13 | import java.util.zip.ZipOutputStream; 14 | 15 | public interface ZipUtils { 16 | static boolean zip(File zipFile, File... inputFiles) throws IOException { 17 | try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile))) { 18 | for (File file : inputFiles) { 19 | if (file.isDirectory()) 20 | zip(out, file, ""); 21 | else 22 | zip(out, file, file.getName()); 23 | } 24 | return true; 25 | } 26 | } 27 | 28 | static boolean zip(Path zipFile, Path... inputFiles) throws IOException { 29 | try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(zipFile))) { 30 | for (Path file : inputFiles) { 31 | if (Files.isDirectory(file)) 32 | zip(out, file, ""); 33 | else 34 | zip(out, file, file.toString()); 35 | } 36 | return true; 37 | } 38 | } 39 | 40 | static void zip(ZipOutputStream out, Path f, String base) throws IOException { 41 | if (Files.isDirectory(f)) { 42 | if (!base.isEmpty()) { 43 | out.putNextEntry(new ZipEntry(base + "/")); 44 | base = base + "/"; 45 | } 46 | String finalBase = base; 47 | for (Path f1: Files.list(f).collect(Collectors.toList())) // 递归遍历子文件夹 48 | zip(out, f1, finalBase + f1.toString()); 49 | } else { 50 | out.putNextEntry(new ZipEntry(base)); // 创建zip压缩进入点base 51 | try (InputStream in = Files.newInputStream(f)){ 52 | int b; 53 | while ((b = in.read()) != -1) 54 | out.write(b); // 将字节流写入当前zip目录 55 | } 56 | } 57 | } 58 | 59 | static void zip(ZipOutputStream out, File f, String base) throws IOException { 60 | if (f.isDirectory()) { 61 | if (!base.isEmpty()) { 62 | out.putNextEntry(new ZipEntry(base + "/")); 63 | base = base + "/"; 64 | } 65 | for (File f1:f.listFiles()) { 66 | zip(out, f1, base + f1.getName()); // 递归遍历子文件夹 67 | } 68 | } else { 69 | out.putNextEntry(new ZipEntry(base)); // 创建zip压缩进入点base 70 | try(FileInputStream in = new FileInputStream(f)){ 71 | int b; 72 | while ((b = in.read()) != -1) 73 | out.write(b); // 将字节流写入当前zip目录 74 | } 75 | } 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/lazy/Lazy.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.util.lazy; 2 | 3 | public interface Lazy { 4 | T get(); 5 | } 6 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/reflect/NMSReflectionUtils.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.util.reflect; 2 | 3 | import team.unstudio.udpl.UDPLib; 4 | import team.unstudio.udpl.annotation.Init; 5 | import team.unstudio.udpl.util.reflect.ReflectionUtils.PackageType; 6 | 7 | import static team.unstudio.udpl.util.reflect.ReflectionUtils.getField; 8 | import static team.unstudio.udpl.util.reflect.ReflectionUtils.getMethod; 9 | 10 | import java.lang.reflect.Constructor; 11 | import java.lang.reflect.Field; 12 | import java.lang.reflect.Method; 13 | 14 | import org.bukkit.inventory.ItemStack; 15 | 16 | public final class NMSReflectionUtils { 17 | 18 | private static Method CraftPlayer$getHandle; 19 | private static Field EntityPlayer$locale; 20 | private static Field CraftMetaBoox$pages; 21 | private static Method IChatBaseComponent$ChatSerializer$a; 22 | private static Method CraftItemStack$asNMSCopy; 23 | private static Method ItemStack$save; 24 | private static Class NBTTagCompound; 25 | private static Constructor NBTTagCompound$init; 26 | 27 | public static Method CraftPlayer$getHandle() { 28 | return CraftPlayer$getHandle; 29 | } 30 | 31 | public static Field EntityPlayer$locale() { 32 | return EntityPlayer$locale; 33 | } 34 | 35 | public static Field CraftMetaBook$pages() { 36 | return CraftMetaBoox$pages; 37 | } 38 | 39 | public static Method IChatBaseComponent$ChatSerializer$a() { 40 | return IChatBaseComponent$ChatSerializer$a; 41 | } 42 | 43 | public static Method CraftItemStack$asNMSCopy() { 44 | return CraftItemStack$asNMSCopy; 45 | } 46 | 47 | public static Method ItemStack$save() { 48 | return ItemStack$save; 49 | } 50 | 51 | public static Class NBTTagCompound() { 52 | return NBTTagCompound; 53 | } 54 | 55 | public static Constructor NBTTagCompound$init() { 56 | return NBTTagCompound$init; 57 | } 58 | 59 | @Init 60 | private static void init() { 61 | try { 62 | CraftPlayer$getHandle = getMethod("CraftPlayer", PackageType.CRAFTBUKKIT_ENTITY, "getHandle", true); 63 | EntityPlayer$locale = getField("EntityPlayer", PackageType.MINECRAFT_SERVER, true, "locale"); 64 | CraftMetaBoox$pages = getField("CraftMetaBook", PackageType.CRAFTBUKKIT_INVENTORY, true, "pages"); 65 | IChatBaseComponent$ChatSerializer$a = getMethod("IChatBaseComponent$ChatSerializer", 66 | ReflectionUtils.PackageType.MINECRAFT_SERVER, "a", true, String.class); 67 | CraftItemStack$asNMSCopy = getMethod("CraftItemStack", PackageType.CRAFTBUKKIT_INVENTORY, "asNMSCopy", true, 68 | ItemStack.class); 69 | NBTTagCompound = PackageType.MINECRAFT_SERVER.getClass("NBTTagCompound"); 70 | NBTTagCompound$init = NBTTagCompound.getConstructor(); 71 | ItemStack$save = getMethod("ItemStack", PackageType.MINECRAFT_SERVER, "save", true, NBTTagCompound); 72 | } catch (ReflectiveOperationException e) { 73 | UDPLib.debug(e); 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/reflect/UnsafeReflections.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.util.reflect; 2 | 3 | import java.lang.reflect.Field; 4 | import java.lang.reflect.Modifier; 5 | 6 | public interface UnsafeReflections { 7 | 8 | public static Field accessible(Field field) { 9 | field.setAccessible(true); 10 | return field; 11 | } 12 | 13 | public static Field unfinal(Field field) throws ReflectiveOperationException { 14 | Field modifiers = Field.class.getDeclaredField("modifiers"); 15 | modifiers.setAccessible(true); 16 | modifiers.setInt(field, field.getModifiers() &~ Modifier.FINAL); 17 | return field; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/util/reflect/UnsafeUtils.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.util.reflect; 2 | 3 | import java.lang.reflect.Field; 4 | 5 | import sun.misc.Unsafe; 6 | 7 | public final class UnsafeUtils { 8 | 9 | private UnsafeUtils() { 10 | } 11 | 12 | private static final Unsafe UNSAFE; 13 | static { 14 | Unsafe unsafe; 15 | try { 16 | Class clazz = Class.forName("sun.misc.Unsafe"); 17 | Field theUnsafe = clazz.getDeclaredField("theUnsafe"); 18 | theUnsafe.setAccessible(true); 19 | unsafe = (Unsafe) theUnsafe.get(null); 20 | } catch (ClassNotFoundException | NoSuchFieldException | SecurityException e) { 21 | unsafe = null; 22 | } catch (IllegalAccessException e) { 23 | throw new AssertionError(e); 24 | } 25 | UNSAFE = unsafe; 26 | } 27 | 28 | public static boolean isUnsafeSupported() { 29 | return UNSAFE != null; 30 | } 31 | 32 | public static Unsafe getUnsafe() { 33 | return UNSAFE; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/variable/SimpleVariableHandler.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.variable; 2 | 3 | import com.google.common.collect.Maps; 4 | import org.apache.commons.lang.Validate; 5 | import org.bukkit.entity.Player; 6 | import org.bukkit.plugin.Plugin; 7 | 8 | import javax.annotation.Nonnull; 9 | import java.util.Map; 10 | import java.util.function.Function; 11 | 12 | public class SimpleVariableHandler implements VariableHandler{ 13 | 14 | private final String name; 15 | private final Plugin plugin; 16 | private final Map> variableHandlers = Maps.newHashMap(); 17 | 18 | public SimpleVariableHandler(@Nonnull String name, @Nonnull Plugin plugin) { 19 | Validate.notEmpty(name); 20 | Validate.notNull(plugin); 21 | this.name = name; 22 | this.plugin = plugin; 23 | } 24 | 25 | public SimpleVariableHandler(@Nonnull String name, @Nonnull Plugin plugin, Map> variableHandlers) { 26 | Validate.notEmpty(name); 27 | Validate.notNull(plugin); 28 | this.name = name; 29 | this.plugin = plugin; 30 | this.variableHandlers.putAll(variableHandlers); 31 | } 32 | 33 | public Map> getVariableHandlers() { 34 | return variableHandlers; 35 | } 36 | 37 | public SimpleVariableHandler addVariableHandler(String key, Function handler){ 38 | variableHandlers.put(key, handler); 39 | return this; 40 | } 41 | 42 | @Override 43 | public Plugin getPlugin() { 44 | return plugin; 45 | } 46 | 47 | @Override 48 | public String getName() { 49 | return name; 50 | } 51 | 52 | @Override 53 | public String get(Player player, String key) { 54 | if(!variableHandlers.containsKey(key)) 55 | return null; 56 | 57 | return variableHandlers.get(key).apply(player); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/variable/VariableHandler.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.variable; 2 | 3 | import org.bukkit.entity.Player; 4 | import org.bukkit.plugin.Plugin; 5 | 6 | public interface VariableHandler { 7 | 8 | String getName(); 9 | 10 | String get(Player player, String key); 11 | 12 | Plugin getPlugin(); 13 | 14 | default boolean isRegistrable(){ 15 | return true; 16 | } 17 | 18 | default void register(){ 19 | if(!isRegistrable()) 20 | return; 21 | VariableHelper.register(this); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /udplib-common/src/main/java/team/unstudio/udpl/variable/VariableHelper.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.variable; 2 | 3 | import com.google.common.base.Strings; 4 | import com.google.common.collect.Sets; 5 | import org.apache.commons.lang.Validate; 6 | import org.bukkit.entity.Player; 7 | import org.bukkit.plugin.Plugin; 8 | 9 | import javax.annotation.Nonnull; 10 | import java.util.Set; 11 | 12 | public interface VariableHelper { 13 | Set REGISTERED_VARIABLE_HANDLERS = Sets.newLinkedHashSet(); 14 | 15 | static void register(@Nonnull VariableHandler handler){ 16 | Validate.notNull(handler); 17 | REGISTERED_VARIABLE_HANDLERS.add(handler); 18 | } 19 | 20 | static void unregister(@Nonnull VariableHandler handler){ 21 | Validate.notNull(handler); 22 | REGISTERED_VARIABLE_HANDLERS.remove(handler); 23 | } 24 | 25 | static void unregister(@Nonnull String name){ 26 | Validate.notEmpty(name); 27 | REGISTERED_VARIABLE_HANDLERS.removeIf(handler->name.equals(handler.getName())); 28 | } 29 | 30 | static void unregister(@Nonnull Plugin plugin){ 31 | Validate.notNull(plugin); 32 | REGISTERED_VARIABLE_HANDLERS.removeIf(handler->plugin.equals(handler.getPlugin())); 33 | } 34 | 35 | static String apply(Player player, String value){ 36 | return apply(player, value, '%', '%'); 37 | } 38 | 39 | static String apply(Player player, String value, char handlerStart, char handlerEnd){ 40 | StringBuilder result = new StringBuilder(value.length()); 41 | StringBuilder handlerName = new StringBuilder(); 42 | boolean handlerMatching = false; 43 | for(char c:value.toCharArray()){ 44 | if(handlerMatching){ 45 | if(c == handlerEnd){ 46 | handlerMatching = false; 47 | String handler = getValue(player, handlerName.toString()); 48 | if(Strings.isNullOrEmpty(handler)) 49 | result.append(handlerStart).append(handlerName.toString()).append(handlerEnd); 50 | else 51 | result.append(handler); 52 | handlerName.delete(0, handlerName.length()); 53 | }else 54 | handlerName.append(c); 55 | }else{ 56 | if(c == handlerStart) 57 | handlerMatching = true; 58 | else 59 | result.append(c); 60 | } 61 | } 62 | return result.toString(); 63 | } 64 | 65 | static String getValue(Player player, String name){ 66 | for(VariableHandler handler : REGISTERED_VARIABLE_HANDLERS){ 67 | try{ 68 | String value = handler.get(player, name); 69 | if(value != null) return value; 70 | }catch(Exception ignored){} 71 | } 72 | return null; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /udplib-core/.gitignore: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | !.gitignore 4 | !src/ 5 | !pom.xml -------------------------------------------------------------------------------- /udplib-core/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | team.unstudio 8 | udplib 9 | 1.3.3 10 | 11 | udplib-core 12 | UDPLib-core 13 | 14 | 15 | team.unstudio 16 | udplib-nms1_11_R1 17 | 18 | 19 | org.spigotmc 20 | spigot 21 | 22 | 23 | 24 | 25 | team.unstudio 26 | udplib-common 27 | 28 | 29 | 30 | 31 | 32 | org.apache.maven.plugins 33 | maven-shade-plugin 34 | 1.4 35 | 36 | 37 | package 38 | 39 | shade 40 | 41 | 42 | false 43 | false 44 | true 45 | 46 | 47 | team.unstudio:udplib-nms1_11_R1 48 | team.unstudio:udplib-common 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /udplib-core/src/main/java/team/unstudio/udpl/core/UDPLConfiguration.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.core; 2 | 3 | import team.unstudio.udpl.config.ConfigItem; 4 | import team.unstudio.udpl.config.ConfigurationHandler; 5 | 6 | import java.io.File; 7 | 8 | public final class UDPLConfiguration extends ConfigurationHandler{ 9 | @ConfigItem("enableTest") 10 | public boolean enableTest = false; 11 | 12 | @ConfigItem("debug") 13 | public boolean debug = false; 14 | 15 | @ConfigItem("language") 16 | public String language = ""; 17 | 18 | public UDPLConfiguration(File file) { 19 | super(file); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /udplib-core/src/main/java/team/unstudio/udpl/core/UDPLI18n.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.core; 2 | 3 | import org.bukkit.entity.Player; 4 | import team.unstudio.udpl.i18n.YamlI18n; 5 | 6 | import java.io.File; 7 | import java.util.Locale; 8 | 9 | /** 10 | * UDPLib本体所需的国际化配置 11 | * @author LasmGratel 12 | */ 13 | public interface UDPLI18n { 14 | YamlI18n I18N = YamlI18n.fromFile(new File(UDPLib.getInstance().getDataFolder(), "lang")); 15 | 16 | static void setLocale(Locale locale) { 17 | I18N.setDefaultLocale(locale); 18 | } 19 | 20 | static void setLocale(String locale) { 21 | I18N.setDefaultLocale(locale); 22 | } 23 | 24 | static String format(String key) { 25 | return I18N.localize(key); 26 | } 27 | 28 | static String format(String key, Object... args) { 29 | return I18N.format(key, args); 30 | } 31 | 32 | static String format(Locale locale, String key, Object... args) { 33 | return I18N.format(locale, key, args); 34 | } 35 | 36 | static String format(Player player, String key){ 37 | return I18N.localize(player, key); 38 | } 39 | 40 | static String format(Player player, String key, Object... args){ 41 | return I18N.format(player, key, args); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /udplib-core/src/main/java/team/unstudio/udpl/core/command/PluginManager.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.core.command; 2 | 3 | import org.bukkit.Bukkit; 4 | import org.bukkit.ChatColor; 5 | import org.bukkit.command.CommandSender; 6 | import org.bukkit.plugin.Plugin; 7 | import team.unstudio.udpl.command.anno.Command; 8 | import team.unstudio.udpl.command.anno.Required; 9 | 10 | import java.io.File; 11 | 12 | public final class PluginManager { 13 | 14 | private static final File PLUGIN_PATH = new File("plugins"); 15 | 16 | @Command(value = { "enable" }, permission = "udpl.pluginmanager.enable") 17 | public void enable(CommandSender sender, @Required(name="Plugin") String plugin) { 18 | if (!plugin.endsWith(".jar")) 19 | plugin = plugin + ".jar"; 20 | try { 21 | Bukkit.getPluginManager().enablePlugin(Bukkit.getPluginManager().loadPlugin(new File(PLUGIN_PATH, plugin))); 22 | sender.sendMessage("[PluginManager]加载插件成功: " + plugin); 23 | } catch (Exception e) { 24 | sender.sendMessage("[PluginManager]加载插件失败: " + plugin); 25 | } 26 | } 27 | 28 | @Command(value = { "disable" }, permission = "udpl.pluginmanager.disable") 29 | public void disable(CommandSender sender, @Required(name="Plugin") String plugin) { 30 | Bukkit.getPluginManager().disablePlugin(Bukkit.getPluginManager().getPlugin(plugin)); 31 | sender.sendMessage("[PluginManager]卸载插件成功: " + plugin); 32 | } 33 | 34 | @Command(value = { "plugins" }, permission = "udpl.pluginmanager.plugins") 35 | public void plugins(CommandSender sender) { 36 | StringBuilder b = new StringBuilder("[PluginManager]Plugins: "); 37 | for (Plugin p : Bukkit.getPluginManager().getPlugins()) 38 | b.append(p.isEnabled() ? ChatColor.GREEN : ChatColor.RED).append(p.getName()).append(" "); 39 | sender.sendMessage(b.toString()); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /udplib-core/src/main/java/team/unstudio/udpl/core/command/UDPLCommand.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.core.command; 2 | 3 | import org.bukkit.Bukkit; 4 | import org.bukkit.command.CommandSender; 5 | import team.unstudio.udpl.command.anno.Command; 6 | import team.unstudio.udpl.UDPLib; 7 | import team.unstudio.udpl.util.ServerUtils; 8 | import team.unstudio.udpl.util.reflect.ReflectionUtils; 9 | 10 | public final class UDPLCommand { 11 | 12 | @Command(value = "debug", permission = "udpl.debug") 13 | public void debug(CommandSender sender) { 14 | if (UDPLib.isDebug()) { 15 | UDPLib.setDebug(false); 16 | sender.sendMessage("UDPL Debug disabled."); 17 | } else { 18 | UDPLib.setDebug(true); 19 | sender.sendMessage("UDPL Debug enabled."); 20 | } 21 | } 22 | 23 | @Command(value = "info", permission = "udpl.info") 24 | public void info(CommandSender sender){ 25 | sender.sendMessage("----------UDPL Infomation----------"); 26 | sender.sendMessage("UDPL Version: " + UDPLib.getPlugin().getDescription().getVersion()); 27 | sender.sendMessage("Minecraft Version: " + ServerUtils.getMinecraftVersion()); 28 | sender.sendMessage("Bukkit Version: " + ReflectionUtils.PackageType.getServerVersion()); 29 | sender.sendMessage("ProtocolLib Version: " + Bukkit.getPluginManager().getPlugin("ProtocolLib").getDescription().getVersion()); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /udplib-core/src/main/java/team/unstudio/udpl/core/inject/Injector.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.core.inject; 2 | 3 | import java.lang.reflect.Field; 4 | import java.lang.reflect.InvocationTargetException; 5 | import java.lang.reflect.Method; 6 | import java.lang.reflect.Modifier; 7 | import java.util.ArrayList; 8 | import java.util.HashMap; 9 | import java.util.List; 10 | import java.util.Map; 11 | 12 | import team.unstudio.udpl.core.UDPLib; 13 | import team.unstudio.udpl.annotation.Init; 14 | 15 | public class Injector { 16 | 17 | private final List> targetClasses = new ArrayList<>(); 18 | private final Map injectObject = new HashMap<>(); 19 | 20 | public Injector() {} 21 | 22 | public void addClass(Class clazz) { 23 | targetClasses.add(clazz); 24 | } 25 | 26 | public void addInjectObject(String name, Object obj) { 27 | injectObject.put(name, obj); 28 | } 29 | 30 | public void inject() { 31 | for(Class clazz : targetClasses) { 32 | for(Field field : clazz.getDeclaredFields()) { 33 | int modifiers = field.getModifiers(); 34 | if(Modifier.isFinal(modifiers)) 35 | continue; 36 | if(!Modifier.isStatic(modifiers)) 37 | continue; 38 | Init init = field.getAnnotation(Init.class); 39 | if(init == null) 40 | continue; 41 | field.setAccessible(true); 42 | try { 43 | field.set(null, injectObject.get(init.value())); 44 | } catch (IllegalArgumentException | IllegalAccessException e) { 45 | UDPLib.getLog().warn(e.getMessage(), e); 46 | } 47 | } 48 | } 49 | for(Class clazz : targetClasses) { 50 | for(Method method : clazz.getDeclaredMethods()) { 51 | int modifiers = method.getModifiers(); 52 | if(!Modifier.isStatic(modifiers)) 53 | continue; 54 | Init init = method.getAnnotation(Init.class); 55 | if(init == null) 56 | continue; 57 | method.setAccessible(true); 58 | try { 59 | method.invoke(null); 60 | } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { 61 | UDPLib.getLog().warn(e.getMessage(), e); 62 | } 63 | } 64 | } 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /udplib-core/src/main/java/team/unstudio/udpl/core/util/AutoUpdate.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.core.util; 2 | 3 | import java.io.File; 4 | 5 | import org.apache.commons.lang3.NotImplementedException; 6 | import org.bukkit.scheduler.BukkitRunnable; 7 | 8 | /** 9 | * 自动更新工具 10 | */ 11 | public class AutoUpdate implements Runnable { 12 | private final String[] downloadUrls; 13 | private final String fileName; 14 | private final String md5; 15 | private final String sha1; 16 | 17 | public AutoUpdate(String[] downloadUrls, String fileName, String md5, String sha1) { 18 | this.downloadUrls = downloadUrls; 19 | this.fileName = fileName; 20 | this.md5 = md5; 21 | this.sha1 = sha1; 22 | } 23 | 24 | /** 25 | * {@inheritDoc} 26 | */ 27 | @Override 28 | public void run() { 29 | File file = new File("plugins/".concat(fileName)); 30 | for (String downloadUrl : downloadUrls) { 31 | throw new NotImplementedException("Haven't supported auto update"); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /udplib-core/src/main/resources/config.yml: -------------------------------------------------------------------------------- 1 | enableTest: false 2 | debug: false 3 | language: en-US -------------------------------------------------------------------------------- /udplib-core/src/main/resources/lang/command.slang: -------------------------------------------------------------------------------- 1 | key |en-US |zh-CN 2 | unknown_command |§cUnknown command, type /%s help for help. |§c未知指令, 输入 /%s help 来获得帮助. 3 | no_permission |§cPermission denied for §e/%s |§c你没有执行 §e/%s §c的权限 4 | no_enough_parameter|§cNo enough parameter! Correct syntax: %s |§c参数不足! 正确使用方式: %s 5 | wrong_sender |§cUnable to use this command due to your terminal. |§c你当前的终端不能执行这个指令. 6 | wrong_parameter |§cWrong parameter type! Correct syntax: %s |§c参数错误! 正确使用方式: %s 7 | failure |§cFailed to execute this command, please check your console.|§c执行指令时出现错误, 请查看控制台了解错误信息.. -------------------------------------------------------------------------------- /udplib-core/src/main/resources/lang/en-US.yml: -------------------------------------------------------------------------------- 1 | # Debug 2 | debug.area.load: "Loading areas..." 3 | debug.area.loaded: "Loaded %s areas." 4 | debug.area.save: "Saving areas..." 5 | debug.area.saved: "Saved %s areas." 6 | debug.area.backup: "Backuping areas..." 7 | debug.area.backuped: "Backuped %s areas." 8 | 9 | # Message 10 | message.unknown_command: "§cUnknown command, type /%s help for help." 11 | message.no_permission: "§cPermission denied for §e/%s" 12 | message.no_enough_parameter: "§cNo enough parameter! Correct syntax: %s" 13 | message.wrong_sender: "§cUnable to use this command due to your terminal." 14 | message.wrong_parameter: "§cWrong parameter type! Correct syntax: %s" 15 | message.failure: "§cFailed to execute this command, please check your console." 16 | 17 | # Update 18 | plugin.found_new_version: "Found new version: %1$s, Download URL: %2$s ." -------------------------------------------------------------------------------- /udplib-core/src/main/resources/lang/zh-CN.yml: -------------------------------------------------------------------------------- 1 | # Debug 2 | debug.area.load: "正在加载区域..." 3 | debug.area.loaded: "加载了%s个区域." 4 | debug.area.save: "正在保存区域..." 5 | debug.area.saved: "保存了%s个区域." 6 | debug.area.backup: "正在备份区域..." 7 | debug.area.backuped: "备份了%s个区域." 8 | 9 | # Message 10 | message.unknown_command: "§c未知指令, 输入 /%s help 来获得帮助." 11 | message.no_permission: "§c你没有执行 §e/%s §c的权限" 12 | message.no_enough_parameter: "§c参数不足! 正确使用方式: %s" 13 | message.wrong_sender: "§c你当前的终端不能执行这个指令." 14 | message.wrong_parameter: "§c参数错误! 正确使用方式: %s" 15 | message.failure: "§c执行指令时出现错误, 请查看控制台了解错误信息." 16 | 17 | # Update 18 | plugin.found_new_version: "发现新版本: %1$s, 请到 %2$s 下载." -------------------------------------------------------------------------------- /udplib-core/src/main/resources/plugin.yml: -------------------------------------------------------------------------------- 1 | name: UDPLib 2 | main: team.unstudio.udpl.core.UDPLib 3 | version: 1.3.3 4 | authors: [Mouse, Trychen, UnknownDomain] 5 | description: Unknown Domain Spigot plugin library. 6 | depend: [ProtocolLib] 7 | commands: 8 | pm: 9 | udpl: 10 | -------------------------------------------------------------------------------- /udplib-core/src/test/java/team/unstudio/udpl/EncodingDetectTest.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl; 2 | 3 | import org.junit.AfterClass; 4 | import org.junit.Test; 5 | import team.unstudio.udpl.config.EncodingDetect; 6 | 7 | import java.io.File; 8 | import java.io.FileOutputStream; 9 | import java.io.IOException; 10 | import java.nio.charset.Charset; 11 | import java.util.Arrays; 12 | import java.util.Collections; 13 | import java.util.List; 14 | 15 | import static org.junit.Assert.fail; 16 | 17 | /** 18 | * Created by trychen on 17/7/29. 19 | */ 20 | public class EncodingDetectTest { 21 | private static File file = new File("encoding_tester.yml"); 22 | 23 | @Test 24 | public void guessingFileEncoding() throws IOException { 25 | guess("UTF-8", Collections.singletonList("Unicode")); 26 | guess("UTF-16", Collections.singletonList("Unicode")); 27 | guess("UTF-32", Arrays.asList("ASCII", "Unicode")); 28 | guess("GB2312", Collections.emptyList()); 29 | guess("GBK", Collections.singletonList("GB2312")); 30 | guess("GB18030", Collections.singletonList("GB2312")); 31 | guess("BIG5", Collections.emptyList()); 32 | guess("ISO-8859-1", Collections.singletonList("ASCII")); 33 | guess("Unicode", Collections.emptyList()); 34 | guess("CP1250", Collections.singletonList("ASCII")); 35 | } 36 | 37 | @AfterClass 38 | public static void delFile(){ 39 | file.delete(); 40 | } 41 | 42 | public void guess(String code, List expect) throws IOException { 43 | file.createNewFile(); 44 | FileOutputStream fileOutputStream = new FileOutputStream(file); 45 | fileOutputStream.write("TODO: 大家好!123/*-§".getBytes(Charset.forName(code))); 46 | fileOutputStream.close(); 47 | String encoding = EncodingDetect.getJavaEncode(file); 48 | file.delete(); 49 | if (!code.equals(encoding) && !expect.contains(encoding)){ 50 | fail(String.format("Can't guess file encoding %s as %s, %s found!", code, Arrays.toString(expect.toArray()), encoding)); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /udplib-core/src/test/java/team/unstudio/udpl/FileUtilsTest.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl; 2 | 3 | import org.junit.After; 4 | import org.junit.Before; 5 | import org.junit.Test; 6 | 7 | import team.unstudio.udpl.util.extra.FileUtils; 8 | 9 | import java.io.*; 10 | 11 | import static org.junit.Assert.*; 12 | 13 | public class FileUtilsTest { 14 | private static File file = new File("file_utils_tester"); 15 | private static final String LINE_SEPARATOR = System.getProperty("line.separator"); 16 | private static String[] DATA = { 17 | "Hello World!", 18 | "中文测试", 19 | "!_!*@)&#%§¶•∞" 20 | }; 21 | 22 | @Before 23 | public void resetFile() throws IOException { 24 | file.createNewFile(); 25 | 26 | Writer writer = new BufferedWriter( 27 | new OutputStreamWriter( 28 | new FileOutputStream(file), "UTF-8")); 29 | for (int i = 0; i < DATA.length; i++) { 30 | writer.write(DATA[i]); 31 | if (i != DATA.length - 1) writer.write(LINE_SEPARATOR); 32 | } 33 | writer.flush(); 34 | writer.close(); 35 | } 36 | 37 | @After 38 | public void delFile(){ 39 | // file.delete(); 40 | } 41 | 42 | @Test 43 | public void readFile() throws Exception { 44 | assertArrayEquals(DATA, FileUtils.readFile2Array(file, "UTF-8")); 45 | } 46 | } -------------------------------------------------------------------------------- /udplib-core/src/test/java/team/unstudio/udpl/I18nTest.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl; 2 | 3 | import org.junit.Test; 4 | import static org.junit.Assert.*; 5 | 6 | import team.unstudio.udpl.i18n.PropertiesI18n; 7 | import team.unstudio.udpl.i18n.SLangI18n; 8 | import team.unstudio.udpl.i18n.YamlI18n; 9 | 10 | import java.util.Locale; 11 | 12 | public class I18nTest { 13 | @Test 14 | public void testClassLoaderI18n(){ 15 | YamlI18n i18n = YamlI18n.fromClassLoader(I18nTest.class.getClassLoader(), "lang/yaml/"); 16 | i18n.setDefaultLocale(Locale.US); 17 | 18 | assertEquals("Internationalization %s.", i18n.localize("test")); 19 | assertEquals("Internationalization Translate.", i18n.format(i18n.getDefaultLocale(), "test", "Translate")); 20 | assertEquals("Internationalization Tester.", i18n.format(i18n.getDefaultLocale(), "test", "test2")); 21 | 22 | i18n.setDefaultLocale(Locale.SIMPLIFIED_CHINESE); 23 | 24 | assertEquals("国际化 %s.", i18n.localize("test")); 25 | assertEquals("国际化 翻译.", i18n.format(i18n.getDefaultLocale(), "test", "翻译")); 26 | assertEquals("国际化 测试.", i18n.format(i18n.getDefaultLocale(), "test", "test2")); 27 | } 28 | 29 | @Test 30 | public void testSLang(){ 31 | SLangI18n sLang = SLangI18n.fromClassLoader(I18nTest.class.getClassLoader(), "lang/slang/general.slang"); 32 | assertNotNull(sLang); 33 | assertEquals("测试", sLang.localize(Locale.SIMPLIFIED_CHINESE, "test")); 34 | assertEquals("Test", sLang.localize(Locale.US, "test")); 35 | assertEquals("Test ", sLang.localize(Locale.UK, "test")); 36 | } 37 | @Test 38 | public void testProperties(){ 39 | PropertiesI18n i18n = PropertiesI18n.fromClassLoader(I18nTest.class.getClassLoader(), "lang/properties/"); 40 | 41 | i18n.setDefaultLocale(Locale.US); 42 | 43 | assertEquals("Internationalization %s.", i18n.localize("test")); 44 | assertEquals("Internationalization Translate.", i18n.format(i18n.getDefaultLocale(), "test", "Translate")); 45 | assertEquals("Internationalization Tester.", i18n.format(i18n.getDefaultLocale(), "test", "test2")); 46 | 47 | i18n.setDefaultLocale(Locale.SIMPLIFIED_CHINESE); 48 | 49 | assertEquals("国际化 %s.", i18n.localize("test")); 50 | assertEquals("国际化 翻译.", i18n.format(i18n.getDefaultLocale(), "test", "翻译")); 51 | assertEquals("国际化 测试.", i18n.format(i18n.getDefaultLocale(), "test", "test2")); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /udplib-core/src/test/java/team/unstudio/udpl/NBTTest.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import org.bukkit.configuration.file.FileConfiguration; 6 | 7 | import org.junit.Test; 8 | import static org.junit.Assert.*; 9 | 10 | import team.unstudio.udpl.config.ConfigurationHelper; 11 | import team.unstudio.udpl.nms.nbt.NBTTagCompound; 12 | import team.unstudio.udpl.nms.nbt.NBTTagList; 13 | import team.unstudio.udpl.nms.nbt.NBTTagString; 14 | import team.unstudio.udpl.nms.nbt.NBTUtils; 15 | 16 | public class NBTTest { 17 | @Test 18 | public void nbt() throws IOException { 19 | NBTUtils.registerAllNBTSerilizable(); 20 | NBTTagCompound nbtTagCompound = new NBTTagCompound(); 21 | nbtTagCompound.setByte("byte", Byte.MAX_VALUE); 22 | nbtTagCompound.setByteArray("byteArray", new byte[]{Byte.MAX_VALUE,Byte.MIN_VALUE}); 23 | nbtTagCompound.setDouble("double", Double.MAX_VALUE); 24 | nbtTagCompound.setFloat("float", Float.MAX_VALUE); 25 | nbtTagCompound.setInt("int", Integer.MAX_VALUE); 26 | nbtTagCompound.setIntArray("intArray", new int[]{Integer.MAX_VALUE,Integer.MIN_VALUE}); 27 | nbtTagCompound.setLong("long", Long.MAX_VALUE); 28 | nbtTagCompound.setShort("short", Short.MAX_VALUE); 29 | nbtTagCompound.setString("string", "String"); 30 | nbtTagCompound.set("list", new NBTTagList(new NBTTagString("String"))); 31 | String expected = "{\"byte\":127B,\"byteArray\":[B;127,-128],\"double\":1.7976931348623157E308D,\"float\":3.4028235E38F,\"int\":2147483647,\"intArray\":[I;2147483647,-2147483648],\"long\":9223372036854775807L,\"short\":32767S,\"string\":\"String\",\"list\":[\"String\"]}"; 32 | assertEquals(expected, nbtTagCompound.toString()); 33 | 34 | NBTTagCompound deserializedNbt = (NBTTagCompound) NBTUtils.parseFromJson(nbtTagCompound.toString()); 35 | assertEquals(expected, deserializedNbt.toString()); 36 | 37 | File file = new File("nbt.yml"); 38 | FileConfiguration config = ConfigurationHelper.loadConfiguration(file); 39 | file.deleteOnExit(); 40 | 41 | config.set("nbt", nbtTagCompound); 42 | config.save(file); 43 | config = ConfigurationHelper.loadConfiguration(file); 44 | assertEquals(expected, config.get("nbt").toString()); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /udplib-core/src/test/java/team/unstudio/udpl/SLangTest.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl; 2 | 3 | import static java.util.Arrays.asList; 4 | import static org.junit.Assert.*; 5 | 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.junit.runners.Parameterized; 9 | import team.unstudio.udpl.i18n.slang.CachedSLang; 10 | import team.unstudio.udpl.i18n.slang.SLangSpliter; 11 | 12 | import java.util.Collection; 13 | import java.util.List; 14 | 15 | @RunWith(Parameterized.class) 16 | public class SLangTest { 17 | private CachedSLang[] sLang; 18 | private String[] datas; 19 | private String separator; 20 | private List checker; 21 | 22 | public SLangTest(Collection datas, String separator, List checker) { 23 | this.checker = checker; 24 | this.separator = separator; 25 | this.datas = datas.toArray(new String[0]); 26 | 27 | sLang = SLangSpliter.split(separator, this.datas); 28 | } 29 | 30 | @Parameterized.Parameters 31 | public static Collection input(){ 32 | return asList(new Object[][]{ 33 | {asList("key|en", "test| why ", "trim|trim ∞"), "\\|", asList("test", "why", "hello", "hello", "trim", "trim ")}, 34 | {asList("en|zh-CN|en-US", "test|测试|TEST", "second|第二|QWQ"), "\\|", asList("test", "测试", "test", "TEST", "second", "第二", "second", "QWQ", "why", "why")}, 35 | {asList("zh-CN en", "卧槽 woc"), " ", asList("卧槽", "woc")}, 36 | }); 37 | } 38 | 39 | @Test 40 | public void check(){ 41 | checkF:for (int i = 0; (i + 1) < checker.size(); i += 2) { 42 | String index = checker.get(i); 43 | String expected = checker.get(i + 1); 44 | 45 | for (CachedSLang lang : sLang) { 46 | String fact = lang.get(index); 47 | if (fact == null) continue; 48 | if (expected.equals(fact)) continue checkF; 49 | 50 | } 51 | 52 | fail(String.format("Can't match %s by key %s", expected, index)); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /udplib-core/src/test/resources/lang/properties/en-US.properties: -------------------------------------------------------------------------------- 1 | test= Internationalization %s. 2 | test2= Tester -------------------------------------------------------------------------------- /udplib-core/src/test/resources/lang/properties/zh-CN.properties: -------------------------------------------------------------------------------- 1 | test= 国际化 %s. 2 | test2= 测试 -------------------------------------------------------------------------------- /udplib-core/src/test/resources/lang/slang/general.slang: -------------------------------------------------------------------------------- 1 | # this is a comment 2 | key |en-US|zh-CN|en-GB 3 | test|Test |测试 |Test ∞ -------------------------------------------------------------------------------- /udplib-core/src/test/resources/lang/yaml/en-US.yml: -------------------------------------------------------------------------------- 1 | test: Internationalization %s. 2 | test2: Tester -------------------------------------------------------------------------------- /udplib-core/src/test/resources/lang/yaml/zh-CN.yml: -------------------------------------------------------------------------------- 1 | test: 国际化 %s. 2 | test2: 测试 -------------------------------------------------------------------------------- /udplib-nms1_11_R1/.gitignore: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | !.gitignore 4 | !src/ 5 | !pom.xml -------------------------------------------------------------------------------- /udplib-nms1_11_R1/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | team.unstudio 6 | udplib 7 | 1.3.3 8 | 9 | udplib-nms1_11_R1 10 | 11 | 12 | team.unstudio 13 | udplib-common 14 | 15 | 16 | org.spigotmc 17 | spigot 18 | 1.11.2-R0.1-SNAPSHOT 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /udplib-nms1_11_R1/src/main/java/team/unstudio/udpl/core/nms/v1_11_R1/entity/NmsEntity.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.core.nms.v1_11_R1.entity; 2 | 3 | import java.util.Set; 4 | 5 | import org.bukkit.craftbukkit.v1_11_R1.entity.CraftEntity; 6 | import org.bukkit.entity.Entity; 7 | 8 | import net.minecraft.server.v1_11_R1.NBTTagCompound; 9 | import team.unstudio.udpl.nms.NmsHelper; 10 | 11 | public class NmsEntity implements team.unstudio.udpl.nms.entity.NmsEntity{ 12 | 13 | private final E entity; 14 | private final N nmsEntity; 15 | 16 | @SuppressWarnings("unchecked") 17 | public NmsEntity(E entity) { 18 | this.entity = entity; 19 | nmsEntity = (N) ((CraftEntity) entity).getHandle(); 20 | } 21 | 22 | @Override 23 | public E getBukkitEntity() { 24 | return entity; 25 | } 26 | 27 | protected N getNmsEntity() { 28 | return nmsEntity; 29 | } 30 | 31 | @Override 32 | public team.unstudio.udpl.nms.nbt.NBTTagCompound save(){ 33 | return NmsHelper.getNmsNBT().toCompound(getNmsEntity().e(new NBTTagCompound())); 34 | } 35 | 36 | @Override 37 | public void load(team.unstudio.udpl.nms.nbt.NBTTagCompound nbt){ 38 | getNmsEntity().f((NBTTagCompound)NmsHelper.getNmsNBT().toNmsNBT(nbt)); 39 | } 40 | 41 | @Override 42 | public Set getScoreboardTags() { 43 | return getNmsEntity().P(); 44 | } 45 | 46 | @Override 47 | public boolean addScoreboardTag(String tag) { 48 | return getScoreboardTags().add(tag); 49 | } 50 | 51 | @Override 52 | public boolean removeScoreboardTag(String tag) { 53 | return getScoreboardTags().remove(tag); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /udplib-nms1_11_R1/src/main/java/team/unstudio/udpl/core/nms/v1_11_R1/entity/NmsLivingEntity.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.core.nms.v1_11_R1.entity; 2 | 3 | import org.bukkit.entity.LivingEntity; 4 | 5 | import net.minecraft.server.v1_11_R1.EntityLiving; 6 | 7 | public class NmsLivingEntity extends NmsEntity implements team.unstudio.udpl.nms.entity.NmsLivingEntity{ 8 | 9 | public NmsLivingEntity(E entity) { 10 | super(entity); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /udplib-nms1_11_R1/src/main/java/team/unstudio/udpl/core/nms/v1_11_R1/entity/NmsPlayer.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.core.nms.v1_11_R1.entity; 2 | 3 | import java.util.Locale; 4 | 5 | import org.bukkit.craftbukkit.v1_11_R1.util.CraftChatMessage; 6 | import org.bukkit.entity.Player; 7 | 8 | import net.minecraft.server.v1_11_R1.EntityPlayer; 9 | import net.minecraft.server.v1_11_R1.IChatBaseComponent; 10 | import net.minecraft.server.v1_11_R1.Packet; 11 | import net.minecraft.server.v1_11_R1.PacketPlayOutChat; 12 | import net.minecraft.server.v1_11_R1.PacketPlayOutTitle; 13 | import team.unstudio.udpl.util.PlayerUtils; 14 | 15 | public class NmsPlayer extends NmsLivingEntity implements team.unstudio.udpl.nms.entity.NmsPlayer{ 16 | 17 | public NmsPlayer(Player player) { 18 | super(player); 19 | } 20 | 21 | @Override 22 | public Locale getLocale() { 23 | return Locale.forLanguageTag(PlayerUtils.normalizeLanguageTag(getNmsEntity().locale)); 24 | } 25 | 26 | @Override 27 | public void sendPacket(Object packet){ 28 | if(!(packet instanceof Packet)) 29 | throw new IllegalArgumentException("Packet isn't net.minecraft.server.Packet"); 30 | sendPacket((Packet) packet); 31 | } 32 | 33 | public

> void sendPacket(P packet) { 34 | getNmsEntity().playerConnection.sendPacket(packet); 35 | } 36 | 37 | @Override 38 | public void sendTitle(String title, String subtitle) { 39 | if (title != null) { 40 | PacketPlayOutTitle packetTitle = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.TITLE, 41 | CraftChatMessage.fromString(title)[0]); 42 | sendPacket(packetTitle); 43 | } 44 | 45 | if (subtitle != null) { 46 | PacketPlayOutTitle packetSubtitle = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.SUBTITLE, 47 | CraftChatMessage.fromString(subtitle)[0]); 48 | sendPacket(packetSubtitle); 49 | } 50 | } 51 | 52 | @Override 53 | public void resetTitle() { 54 | PacketPlayOutTitle packetReset = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.RESET, null); 55 | sendPacket(packetReset); 56 | } 57 | 58 | @Override 59 | public void sendActionBar(String message){ 60 | sendPacket(new PacketPlayOutChat(IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + message + "\"}"), (byte)2)); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /udplib-nms1_11_R1/src/main/java/team/unstudio/udpl/core/nms/v1_11_R1/entity/fake/FakeEntity.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.core.nms.v1_11_R1.entity.fake; 2 | 3 | import java.util.Collections; 4 | import java.util.Set; 5 | import java.util.UUID; 6 | 7 | import org.bukkit.entity.Player; 8 | 9 | import com.google.common.collect.Sets; 10 | 11 | import team.unstudio.udpl.util.reflect.ReflectionUtils; 12 | 13 | public abstract class FakeEntity { 14 | 15 | private static int nextEntityId = Integer.MAX_VALUE; 16 | 17 | private int entityId; 18 | private UUID uuid; 19 | 20 | private final Set observers; 21 | private final Set unmodifiableOvservers; 22 | 23 | public FakeEntity() { 24 | observers = Sets.newHashSet(); 25 | unmodifiableOvservers = Collections.unmodifiableSet(observers); 26 | 27 | entityId = getNewEntityId(); 28 | uuid = UUID.randomUUID(); 29 | } 30 | 31 | private int getNewEntityId(){ 32 | try { 33 | int entityId = (int) ReflectionUtils.getValue(null, ReflectionUtils.PackageType.MINECRAFT_SERVER.getClass("Entity"),true, "entityCount"); 34 | ReflectionUtils.setValue(null, ReflectionUtils.PackageType.MINECRAFT_SERVER.getClass("Entity"),true, "entityCount", entityId-1); 35 | return entityId; 36 | } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException 37 | | ClassNotFoundException e) { 38 | return nextEntityId--; 39 | } 40 | } 41 | 42 | public int getEntityId() { 43 | return entityId; 44 | } 45 | 46 | public void setEntityId(int entityId) { 47 | this.entityId = entityId; 48 | } 49 | 50 | public UUID getUuid() { 51 | return uuid; 52 | } 53 | 54 | public void setUuid(UUID uuid) { 55 | this.uuid = uuid; 56 | } 57 | 58 | public Set getObservers() { 59 | return unmodifiableOvservers; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /udplib-nms1_11_R1/src/main/java/team/unstudio/udpl/core/nms/v1_11_R1/entity/fake/FakeItem.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.core.nms.v1_11_R1.entity.fake; 2 | 3 | import org.bukkit.inventory.ItemStack; 4 | 5 | public class FakeItem extends FakeEntity{ 6 | 7 | private ItemStack itemStack; 8 | 9 | public FakeItem(ItemStack itemStack) { 10 | this.setItemStack(itemStack); 11 | } 12 | 13 | public ItemStack getItemStack() { 14 | return itemStack; 15 | } 16 | 17 | public void setItemStack(ItemStack itemStack) { 18 | this.itemStack = itemStack; 19 | } 20 | 21 | 22 | } 23 | -------------------------------------------------------------------------------- /udplib-nms1_11_R1/src/main/java/team/unstudio/udpl/core/nms/v1_11_R1/inventory/NmsItemStack.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.core.nms.v1_11_R1.inventory; 2 | 3 | import org.bukkit.craftbukkit.v1_11_R1.inventory.CraftItemStack; 4 | import org.bukkit.inventory.ItemStack; 5 | 6 | import team.unstudio.udpl.nms.NmsHelper; 7 | import team.unstudio.udpl.nms.nbt.NBTTagCompound; 8 | 9 | public class NmsItemStack implements team.unstudio.udpl.nms.inventory.NmsItemStack{ 10 | 11 | private final net.minecraft.server.v1_11_R1.ItemStack itemStack; 12 | 13 | public NmsItemStack(ItemStack itemStack) { 14 | this.itemStack = CraftItemStack.asNMSCopy(itemStack); 15 | } 16 | 17 | @Override 18 | public ItemStack getBukkitItemStack() { 19 | return CraftItemStack.asBukkitCopy(itemStack); 20 | } 21 | 22 | @Override 23 | public NBTTagCompound getTag() { 24 | return NmsHelper.getNmsNBT().toCompound(itemStack.getTag()); 25 | } 26 | 27 | @Override 28 | public void setTag(NBTTagCompound nbt) { 29 | itemStack.setTag((net.minecraft.server.v1_11_R1.NBTTagCompound)NmsHelper.getNmsNBT().toNmsNBT(nbt)); 30 | } 31 | 32 | @Override 33 | public boolean hasTag() { 34 | return itemStack.hasTag(); 35 | } 36 | 37 | @Override 38 | public void load(NBTTagCompound nbt){ 39 | itemStack.load((net.minecraft.server.v1_11_R1.NBTTagCompound)NmsHelper.getNmsNBT().toNmsNBT(nbt)); 40 | } 41 | 42 | @Override 43 | public NBTTagCompound save() { 44 | return NmsHelper.getNmsNBT().toCompound(itemStack.save(new net.minecraft.server.v1_11_R1.NBTTagCompound())); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /udplib-nms1_11_R1/src/main/java/team/unstudio/udpl/core/nms/v1_11_R1/network/NmsNetwork.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.core.nms.v1_11_R1.network; 2 | 3 | import java.util.Iterator; 4 | import java.util.List; 5 | 6 | import org.bukkit.craftbukkit.v1_11_R1.entity.CraftPlayer; 7 | import org.bukkit.entity.Player; 8 | 9 | import io.netty.buffer.ByteBuf; 10 | import io.netty.channel.Channel; 11 | import io.netty.channel.ChannelHandlerContext; 12 | import io.netty.channel.ChannelPipeline; 13 | import io.netty.handler.codec.ByteToMessageDecoder; 14 | import io.netty.handler.codec.MessageToByteEncoder; 15 | import net.minecraft.server.v1_11_R1.EntityPlayer; 16 | import net.minecraft.server.v1_11_R1.EnumProtocolDirection; 17 | import net.minecraft.server.v1_11_R1.PacketDecoder; 18 | 19 | public class NmsNetwork implements team.unstudio.udpl.nms.network.NmsNetwork{ 20 | 21 | private static final String UDPL_DECODER = "udplDecoder"; 22 | private static final String UDPL_ENCODER = "udplEncoder"; 23 | 24 | @Override 25 | public void inject(Player player) { 26 | EntityPlayer nmsPlayer = ((CraftPlayer) player).getHandle(); 27 | Channel channel = nmsPlayer.playerConnection.networkManager.channel; 28 | ChannelPipeline pipeline = channel.pipeline(); 29 | if (pipeline.get(UDPL_DECODER) != null) 30 | return; 31 | 32 | ByteToMessageDecoder decoder = (ByteToMessageDecoder) pipeline.get("decoder"); 33 | MessageToByteEncoder encoder = (MessageToByteEncoder) pipeline.get("encoder"); 34 | 35 | pipeline.addBefore("decoder", UDPL_DECODER, new ByteToMessageDecoder() { 36 | 37 | @Override 38 | protected void decode(ChannelHandlerContext context, ByteBuf buffer, List packets) throws Exception { 39 | 40 | Iterator iterator = packets.iterator(); 41 | while (iterator.hasNext()) { 42 | Object packet = iterator.next(); 43 | // PlayerSendPacket event = new PlayerSendPacket(player, packet); 44 | // EventManager.call(event); 45 | // if (event.isCancelled()) iterator.remove(); 46 | } 47 | } 48 | 49 | }); 50 | 51 | pipeline.addAfter("encoder", UDPL_ENCODER, new MessageToByteEncoder() { 52 | 53 | @Override 54 | protected void encode(ChannelHandlerContext context, Object packet, ByteBuf buffer) throws Exception { 55 | if (packet == null) 56 | return; 57 | 58 | // PlayerReceivePacket event = new PlayerReceivePacket(NetworkInjector.this.player, packet); 59 | // EventManager.call(event); 60 | // if (!event.isCancelled()) NetworkInjector.methodEncode.invoke(NetworkInjector.this.objectEncoder, context, packet, buffer); 61 | } 62 | 63 | }); 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /udplib-nms1_11_R1/src/main/java/team/unstudio/udpl/core/nms/v1_11_R1/tileentity/NmsTileEntity.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.core.nms.v1_11_R1.tileentity; 2 | 3 | import org.bukkit.block.BlockState; 4 | import org.bukkit.craftbukkit.v1_11_R1.block.CraftBlockState; 5 | import net.minecraft.server.v1_11_R1.TileEntity; 6 | import team.unstudio.udpl.nms.NmsHelper; 7 | import team.unstudio.udpl.nms.nbt.NBTTagCompound; 8 | 9 | public class NmsTileEntity implements team.unstudio.udpl.nms.tileentity.NmsTileEntity{ 10 | 11 | private final T tileEntity; 12 | 13 | @SuppressWarnings("unchecked") 14 | public NmsTileEntity(BlockState blockState) { 15 | this.tileEntity = (T) ((CraftBlockState)blockState).getTileEntity(); 16 | } 17 | 18 | protected T getTileEntity(){ 19 | return tileEntity; 20 | } 21 | 22 | @SuppressWarnings("unchecked") 23 | @Override 24 | public B getBukkitBlockState() { 25 | return (B) CraftBlockState.getBlockState(tileEntity.getWorld(), tileEntity.getPosition().getX(), tileEntity.getPosition().getY(), tileEntity.getPosition().getZ()); 26 | } 27 | 28 | @Override 29 | public NBTTagCompound save(){ 30 | return NmsHelper.getNmsNBT().toCompound(tileEntity.save(new net.minecraft.server.v1_11_R1.NBTTagCompound())); 31 | } 32 | 33 | @Override 34 | public void load(NBTTagCompound nbt){ 35 | tileEntity.a((net.minecraft.server.v1_11_R1.NBTTagCompound)NmsHelper.getNmsNBT().toNmsNBT(nbt)); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /udplib-test/.gitignore: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | !.gitignore 4 | !src/ 5 | !pom.xml -------------------------------------------------------------------------------- /udplib-test/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | team.unstudio 8 | udplib 9 | 1.3.3 10 | 11 | udplib-test 12 | UDPLib-test 13 | 14 | 15 | team.unstudio 16 | udplib-core 17 | 18 | 19 | 20 | 21 | 22 | org.apache.maven.plugins 23 | maven-shade-plugin 24 | 1.4 25 | 26 | 27 | package 28 | 29 | shade 30 | 31 | 32 | false 33 | false 34 | true 35 | 36 | 37 | team.unstudio:udplib-nms1_11_R1 38 | team.unstudio:udplib-common 39 | team.unstudio:udplib-core 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /udplib-test/src/main/java/team/unstudio/udpl/core/test/TestLoader.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.core.test; 2 | 3 | import org.bukkit.configuration.serialization.ConfigurationSerialization; 4 | import team.unstudio.udpl.area.AreaManager; 5 | import team.unstudio.udpl.command.anno.AnnoCommandManager; 6 | import team.unstudio.udpl.core.UDPLib; 7 | 8 | public class TestLoader { 9 | 10 | public static AreaManager areaManager; 11 | 12 | public static void onLoad(){ 13 | ConfigurationSerialization.registerClass(TestSerialization.class); 14 | UDPLib.getLog().info("Loaded test."); 15 | } 16 | 17 | public static void onEnable(){ 18 | areaManager = new AreaManager(UDPLib.getInstance()); 19 | areaManager.addPlayerEnterAreaCallback((player,area)->player.sendMessage("Entered Area.")); 20 | areaManager.addPlayerLeaveAreaCallback((player,area)->player.sendMessage("Leaved Area.")); 21 | areaManager.setAutoSavePeriod(20*60); 22 | areaManager.setAutoSave(true); 23 | areaManager.setAutoBackupPeriod(20*120); 24 | areaManager.setAutoBackup(true); 25 | 26 | new AnnoCommandManager("test", UDPLib.getInstance()).addHandler(new TestCommand()).unsafeRegisterCommand(); 27 | UDPLib.getLog().info("Enabled test."); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /udplib-test/src/main/java/team/unstudio/udpl/core/test/TestSerialization.java: -------------------------------------------------------------------------------- 1 | package team.unstudio.udpl.core.test; 2 | 3 | import org.bukkit.configuration.serialization.ConfigurationSerializable; 4 | import team.unstudio.udpl.config.ConfigItem; 5 | import team.unstudio.udpl.config.SerializationHelper; 6 | 7 | import java.util.Map; 8 | 9 | public class TestSerialization implements ConfigurationSerializable{ 10 | 11 | @ConfigItem("item") 12 | private int item; 13 | 14 | public TestSerialization(){} 15 | 16 | public TestSerialization(int item){ 17 | this.item = item; 18 | } 19 | 20 | public void setItem(int item){ 21 | this.item = item; 22 | } 23 | 24 | public int getItem(){ 25 | return item; 26 | } 27 | 28 | @Override 29 | public Map serialize() { 30 | return SerializationHelper.serialize(this); 31 | } 32 | 33 | public static TestSerialization deserialize(Map data){ 34 | return SerializationHelper.deserialize(new TestSerialization(), data); 35 | } 36 | 37 | } 38 | --------------------------------------------------------------------------------