Compare commits

..

170 Commits
4.3.1 ... 5.7.0

Author SHA1 Message Date
Auxilor
726f4a44c4 Re-Added PluginDependent to HandledCommand 2021-07-05 17:53:28 +02:00
Auxilor
eafae209a6 Fixed bug with Handle 2021-07-05 17:43:18 +02:00
Auxilor
04c450b46a Improved subcommand system 2021-07-05 17:37:05 +02:00
Auxilor
d4e1f58f2a Updated to 5.7.0 2021-07-05 17:24:18 +02:00
Auxilor
b0806b934b Began introduction of new command system 2021-07-05 15:14:54 +02:00
Auxilor
a21ecfbdde Refactoring to use PluginDependent<T extends EcoPlugin> and updated CombatLogX 2021-07-05 11:41:26 +02:00
Auxilor
f3a6861bc6 Merge remote-tracking branch 'origin/master' 2021-07-05 11:22:08 +02:00
Auxilor
eaa295e6a3 Merge pull request #8 from SirBlobman/main 2021-07-05 11:05:33 +02:00
SirBlobman
399387eca1 Add comments. 2021-07-05 02:17:20 -04:00
SirBlobman
272f551aae Fix gradle dependencies and remove unnecessary local jar files. 2021-07-05 02:14:30 -04:00
SirBlobman
d8c5fc0959 Update plugin class to use correct CombatLogX hook based on version. 2021-07-05 02:13:49 -04:00
SirBlobman
d1ca106d01 Create CombatLogX V11 hook class. 2021-07-05 02:13:31 -04:00
SirBlobman
99f5174e28 Update CombatLogX V10 hook class. 2021-07-05 02:13:10 -04:00
Auxilor
d9f4aee384 Updated to 5.6.1 and added type parameters to PluginDependent 2021-07-04 19:00:14 +02:00
Auxilor
c2aae8c2eb Added direct download link to eco version checker 2021-07-04 00:45:37 +02:00
Auxilor
52061b7b51 Reverted proxy changes 2021-07-01 22:29:53 +01:00
Auxilor
762969c172 Fixed error with WildTP making their own Player class 2021-07-01 22:11:40 +01:00
Auxilor
62d5cf885f Fixed internals load order 2021-07-01 22:10:00 +01:00
Auxilor
1e70a9fdea Added eco version checking 2021-06-30 07:47:49 +01:00
Auxilor
ec8a65b4f8 Removed redundant suppression 2021-06-27 15:59:55 +01:00
Auxilor
a163219372 Chnaged ExtensionMetadata to record 2021-06-27 15:55:12 +01:00
Auxilor
4d6e097f8f Minor changes 2021-06-27 15:50:10 +01:00
Auxilor
497adbe7b1 Added extension unloading 2021-06-27 15:30:05 +01:00
Auxilor
78907412b2 Updated to 5.6.0 2021-06-27 14:59:14 +01:00
Auxilor
d6bec5d88b Added EcoPlugin#getProxy 2021-06-27 14:58:57 +01:00
Auxilor
aab1f31ca0 More changes to EcoPlugin 2021-06-27 14:39:29 +01:00
Auxilor
5ea586eaae Added more constructors and options to EcoPlugin 2021-06-27 14:11:47 +01:00
Auxilor
2ffc293211 Added http encoding to paste 2021-06-27 13:59:45 +01:00
Auxilor
88bedef420 Encoded strings paste 2021-06-25 11:47:24 +01:00
Auxilor
dac5ffce9a Fixed JsonConfigWrapper#clone returning internal JsonConfigWrapper rather than JSONConfig 2021-06-25 09:15:45 +01:00
Auxilor
d641adadea Fixed broken slot javadoc 2021-06-22 15:36:07 +01:00
Auxilor
46269354c6 'Cleaned up' ArrowDataListener 2021-06-22 15:34:27 +01:00
Auxilor
2d93465d1d Added Paste#getFromHastebin 2021-06-22 15:31:00 +01:00
Auxilor
484d4dde75 Renamed Internals class 2021-06-22 15:28:08 +01:00
Auxilor
5e9a408704 Refactored configs 2021-06-22 15:24:32 +01:00
Auxilor
f1b113f435 Extracted ConfigHandler interface 2021-06-22 15:23:35 +01:00
Auxilor
5d553d725c Updated to 5.5.1 2021-06-20 16:42:25 +01:00
Auxilor
a3be846083 Removed gson implementation 2021-06-20 16:42:15 +01:00
Auxilor
54e0b3f482 Merge remote-tracking branch 'origin/master'
# Conflicts:
#	eco-api/src/main/java/com/willfp/eco/internal/arrows/ArrowDataListener.java
#	eco-api/src/main/java/com/willfp/eco/internal/items/AbstractItemStackBuilder.java
#	eco-api/src/main/java/com/willfp/eco/util/TeamUtils.java
2021-06-19 11:38:34 +01:00
Auxilor
93794fe454 Reverted 2021-06-18 11:42:49 +01:00
Auxilor
7f4a0c800e Fixed bug with empty JSON string lists 2021-06-18 09:02:17 +01:00
Auxilor
853864f6f0 Added Paste 2021-06-17 22:23:17 +01:00
Auxilor
0cb6e8f669 Added toPlaintext 2021-06-17 17:45:15 +01:00
Auxilor
d30f657eec Fixed list translation modifying by reference 2021-06-17 13:43:30 +01:00
Auxilor
d60ecdd340 Fixed SkullBuilder 2021-06-17 13:37:47 +01:00
Auxilor
07310df68a Added support for plugin parameters on update methods 2021-06-17 12:57:40 +01:00
Auxilor
5c91aa220a Added LeatherArmorBuilder 2021-06-17 11:33:22 +01:00
Auxilor
756a76057a Reduced generic abuse 2021-06-17 11:28:24 +01:00
Auxilor
b6f27ee232 Refactoring builders to be easier to use 2021-06-17 11:25:54 +01:00
Auxilor
74ca2e82ef Added suppliers to itemstackbuilder 2021-06-17 11:14:47 +01:00
Auxilor
4039439fda Added AbstractItemStackBuilder#setCustomModelData 2021-06-17 11:04:49 +01:00
Auxilor
7dac671690 Added Recipes#createAndRegisterRecipe 2021-06-17 10:56:15 +01:00
Auxilor
411d517a9a Added persistent meta writing to ItemStackBuilder 2021-06-17 10:52:36 +01:00
Auxilor
0d84141116 Updated configs to translate all strings in lists automatically 2021-06-17 10:37:37 +01:00
Auxilor
6bfd5bd153 Added TranslateList and JSON parity 2021-06-17 10:36:38 +01:00
Auxilor
b7d421e1a8 Fixed JSON int bug 2021-06-17 10:28:46 +01:00
Auxilor
2e9d811d3f Fixed deprecated reference 2021-06-17 09:41:53 +01:00
Auxilor
672b295917 Fixed Prerequisite typo 2021-06-17 09:19:42 +01:00
Auxilor
60a83478e8 J16 work 2021-06-17 08:38:18 +01:00
Auxilor
c880a476d4 Continued adding stack support to recipes 2021-06-16 22:17:23 +01:00
Auxilor
692305d595 Continued adding stack support to recipes 2021-06-16 16:54:33 +01:00
Auxilor
9d4cc2961c Fixed NPE 2021-06-16 16:08:45 +01:00
Auxilor
358b389875 Fixed NPE 2021-06-16 16:07:22 +01:00
Auxilor
7fa25c2500 Naming update 2021-06-16 16:04:54 +01:00
Auxilor
91c58c4a53 Added stack support to crafting 2021-06-16 16:03:07 +01:00
Auxilor
4ccee91c64 Added PlayerJumpEvent 2021-06-16 15:45:10 +01:00
Auxilor
eef87342a1 Switched to Java 15 pattern variables 2021-06-16 15:35:15 +01:00
Auxilor
efc70ea7a8 GUI Javadoc 2021-06-16 15:21:48 +01:00
Auxilor
de38299264 Removed test 2021-06-16 15:18:22 +01:00
Auxilor
bc94f43299 Data null safetyx 2021-06-16 13:30:36 +01:00
Auxilor
ed705cc577 Added 1.17 materials to TeamUtils 2021-06-16 11:30:23 +01:00
Auxilor
93410490c5 Javadoc 2021-06-16 11:26:43 +01:00
Auxilor
33914ac284 Added COPPER_ORE to TeamUtils 2021-06-15 21:11:06 +01:00
Auxilor
2acf2ee687 Added setPersistentKEy 2021-06-15 21:08:02 +01:00
Auxilor
0470552168 Added ItemStack builders 2021-06-15 21:04:55 +01:00
Auxilor
3e724eea18 Updated GUI system 2021-06-15 20:44:57 +01:00
Auxilor
33ba5c9d31 Reworked data to just have a call to retrieve a JSON config that can be modified 2021-06-15 15:47:25 +01:00
Auxilor
94ab094952 Cleaning up config 2021-06-15 15:25:45 +01:00
Auxilor
58f5d3f352 Added getKeys(true) 2021-06-15 14:07:55 +01:00
Auxilor
912872e791 Updated config backend 2021-06-15 12:39:10 +01:00
Auxilor
7a65e6e821 Added getSubsections to JSON Configs 2021-06-15 11:29:42 +01:00
Auxilor
3f446f6072 Added JSON support 2021-06-15 11:02:21 +01:00
Auxilor
50f57abd6c Added recursive JSON Get/Set and tests 2021-06-15 10:59:55 +01:00
Auxilor
2c5eae6c6c Removed unused imports 2021-06-15 09:35:12 +01:00
Auxilor
1e3e54b8c5 Added preliminary JSON support 2021-06-14 16:56:10 +01:00
Auxilor
0ce9119a94 Added gson as a dependency 2021-06-14 14:53:16 +01:00
Auxilor
bf76ba9f5a Fixed publication issues 2021-06-13 10:46:57 +01:00
Auxilor
8a065bf7ca Updated to 5.4.1 2021-06-13 10:26:33 +01:00
Auxilor
5f045d02a6 Fixed publishing errors 2021-06-11 12:11:19 +01:00
Auxilor
f07ef3045b Fixed gradle issues 2021-06-11 12:04:07 +01:00
Auxilor
007a579f5a Updated to 5.4.0 2021-06-11 11:37:09 +01:00
Auxilor
9b19cd412a Updated to 1.17 and Java 16 2021-06-11 11:36:58 +01:00
Auxilor
08b5cc1612 Added more null checks to fix incompatibility with paper/adventure 2021-05-18 15:41:45 +01:00
Auxilor
47aa61c7b3 Updated to 5.3.7 2021-05-18 15:34:02 +01:00
Auxilor
ef1ee84358 Added checks for null components due to problem with adventure 2021-05-18 15:33:47 +01:00
Auxilor
49a36a4e81 Updated to 5.3.6 2021-05-06 08:47:51 +01:00
Auxilor
bf76dec28e Added emerald ore in TeamUtils 2021-05-06 08:47:41 +01:00
Auxilor
a0f51d79e8 Updated to 5.3.5 2021-04-26 21:24:45 +01:00
Auxilor
9be516e511 Added villager-display-fix to force remove all hideflags 2021-04-26 21:24:28 +01:00
Auxilor
a130935c62 Fixed Villager Trades for the last time 2021-04-25 15:54:50 +01:00
Auxilor
4359bd17ae Updated to 5.3.4 2021-04-25 15:45:26 +01:00
Auxilor
07726959e9 Fixed MerchantRecipe again 2021-04-25 15:45:16 +01:00
Auxilor
13c8187b3b Updated to 5.3.3 2021-04-25 15:18:51 +01:00
Auxilor
be1267ef0c Fixed config default 2021-04-25 15:18:40 +01:00
Auxilor
e61e9bc0a8 Added disable villager display option 2021-04-24 17:05:07 +01:00
Auxilor
ec801cd776 Updated to 5.3.2 2021-04-24 17:02:23 +01:00
Auxilor
a5b5bc6b46 Fixed ChatComponent 2021-04-24 17:01:53 +01:00
Auxilor
f5efb50d71 Updated to 5.3.1 2021-04-23 21:17:13 +01:00
Auxilor
d65c04aaa7 Hopefully fixed Villager Trades again 2021-04-23 21:16:46 +01:00
Auxilor
aa69d2a1a9 Fixed deprecation still being used 2021-04-20 21:41:04 +01:00
Auxilor
685cd5f998 Deprecated finalization system 2021-04-20 21:39:25 +01:00
Auxilor
bae4b567c8 Updated to 5.3.0 2021-04-20 21:31:05 +01:00
Auxilor
0eb3315d61 Updated to 5.2.2 2021-04-20 21:29:28 +01:00
Auxilor
0a42320b78 Fixed villager trade display 2021-04-20 21:29:19 +01:00
Auxilor
6ce0de8db7 Merge remote-tracking branch 'origin/master' 2021-04-20 21:28:04 +01:00
Auxilor
345d4cd1b5 Reworked villager trade display 2021-04-20 20:21:32 +01:00
Auxilor
950c092025 Added EcoSkills to loadbefore 2021-04-17 10:25:38 +01:00
Auxilor
0c6bb8c1b7 Updated to 5.2.1 2021-04-17 10:24:39 +01:00
Auxilor
0f9cb7db7a Items in menus now translate placeholder lore with respect to a player 2021-04-17 10:24:27 +01:00
Auxilor
7d4262e0ef Finished GUIs 2021-04-16 15:32:42 +01:00
Auxilor
e543be7a13 Updated to 5.2.0 2021-04-16 14:51:47 +01:00
Auxilor
3d7027bf47 Added initial GUI system 2021-04-16 14:51:30 +01:00
Auxilor
632b42ad65 Updated to 5.1.1 2021-04-14 16:02:00 +01:00
Auxilor
bcd79e3886 Added vulcan support 2021-04-14 16:01:51 +01:00
Auxilor
8fbcf485b3 Renamed PlayerData to Data 2021-04-08 15:03:17 +01:00
Auxilor
6a64be2e25 Removed debug code 2021-04-08 15:01:57 +01:00
Auxilor
3f9f3991d8 Fixed cache on set in configs 2021-04-08 15:00:31 +01:00
Auxilor
54a8d942fa Fixed getSubsectionOrNull 2021-04-08 14:36:07 +01:00
Auxilor
6aa14be577 Updated to 5.1.0 2021-04-08 14:28:53 +01:00
Auxilor
d6db7673d8 Added data.yml 2021-04-08 14:28:19 +01:00
Auxilor
d002073124 Updated to 5.0.2 2021-04-06 18:03:03 +01:00
Auxilor
4bc98cae81 Fixed getVein 2021-04-06 18:02:50 +01:00
Auxilor
2696baf1d6 Updated to 5.0.1 2021-04-05 17:46:30 +01:00
Auxilor
3c3cc36403 Fixed fast sin and cos 2021-04-05 17:46:18 +01:00
Auxilor
fd87683b6a Fixed display 2021-04-04 16:48:33 +01:00
Auxilor
83da1e7b95 Fixed ShapedCraftingRecipe 2021-04-04 16:34:08 +01:00
Auxilor
9f9515675a Removed ULands as softdepend 2021-04-04 16:27:43 +01:00
Auxilor
1aa084cd90 Fixed main class 2021-04-04 16:27:24 +01:00
Auxilor
525ec0260f Renamed CustomItems to Items 2021-04-04 15:17:02 +01:00
Auxilor
ac15ffee6c Moved ConfigUpdater into core 2021-04-04 15:09:53 +01:00
Auxilor
83d68c5046 Fixed RunnableTask 2021-04-04 15:03:26 +01:00
Auxilor
7d1186811f Cleaned up util initialization 2021-04-04 14:53:40 +01:00
Auxilor
88bc01e5df Refactored shaped recipes 2021-04-04 14:45:17 +01:00
Auxilor
78d2459c7a Changed dependencies 2021-04-04 13:58:40 +01:00
Auxilor
21f4bd79eb Changed TeamUtils teams 2021-04-04 13:50:17 +01:00
Auxilor
64147c6261 Refactoring 2021-04-04 13:45:13 +01:00
Auxilor
c67c486f2f Registered custom logger 2021-04-04 13:31:07 +01:00
Auxilor
ae419bacb3 Refactored Config and Lang into ConfigYml and LangYml 2021-04-04 13:30:27 +01:00
Auxilor
17b0214f2f Added <#ffffff> hex pattern 2021-04-04 13:23:18 +01:00
Auxilor
963f706018 Added more gradient and hex patterns 2021-04-04 13:22:05 +01:00
Auxilor
74398cda62 Removed hardcoded author in PAPI integration 2021-04-04 13:15:23 +01:00
Auxilor
8321af5af2 Renamed RecipePart into CustomItem system 2021-04-03 20:13:34 +01:00
Auxilor
2524d86462 Removed unneeded fully qualified name 2021-04-03 19:57:43 +01:00
Auxilor
e050bf83df Removed 1.15 support 2021-04-03 19:57:27 +01:00
Auxilor
91c936a06f ArrowDataListener now sends the whole ItemStack 2021-04-03 19:53:48 +01:00
Auxilor
93dfd44410 Removed broken ULands integration 2021-04-03 16:37:02 +01:00
Auxilor
304d0cdebf Updated spigot api to 1.16.5 2021-04-03 16:34:49 +01:00
Auxilor
108d878939 Refactored internal/util into internal/core/util 2021-04-03 16:34:19 +01:00
Auxilor
e10e327c56 Updated v1_16_R3 to spigot 1.16.5 2021-04-03 15:28:27 +01:00
Auxilor
cabea9fba9 Added fast sin and cos functions 2021-04-03 15:22:00 +01:00
Auxilor
f9159cf245 Added setters to config 2021-04-03 14:26:27 +01:00
Auxilor
2db011ae10 Refactoring and removed serialization system 2021-04-03 14:19:11 +01:00
Auxilor
f96716966d Removed deprecated DisplayModule method 2021-04-03 14:01:47 +01:00
Auxilor
7515efbde9 Added CraftItemStack check to FastItemStackHandler 2021-04-03 13:57:28 +01:00
Auxilor
4ebd0d79d5 Updated to 5.0.0 2021-04-03 13:26:34 +01:00
Auxilor
0c3b5d3c30 Began implementing FastItemStack 2021-04-03 12:32:39 +01:00
Auxilor
e0b06dedff Continued refactor 2021-04-03 11:01:47 +01:00
Auxilor
187ac8163d Merge branch 'master' into develop
# Conflicts:
#	eco-api/src/main/java/com/willfp/eco/internal/config/AbstractConfig.java
#	eco-api/src/main/java/com/willfp/eco/internal/config/ConfigSection.java
#	eco-api/src/main/java/com/willfp/eco/internal/config/ConfigWrapper.java
#	eco-api/src/main/java/com/willfp/eco/util/SerializationUtils.java
#	eco-api/src/main/java/com/willfp/eco/util/config/Config.java
#	eco-api/src/main/java/com/willfp/eco/util/config/StaticOptionalConfig.java
#	eco-api/src/main/java/com/willfp/eco/util/serialization/Deserializer.java
#	eco-api/src/main/java/com/willfp/eco/util/serialization/EcoSerializable.java
#	eco-api/src/main/java/com/willfp/eco/util/serialization/NoRegisteredDeserializerException.java
2021-04-03 10:49:02 +01:00
Auxilor
ac2078957d Began refactor 2021-04-03 10:48:31 +01:00
Auxilor
352d495301 Renamed eco-util to eco-api 2021-04-03 10:22:01 +01:00
228 changed files with 5427 additions and 2425 deletions

2
.gitignore vendored
View File

@@ -14,7 +14,7 @@ bin/
# Gradle
.gradle
**/build/
!eco-util/src/**/build/
!eco-api/src/**/build/
.gradletasknamecache
!gradle-wrapper.jar
gradle-app.setting

View File

@@ -1,12 +1,12 @@
plugins {
id 'java-library'
id 'com.github.johnrengelman.shadow' version '5.2.0'
id 'com.github.johnrengelman.shadow' version '7.0.0'
id 'maven-publish'
id 'java'
}
dependencies {
implementation project(":eco-util")
implementation project(":eco-api")
implementation project(":eco-core").getSubprojects()
}
@@ -18,7 +18,6 @@ allprojects {
repositories {
mavenCentral()
jcenter()
mavenLocal()
maven { url 'https://jitpack.io' }
@@ -51,14 +50,13 @@ allprojects {
}
dependencies {
compileOnly 'org.spigotmc:spigot-api:1.16.4-R0.1-SNAPSHOT'
compileOnly 'org.jetbrains:annotations:19.0.0'
// Lombok
compileOnly 'org.projectlombok:lombok:1.18.16'
annotationProcessor 'org.projectlombok:lombok:1.18.16'
testCompileOnly 'org.projectlombok:lombok:1.18.16'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.16'
compileOnly 'org.projectlombok:lombok:1.18.20'
annotationProcessor 'org.projectlombok:lombok:1.18.20'
testCompileOnly 'org.projectlombok:lombok:1.18.20'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.20'
}
tasks.withType(JavaCompile) {
@@ -76,8 +74,8 @@ allprojects {
}
shadowJar {
relocate('org.bstats.bukkit', 'com.willfp.eco.util.shaded.bstats')
relocate('org.apache.maven', 'com.willfp.eco.util.shaded.maven')
relocate('org.bstats.bukkit', 'com.willfp.eco.shaded.bstats')
relocate('org.apache.maven', 'com.willfp.eco.shaded.maven')
}
jar {
@@ -88,6 +86,11 @@ allprojects {
onlyIf { !sourceSets.main.allSource.files.isEmpty() }
}
java {
sourceCompatibility = JavaVersion.VERSION_16
targetCompatibility = JavaVersion.VERSION_16
}
compileJava.options.encoding = 'UTF-8'
compileJava.dependsOn clean
@@ -96,5 +99,4 @@ allprojects {
group = 'com.willfp'
archivesBaseName = project.name
version = findProperty("version")
java.sourceCompatibility = JavaVersion.VERSION_1_8
version = findProperty("version")

View File

@@ -5,6 +5,12 @@
"http://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
<suppressions>
<!-- Internals don't need javadoc. -->
<suppress files="[\\/]internal[\\/]" checks="MissingJavadocMethod"/>
<suppress files="[\\/]internal[\\/]" checks="JavadocVariable"/>
<suppress files="[\\/]eco[\\/]spigot[\\/]" checks="MissingJavadocMethod"/>
<suppress files="[\\/]eco[\\/]spigot[\\/]" checks="JavadocVariable"/>
<!-- Modified version of library -->
<suppress files="ArmorEquipEvent.java" checks="JavadocVariable"/>
<suppress files="ArmorEquipEvent.java" checks="MissingJavadocMethod"/>

View File

@@ -1,11 +1,17 @@
plugins {
id 'com.github.johnrengelman.shadow'
}
group 'com.willfp'
version rootProject.version
dependencies {
compileOnly 'org.spigotmc:spigot:1.17-R0.1-SNAPSHOT'
compileOnly 'org.apache.maven:maven-artifact:3.0.3'
compileOnly 'org.bstats:bstats-bukkit:1.7'
compileOnly 'com.comphenix.protocol:ProtocolLib:4.6.0-SNAPSHOT'
compileOnly 'me.clip:placeholderapi:2.10.9'
compileOnly 'com.google.code.gson:gson:2.8.7'
}
compileJava.options.encoding = 'UTF-8'
@@ -17,7 +23,6 @@ publishing {
publications {
shadow(MavenPublication) {
from components.java
artifact shadowJar
artifactId 'eco'
}
}

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.protocollib;
package com.willfp.eco.core;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
@@ -6,7 +6,6 @@ import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.events.PacketEvent;
import com.willfp.eco.util.plugin.AbstractEcoPlugin;
import lombok.Getter;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
@@ -35,7 +34,7 @@ public abstract class AbstractPacketAdapter extends PacketAdapter {
* @param priority The priority at which the adapter should be ran on packet send/receive.
* @param postLoad If the packet adapter should be registered after the server has loaded.
*/
protected AbstractPacketAdapter(@NotNull final AbstractEcoPlugin plugin,
protected AbstractPacketAdapter(@NotNull final EcoPlugin plugin,
@NotNull final PacketType type,
@NotNull final ListenerPriority priority,
final boolean postLoad) {
@@ -51,7 +50,7 @@ public abstract class AbstractPacketAdapter extends PacketAdapter {
* @param type The {@link PacketType} to listen for.
* @param postLoad If the packet adapter should be registered after the server has loaded.
*/
protected AbstractPacketAdapter(@NotNull final AbstractEcoPlugin plugin,
protected AbstractPacketAdapter(@NotNull final EcoPlugin plugin,
@NotNull final PacketType type,
final boolean postLoad) {
this(plugin, type, ListenerPriority.NORMAL, postLoad);
@@ -79,6 +78,32 @@ public abstract class AbstractPacketAdapter extends PacketAdapter {
// Empty rather than abstract as implementations don't need both
}
/**
* The code that should be executed once the packet has been received.
*
* @param packet The packet.
* @param player The player.
* @param event The event.
*/
public void onReceive(@NotNull final PacketContainer packet,
@NotNull final Player player,
@NotNull final PacketEvent event) {
// Empty rather than abstract as implementations don't need both
}
/**
* THe code that should be executed once the packet has been sent.
*
* @param packet The packet.
* @param player The player.
* @param event The event.
*/
public void onSend(@NotNull final PacketContainer packet,
@NotNull final Player player,
@NotNull final PacketEvent event) {
// Empty rather than abstract as implementations don't need both
}
/**
* Boilerplate to assert that the packet is of the specified type.
*
@@ -95,6 +120,7 @@ public abstract class AbstractPacketAdapter extends PacketAdapter {
}
onReceive(event.getPacket(), event.getPlayer());
onReceive(event.getPacket(), event.getPlayer(), event);
}
/**
@@ -113,6 +139,12 @@ public abstract class AbstractPacketAdapter extends PacketAdapter {
}
onSend(event.getPacket(), event.getPlayer());
onSend(event.getPacket(), event.getPlayer(), event);
}
@Override
public final EcoPlugin getPlugin() {
return (EcoPlugin) super.getPlugin();
}
/**

View File

@@ -0,0 +1,690 @@
package com.willfp.eco.core;
import com.willfp.eco.core.command.AbstractCommand;
import com.willfp.eco.core.command.impl.PluginCommand;
import com.willfp.eco.core.config.ConfigHandler;
import com.willfp.eco.core.config.base.ConfigYml;
import com.willfp.eco.core.config.base.LangYml;
import com.willfp.eco.core.display.Display;
import com.willfp.eco.core.display.DisplayModule;
import com.willfp.eco.core.events.EventManager;
import com.willfp.eco.core.extensions.ExtensionLoader;
import com.willfp.eco.core.factory.MetadataValueFactory;
import com.willfp.eco.core.factory.NamespacedKeyFactory;
import com.willfp.eco.core.factory.RunnableFactory;
import com.willfp.eco.core.integrations.IntegrationLoader;
import com.willfp.eco.core.integrations.placeholder.PlaceholderManager;
import com.willfp.eco.core.scheduling.Scheduler;
import com.willfp.eco.internal.Internals;
import com.willfp.eco.internal.UpdateChecker;
import com.willfp.eco.internal.arrows.ArrowDataListener;
import com.willfp.eco.internal.config.updating.EcoConfigHandler;
import com.willfp.eco.internal.events.EcoEventManager;
import com.willfp.eco.internal.extensions.EcoExtensionLoader;
import com.willfp.eco.internal.factory.EcoMetadataValueFactory;
import com.willfp.eco.internal.factory.EcoNamespacedKeyFactory;
import com.willfp.eco.internal.factory.EcoRunnableFactory;
import com.willfp.eco.internal.integrations.PlaceholderIntegrationPAPI;
import com.willfp.eco.internal.logging.EcoLogger;
import com.willfp.eco.internal.scheduling.EcoScheduler;
import lombok.Getter;
import org.apache.commons.lang.Validate;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.bstats.bukkit.Metrics;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import java.util.stream.Collectors;
@SuppressWarnings({"deprecation", "DeprecatedIsStillUsed"})
public abstract class EcoPlugin extends JavaPlugin {
/**
* Loaded eco plugins.
*/
public static final List<String> LOADED_ECO_PLUGINS = new ArrayList<>();
/**
* The name of the plugin.
*
* @deprecated Pointless, use getName instead.
*/
@Getter
@Deprecated
private final String pluginName;
/**
* The spigot resource ID of the plugin.
*/
@Getter
private final int resourceId;
/**
* The bStats resource ID of the plugin.
*/
@Getter
private final int bStatsId;
/**
* The package where proxy implementations are.
*/
@Getter
private final String proxyPackage;
/**
* The color of the plugin, used in messages.
*/
@Getter
private final String color;
/**
* Loaded integrations.
*/
@Getter
private final Set<String> loadedIntegrations = new HashSet<>();
/**
* Set of classes to be processed on config update.
*/
private final List<Class<?>> updatableClasses = new ArrayList<>();
/**
* The internal plugin scheduler.
*/
@Getter
private final Scheduler scheduler;
/**
* The internal plugin Event Manager.
*/
@Getter
private final EventManager eventManager;
/**
* Config.yml.
*/
@Getter
private final ConfigYml configYml;
/**
* Lang.yml.
*/
@Getter
private final LangYml langYml;
/**
* The internal factory to produce {@link org.bukkit.NamespacedKey}s.
*/
@Getter
private final NamespacedKeyFactory namespacedKeyFactory;
/**
* The internal factory to produce {@link org.bukkit.metadata.FixedMetadataValue}s.
*/
@Getter
private final MetadataValueFactory metadataValueFactory;
/**
* The internal factory to produce {@link com.willfp.eco.core.scheduling.RunnableTask}s.
*/
@Getter
private final RunnableFactory runnableFactory;
/**
* The loader for all plugin extensions.
*
* @see com.willfp.eco.core.extensions.Extension
*/
@Getter
private final ExtensionLoader extensionLoader;
/**
* The handler class for updatable classes.
*/
@Getter
private final ConfigHandler configHandler;
/**
* The display module for the plugin.
*/
@Getter
private DisplayModule displayModule;
/**
* The logger for the plugin.
*/
private final Logger logger;
/**
* If the server is running an outdated version of the plugin.
*/
@Getter
private boolean outdated = false;
/**
* If the plugin supports extensions.
*/
@Getter
private final boolean supportingExtensions;
/**
* Create a new plugin without a specified color, proxy support, spigot, or bStats.
*/
protected EcoPlugin() {
this("&f");
}
/**
* Create a new plugin without proxy support, spigot, or bStats.
*
* @param color The color.
*/
protected EcoPlugin(@NotNull final String color) {
this("", color);
}
/**
* Create a new plugin unlinked to spigot and bStats.
*
* @param proxyPackage The package where proxy implementations are stored.
* @param color The color of the plugin (used in messages, such as &a, &b)
*/
protected EcoPlugin(@NotNull final String proxyPackage,
@NotNull final String color) {
this(0, 0, proxyPackage, color);
}
/**
* Create a new plugin without proxy or extension support.
*
* @param resourceId The spigot resource ID for the plugin.
* @param bStatsId The bStats resource ID for the plugin.
* @param color The color of the plugin (used in messages, such as &a, &b)
*/
protected EcoPlugin(final int resourceId,
final int bStatsId,
@NotNull final String color) {
this(resourceId, bStatsId, "", color);
}
/**
* Create a new plugin without proxy support.
*
* @param resourceId The spigot resource ID for the plugin.
* @param bStatsId The bStats resource ID for the plugin.
* @param color The color of the plugin (used in messages, such as &a, &b)
* @param supportingExtensions If the plugin supports extensions.
*/
protected EcoPlugin(final int resourceId,
final int bStatsId,
@NotNull final String color,
final boolean supportingExtensions) {
this(resourceId, bStatsId, "", color, supportingExtensions);
}
/**
* Create a new plugin without extension support.
*
* @param resourceId The spigot resource ID for the plugin.
* @param bStatsId The bStats resource ID for the plugin.
* @param proxyPackage The package where proxy implementations are stored.
* @param color The color of the plugin (used in messages, such as &a, &b)
*/
protected EcoPlugin(final int resourceId,
final int bStatsId,
@NotNull final String proxyPackage,
@NotNull final String color) {
this(resourceId, bStatsId, proxyPackage, color, false);
}
/**
* Create a new plugin.
*
* @param resourceId The spigot resource ID for the plugin.
* @param bStatsId The bStats resource ID for the plugin.
* @param proxyPackage The package where proxy implementations are stored.
* @param color The color of the plugin (used in messages, such as &a, &b)
* @param supportingExtensions If the plugin supports extensions.
*/
protected EcoPlugin(final int resourceId,
final int bStatsId,
@NotNull final String proxyPackage,
@NotNull final String color,
final boolean supportingExtensions) {
this("", resourceId, bStatsId, proxyPackage, color, supportingExtensions);
}
/**
* Create a new plugin.
*
* @param pluginName The name of the plugin.
* @param resourceId The spigot resource ID for the plugin.
* @param bStatsId The bStats resource ID for the plugin.
* @param proxyPackage The package where proxy implementations are stored.
* @param color The color of the plugin (used in messages, such as &a, &b)
* @deprecated pluginName is redundant.
*/
@Deprecated
@SuppressWarnings("unused")
protected EcoPlugin(@NotNull final String pluginName,
final int resourceId,
final int bStatsId,
@NotNull final String proxyPackage,
@NotNull final String color) {
this(pluginName, resourceId, bStatsId, proxyPackage, color, false);
}
/**
* Create a new plugin.
*
* @param pluginName The name of the plugin.
* @param resourceId The spigot resource ID for the plugin.
* @param bStatsId The bStats resource ID for the plugin.
* @param proxyPackage The package where proxy implementations are stored.
* @param color The color of the plugin (used in messages, such as &a, &b)
* @param supportingExtensions If the plugin supports extensions.
* @deprecated pluginName is redundant.
*/
@Deprecated
@SuppressWarnings("unused")
protected EcoPlugin(@NotNull final String pluginName,
final int resourceId,
final int bStatsId,
@NotNull final String proxyPackage,
@NotNull final String color,
final boolean supportingExtensions) {
this.pluginName = this.getName();
this.resourceId = resourceId;
this.bStatsId = bStatsId;
this.proxyPackage = proxyPackage;
this.color = color;
this.supportingExtensions = supportingExtensions;
this.scheduler = new EcoScheduler(this);
this.eventManager = new EcoEventManager(this);
this.namespacedKeyFactory = new EcoNamespacedKeyFactory(this);
this.metadataValueFactory = new EcoMetadataValueFactory(this);
this.runnableFactory = new EcoRunnableFactory(this);
this.extensionLoader = new EcoExtensionLoader(this);
this.configHandler = new EcoConfigHandler(this);
this.logger = new EcoLogger(this);
this.langYml = new LangYml(this);
this.configYml = new ConfigYml(this);
LOADED_ECO_PLUGINS.add(this.getName().toLowerCase());
}
/**
* Default code to be executed on plugin enable.
*/
@Override
public final void onEnable() {
super.onEnable();
this.getLogger().info("");
this.getLogger().info("Loading " + this.getColor() + this.getName());
this.getEventManager().registerListener(new ArrowDataListener(this));
if (this.getResourceId() != 0) {
new UpdateChecker(this).getVersion(version -> {
DefaultArtifactVersion currentVersion = new DefaultArtifactVersion(this.getDescription().getVersion());
DefaultArtifactVersion mostRecentVersion = new DefaultArtifactVersion(version);
if (!(currentVersion.compareTo(mostRecentVersion) > 0 || currentVersion.equals(mostRecentVersion))) {
this.outdated = true;
this.getScheduler().runTimer(() -> {
this.getLogger().info("&c " + this.getName() + " is out of date! (Version " + this.getDescription().getVersion() + ")");
this.getLogger().info("&cThe newest version is &f" + version);
this.getLogger().info("&cDownload the new version!");
}, 0, 864000);
}
});
}
DefaultArtifactVersion runningVersion = new DefaultArtifactVersion(Internals.getInstance().getPlugin().getDescription().getVersion());
DefaultArtifactVersion requiredVersion = new DefaultArtifactVersion(this.getMinimumEcoVersion());
if (!(runningVersion.compareTo(requiredVersion) > 0 || runningVersion.equals(requiredVersion))) {
this.getLogger().severe("You are running an outdated version of eco!");
this.getLogger().severe("You must be on at least" + this.getMinimumEcoVersion());
this.getLogger().severe("Download the newest version here:");
this.getLogger().severe("https://polymart.org/download/773/recent/JSpprMspkuyecf5y1wQ2Jn8OoLQSQ_IW");
Bukkit.getPluginManager().disablePlugin(this);
}
if (this.getBStatsId() != 0) {
new Metrics(this, this.getBStatsId());
}
Set<String> enabledPlugins = Arrays.stream(Bukkit.getPluginManager().getPlugins()).map(Plugin::getName).collect(Collectors.toSet());
if (enabledPlugins.contains("PlaceholderAPI")) {
this.loadedIntegrations.add("PlaceholderAPI");
PlaceholderManager.addIntegration(new PlaceholderIntegrationPAPI(this));
}
this.getIntegrationLoaders().forEach((integrationLoader -> {
if (enabledPlugins.contains(integrationLoader.getPluginName())) {
this.loadedIntegrations.add(integrationLoader.getPluginName());
integrationLoader.load();
}
}));
this.getLogger().info("Loaded integrations: " + String.join(", ", this.getLoadedIntegrations()));
Prerequisite.update();
this.getPacketAdapters().forEach(abstractPacketAdapter -> {
if (!abstractPacketAdapter.isPostLoad()) {
abstractPacketAdapter.register();
}
});
updatableClasses.addAll(this.getUpdatableClasses());
this.getListeners().forEach(listener -> this.getEventManager().registerListener(listener));
this.getCommands().forEach(AbstractCommand::register);
this.getPluginCommands().forEach(PluginCommand::register);
this.getScheduler().runLater(this::afterLoad, 1);
this.updatableClasses.forEach(clazz -> this.getConfigHandler().registerUpdatableClass(clazz));
if (this.isSupportingExtensions()) {
this.getExtensionLoader().loadExtensions();
if (this.getExtensionLoader().getLoadedExtensions().isEmpty()) {
this.getLogger().info("&cNo extensions found");
} else {
this.getLogger().info("Extensions Loaded:");
this.getExtensionLoader().getLoadedExtensions().forEach(extension -> this.getLogger().info("- " + extension.getName() + " v" + extension.getVersion()));
}
}
this.enable();
this.getLogger().info("");
}
/**
* Default code to be executed on plugin disable.
*/
@Override
public final void onDisable() {
super.onDisable();
this.getEventManager().unregisterAllListeners();
this.getScheduler().cancelAll();
this.getConfigHandler().saveAllConfigs();
this.disable();
if (this.isSupportingExtensions()) {
this.getExtensionLoader().unloadExtensions();
}
}
/**
* Default code to be executed on plugin load.
*/
@Override
public final void onLoad() {
super.onLoad();
this.load();
}
/**
* Default code to be executed after the server is up.
*/
public final void afterLoad() {
this.displayModule = createDisplayModule();
if (this.getDisplayModule() != null) {
Display.registerDisplayModule(this.getDisplayModule());
}
this.getPacketAdapters().forEach(abstractPacketAdapter -> {
if (abstractPacketAdapter.isPostLoad()) {
abstractPacketAdapter.register();
}
});
if (!Prerequisite.HAS_PAPER.isMet()) {
this.getLogger().severe("");
this.getLogger().severe("----------------------------");
this.getLogger().severe("");
this.getLogger().severe("You don't seem to be running paper!");
this.getLogger().severe("Paper is strongly recommended for all servers,");
this.getLogger().severe("and some things may not function properly without it");
this.getLogger().severe("Download Paper from &fhttps://papermc.io");
this.getLogger().severe("");
this.getLogger().severe("----------------------------");
this.getLogger().severe("");
}
this.postLoad();
this.reload();
this.getLogger().info("Loaded " + this.color + this.pluginName);
}
/**
* Default code to be executed on plugin reload.
*/
public final void reload() {
this.getConfigHandler().updateConfigs();
this.getConfigHandler().callUpdate();
this.getConfigHandler().callUpdate(); // Call twice to fix issues
this.getScheduler().cancelAll();
this.onReload();
}
/**
* The plugin-specific code to be executed on enable.
* <p>
* Override when needed.
*/
public void enable() {
}
/**
* The plugin-specific code to be executed on disable.
* <p>
* Override when needed.
*/
public void disable() {
}
/**
* The plugin-specific code to be executed on load.
* <p>
* This is executed before enabling.
* <p>
* Override when needed.
*/
public void load() {
}
/**
* The plugin-specific code to be executed on reload.
* <p>
* Override when needed.
*/
public void onReload() {
}
/**
* The plugin-specific code to be executed after the server is up.
* <p>
* Override when needed.
*/
public void postLoad() {
}
/**
* The plugin-specific integrations to be tested and loaded.
*
* @return A list of integrations.
*/
public List<IntegrationLoader> getIntegrationLoaders() {
return new ArrayList<>();
}
/**
* The commands to be registered.
*
* @return A list of commands.
* @deprecated Use {@link this#getPluginCommands()} instead.
*/
@Deprecated
public List<AbstractCommand> getCommands() {
return new ArrayList<>();
}
/**
* The commands to be registered.
*
* @return A list of commands.
*/
public List<PluginCommand> getPluginCommands() {
return new ArrayList<>();
}
/**
* ProtocolLib packet adapters to be registered.
* <p>
* If the plugin does not require ProtocolLib this can be left empty.
*
* @return A list of packet adapters.
*/
public List<AbstractPacketAdapter> getPacketAdapters() {
return new ArrayList<>();
}
/**
* All listeners to be registered.
*
* @return A list of all listeners.
*/
public abstract List<Listener> getListeners();
/**
* All updatable classes.
*
* @return A list of all updatable classes.
*/
public List<Class<?>> getUpdatableClasses() {
return new ArrayList<>();
}
/**
* Create the display module for the plugin.
*
* @return The display module, or null.
*/
@Nullable
protected DisplayModule createDisplayModule() {
Validate.isTrue(
this.getDisplayModule() == null,
"Display module exists!"
);
return null;
}
/**
* Get the minimum version of eco to use the plugin.
*
* @return The version.
*/
protected String getMinimumEcoVersion() {
return "5.0.0";
}
/**
* Get the plugin's logger.
*
* @return The logger.
*/
@NotNull
@Override
public Logger getLogger() {
return logger;
}
/**
* Get unwrapped config.
* Does not use eco config system, don't use.
*
* @return The bukkit config.
* @deprecated Use {@link EcoPlugin#getConfigYml()} instead.
*/
@NotNull
@Override
@Deprecated
public final FileConfiguration getConfig() {
this.getLogger().warning("Call to default config method in eco plugin!");
return this.getConfigYml().getHandle();
}
/**
* Does not use eco config system, don't use.
*
* @deprecated Use eco config system.
*/
@Override
@Deprecated
public final void saveConfig() {
this.getLogger().warning("Call to default config method in eco plugin!");
super.saveConfig();
}
/**
* Does not use eco config system, don't use.
*
* @deprecated Use eco config system.
*/
@Override
@Deprecated
public final void saveDefaultConfig() {
this.getLogger().warning("Call to default config method in eco plugin!");
super.saveDefaultConfig();
}
/**
* Does not use eco config system, don't use.
*
* @deprecated Use eco config system.
*/
@Override
@Deprecated
public final void reloadConfig() {
this.getLogger().warning("Call to default config method in eco plugin!");
super.reloadConfig();
}
}

View File

@@ -0,0 +1,22 @@
package com.willfp.eco.core;
import lombok.AccessLevel;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
public abstract class PluginDependent<T extends EcoPlugin> {
/**
* The {@link EcoPlugin} that is stored.
*/
@Getter(AccessLevel.PROTECTED)
private final T plugin;
/**
* Pass an {@link EcoPlugin} in order to interface with it.
*
* @param plugin The plugin to manage.
*/
protected PluginDependent(@NotNull final T plugin) {
this.plugin = plugin;
}
}

View File

@@ -1,7 +1,7 @@
package com.willfp.eco.util.optional;
package com.willfp.eco.core;
import com.willfp.eco.core.proxy.ProxyConstants;
import com.willfp.eco.util.ClassUtils;
import com.willfp.eco.util.proxy.ProxyConstants;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
@@ -16,14 +16,6 @@ public class Prerequisite {
*/
private static final List<Prerequisite> VALUES = new ArrayList<>();
/**
* Requires the server to be running minecraft version 1.16 or higher.
*/
public static final Prerequisite MINIMUM_1_16 = new Prerequisite(
() -> !ProxyConstants.NMS_VERSION.contains("15"),
"Requires minimum server version of 1.16"
);
/**
* Requires the server to be running an implementation of paper.
*/
@@ -32,6 +24,23 @@ public class Prerequisite {
"Requires server to be running paper (or a fork)"
);
/**
* Requires the server to be running 1.17.
*/
@Deprecated
public static final Prerequisite v1_17 = new Prerequisite(
() -> ProxyConstants.NMS_VERSION.contains("17"),
"Requires server to be running 1.17+"
);
/**
* Requires the server to be running 1.17.
*/
public static final Prerequisite HAS_1_17 = new Prerequisite(
() -> ProxyConstants.NMS_VERSION.contains("17"),
"Requires server to be running 1.17+"
);
/**
* If the necessary prerequisite condition has been met.
*/

View File

@@ -1,7 +1,7 @@
package com.willfp.eco.util.command;
package com.willfp.eco.core.command;
import com.willfp.eco.util.internal.PluginDependent;
import com.willfp.eco.util.plugin.AbstractEcoPlugin;
import com.willfp.eco.core.PluginDependent;
import com.willfp.eco.core.EcoPlugin;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
@@ -14,7 +14,9 @@ import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.List;
public abstract class AbstractCommand extends PluginDependent implements CommandExecutor {
@Deprecated
@SuppressWarnings("DeprecatedIsStillUsed")
public abstract class AbstractCommand extends PluginDependent<EcoPlugin> implements CommandExecutor {
/**
* The name of the command
* <p>
@@ -43,12 +45,12 @@ public abstract class AbstractCommand extends PluginDependent implements Command
* <p>
* The name cannot be the same as an existing command as this will conflict.
*
* @param plugin The owning {@link AbstractEcoPlugin}.
* @param plugin The owning {@link EcoPlugin}.
* @param name The name used in execution.
* @param permission The permission required to execute the command.
* @param playersOnly If only players should be able to execute this command.
*/
protected AbstractCommand(@NotNull final AbstractEcoPlugin plugin,
protected AbstractCommand(@NotNull final EcoPlugin plugin,
@NotNull final String name,
@NotNull final String permission,
final boolean playersOnly) {
@@ -98,7 +100,7 @@ public abstract class AbstractCommand extends PluginDependent implements Command
* @param command The bukkit command.
* @param label The name of the executed command.
* @param args The arguments of the command (anything after the physical command name)
* @return If the command was processed by the linked {@link AbstractEcoPlugin}
* @return If the command was processed by the linked {@link EcoPlugin}
*/
@Override
public final boolean onCommand(@NotNull final CommandSender sender,

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.command;
package com.willfp.eco.core.command;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
@@ -9,6 +9,7 @@ import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.List;
@Deprecated
public abstract class AbstractTabCompleter implements TabCompleter {
/**
* The {@link AbstractCommand} that is tab-completed.

View File

@@ -0,0 +1,48 @@
package com.willfp.eco.core.command;
import org.jetbrains.annotations.NotNull;
public interface CommandBase {
/**
* Get command name.
*
* @return The name.
*/
String getName();
/**
* Get command permission.
*
* @return The permission.
*/
String getPermission();
/**
* If only players can execute the command.
*
* @return If true.
*/
boolean isPlayersOnly();
/**
* Add a subcommand to the command.
*
* @param command The subcommand.
* @return The parent command.
*/
CommandBase addSubcommand(@NotNull CommandBase command);
/**
* Get the handler.
*
* @return The handler.
*/
CommandHandler getHandler();
/**
* Get the tab completer.
*
* @return The tab completer.
*/
TabCompleteHandler getTabCompleter();
}

View File

@@ -0,0 +1,18 @@
package com.willfp.eco.core.command;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import java.util.List;
@FunctionalInterface
public interface CommandHandler {
/**
* The code to be called on execution.
*
* @param sender The sender.
* @param args The arguments.
*/
void onExecute(@NotNull CommandSender sender,
@NotNull List<String> args);
}

View File

@@ -0,0 +1,19 @@
package com.willfp.eco.core.command;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import java.util.List;
@FunctionalInterface
public interface TabCompleteHandler {
/**
* Handle Tab Completion.
*
* @param sender The sender.
* @param args The arguments.
* @return The tab completion results.
*/
List<String> tabComplete(@NotNull CommandSender sender,
@NotNull List<String> args);
}

View File

@@ -0,0 +1,92 @@
package com.willfp.eco.core.command.impl;
import com.willfp.eco.core.EcoPlugin;
import com.willfp.eco.internal.commands.HandledCommand;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public abstract class PluginCommand extends HandledCommand implements CommandExecutor, TabCompleter {
/**
* Create a new command.
* <p>
* The command will not be registered until {@link this#register()} is called.
* <p>
* The name cannot be the same as an existing command as this will conflict.
*
* @param plugin The plugin.
* @param name The name used in execution.
* @param permission The permission required to execute the command.
* @param playersOnly If only players should be able to execute this command.
*/
protected PluginCommand(@NotNull final EcoPlugin plugin,
@NotNull final String name,
@NotNull final String permission,
final boolean playersOnly) {
super(plugin, name, permission, playersOnly);
}
/**
* Registers the command with the server,
* <p>
* Requires the command name to exist, defined in plugin.yml.
*/
public final void register() {
org.bukkit.command.PluginCommand command = Bukkit.getPluginCommand(this.getName());
assert command != null;
command.setExecutor(this);
command.setTabCompleter(this);
}
/**
* Internal implementation used to clean up boilerplate.
* Used for parity with {@link CommandExecutor#onCommand(CommandSender, Command, String, String[])}.
*
* @param sender The executor of the command.
* @param command The bukkit command.
* @param label The name of the executed command.
* @param args The arguments of the command (anything after the physical command name)
* @return If the command was processed by the linked {@link EcoPlugin}
*/
@Override
public final boolean onCommand(@NotNull final CommandSender sender,
@NotNull final Command command,
@NotNull final String label,
@NotNull final String[] args) {
if (!command.getName().equalsIgnoreCase(this.getName())) {
return false;
}
this.handle(sender, args);
return true;
}
/**
* Internal implementation used to clean up boilerplate.
* Used for parity with {@link TabCompleter#onTabComplete(CommandSender, Command, String, String[])}.
*
* @param sender The executor of the command.
* @param command The bukkit command.
* @param label The name of the executed command.
* @param args The arguments of the command (anything after the physical command name).
* @return The list of tab-completions.
*/
@Override
public @Nullable List<String> onTabComplete(@NotNull final CommandSender sender,
@NotNull final Command command,
@NotNull final String label,
@NotNull final String[] args) {
if (!command.getName().equalsIgnoreCase(this.getName())) {
return null;
}
return this.handleTabCompletion(sender, args);
}
}

View File

@@ -0,0 +1,36 @@
package com.willfp.eco.core.command.impl;
import com.willfp.eco.core.EcoPlugin;
import com.willfp.eco.core.command.CommandBase;
import com.willfp.eco.internal.commands.HandledCommand;
import org.jetbrains.annotations.NotNull;
public abstract class Subcommand extends HandledCommand {
/**
* Create subcommand.
*
* @param plugin The plugin.
* @param name The subcommand name.
* @param permission The subcommand permission.
* @param playersOnly If the subcommand only works on players.
*/
protected Subcommand(@NotNull final EcoPlugin plugin,
@NotNull final String name,
@NotNull final String permission,
final boolean playersOnly) {
super(plugin, name, permission, playersOnly);
}
/**
* Create subcommand.
*
* @param plugin The plugin.
* @param name The name of the subcommand.
* @param parent The parent command.
*/
protected Subcommand(@NotNull final EcoPlugin plugin,
@NotNull final String name,
@NotNull final CommandBase parent) {
super(plugin, name, parent.getPermission(), parent.isPlayersOnly());
}
}

View File

@@ -1,10 +1,10 @@
package com.willfp.eco.util.config;
package com.willfp.eco.core.config;
import com.willfp.eco.internal.config.AbstractUpdatableConfig;
import com.willfp.eco.util.plugin.AbstractEcoPlugin;
import com.willfp.eco.internal.config.yaml.UpdatableYamlConfig;
import com.willfp.eco.core.EcoPlugin;
import org.jetbrains.annotations.NotNull;
public abstract class BaseConfig extends AbstractUpdatableConfig {
public abstract class BaseConfig extends UpdatableYamlConfig {
/**
* Config implementation for configs present in the plugin's base directory (eg config.yml, lang.yml).
@@ -18,7 +18,7 @@ public abstract class BaseConfig extends AbstractUpdatableConfig {
*/
protected BaseConfig(@NotNull final String configName,
final boolean removeUnused,
@NotNull final AbstractEcoPlugin plugin,
@NotNull final EcoPlugin plugin,
@NotNull final String... updateBlacklist) {
super(configName, plugin, "", plugin.getClass(), removeUnused, updateBlacklist);
}
@@ -34,7 +34,7 @@ public abstract class BaseConfig extends AbstractUpdatableConfig {
*/
protected BaseConfig(@NotNull final String configName,
final boolean removeUnused,
@NotNull final AbstractEcoPlugin plugin) {
@NotNull final EcoPlugin plugin) {
super(configName, plugin, "", plugin.getClass(), removeUnused, "");
}
}

View File

@@ -1,7 +1,5 @@
package com.willfp.eco.util.config;
package com.willfp.eco.core.config;
import com.willfp.eco.util.serialization.EcoSerializable;
import org.bukkit.configuration.ConfigurationSection;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -13,6 +11,13 @@ public interface Config {
*/
void clearCache();
/**
* Convert the config into readable text.
*
* @return The plaintext.
*/
String toPlaintext();
/**
* Get if the config contains a key.
*
@@ -30,15 +35,6 @@ public interface Config {
@NotNull
List<String> getKeys(boolean deep);
/**
* Set an object in config.
*
* @param path The path.
* @param object The object.
*/
void set(@NotNull String path,
@NotNull EcoSerializable<?> object);
/**
* Get an object from config.
* Default implementations call {@link org.bukkit.configuration.file.YamlConfiguration#get(String)}.
@@ -47,49 +43,17 @@ public interface Config {
* @return The object.
*/
@Nullable
Object getRaw(@NotNull String path);
Object get(@NotNull String path);
/**
* Get an object from config.
* Set an object in config.
* Default implementations call {@link org.bukkit.configuration.file.YamlConfiguration#set(String, Object)}
*
* @param path The path.
* @param clazz The class of the object.
* @param <T> The type of the object.
* @return The object.
* @param path The path.
* @param object The object.
*/
@NotNull <T extends EcoSerializable<T>> T get(@NotNull String path,
@NotNull Class<T> clazz);
/**
* Get an object from config.
*
* @param path The path.
* @param clazz The class of the object.
* @param <T> The type of the object.
* @return The object, or null if not found.
*/
@Nullable <T extends EcoSerializable<T>> T getOrNull(@NotNull String path,
@NotNull Class<T> clazz);
/**
* Get bukkit configuration section from config.
*
* @param path The key to check.
* @return The configuration section. Throws NPE if not found.
*/
@NotNull
@Deprecated
ConfigurationSection getSection(@NotNull String path);
/**
* Get bukkit configuration section from config.
*
* @param path The key to check.
* @return The configuration section, or null if not found.
*/
@Nullable
@Deprecated
ConfigurationSection getSectionOrNull(@NotNull String path);
void set(@NotNull String path,
@Nullable Object object);
/**
* Get subsection from config.

View File

@@ -0,0 +1,35 @@
package com.willfp.eco.core.config;
import com.willfp.eco.internal.config.LoadableConfig;
import org.jetbrains.annotations.NotNull;
public interface ConfigHandler {
/**
* Invoke all update methods.
*/
void callUpdate();
/**
* Register an updatable class.
*
* @param updatableClass The class with an update method.
*/
void registerUpdatableClass(@NotNull Class<?> updatableClass);
/**
* Save all configs.
*/
void saveAllConfigs();
/**
* Update all updatable configs.
*/
void updateConfigs();
/**
* Add new config to be saved.
*
* @param config The config.
*/
void addConfig(@NotNull LoadableConfig config);
}

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.config.updating.annotations;
package com.willfp.eco.core.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;

View File

@@ -1,10 +1,10 @@
package com.willfp.eco.util.config;
package com.willfp.eco.core.config;
import com.willfp.eco.internal.config.AbstractUpdatableConfig;
import com.willfp.eco.util.plugin.AbstractEcoPlugin;
import com.willfp.eco.internal.config.yaml.UpdatableYamlConfig;
import com.willfp.eco.core.EcoPlugin;
import org.jetbrains.annotations.NotNull;
public abstract class ExtendableConfig extends AbstractUpdatableConfig {
public abstract class ExtendableConfig extends UpdatableYamlConfig {
/**
* Config implementation for configs present in the plugin's base directory (eg config.yml, lang.yml).
* <p>
@@ -19,7 +19,7 @@ public abstract class ExtendableConfig extends AbstractUpdatableConfig {
*/
protected ExtendableConfig(@NotNull final String configName,
final boolean removeUnused,
@NotNull final AbstractEcoPlugin plugin,
@NotNull final EcoPlugin plugin,
@NotNull final Class<?> source,
@NotNull final String subDirectoryPath,
@NotNull final String... updateBlacklist) {

View File

@@ -0,0 +1,26 @@
package com.willfp.eco.core.config;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public interface JSONConfig extends Config {
/**
* Get a list of subsections from config.
*
* @param path The key to fetch the value from.
* @return The found value, or a blank {@link java.util.ArrayList} if not found.
*/
@NotNull
List<JSONConfig> getSubsections(@NotNull String path);
/**
* Get a list of subsections from config.
*
* @param path The key to fetch the value from.
* @return The found value, or null if not found.
*/
@Nullable
List<JSONConfig> getSubsectionsOrNull(@NotNull String path);
}

View File

@@ -0,0 +1,20 @@
package com.willfp.eco.core.config;
import com.willfp.eco.core.EcoPlugin;
import com.willfp.eco.internal.config.json.LoadableJsonConfig;
import org.jetbrains.annotations.NotNull;
public abstract class JsonStaticBaseConfig extends LoadableJsonConfig {
/**
* Config implementation for configs present in the plugin's base directory (eg config.json, lang.json).
* <p>
* Does not automatically update.
*
* @param configName The name of the config
* @param plugin The plugin.
*/
protected JsonStaticBaseConfig(@NotNull final String configName,
@NotNull final EcoPlugin plugin) {
super(configName, plugin, "", plugin.getClass());
}
}

View File

@@ -1,10 +1,10 @@
package com.willfp.eco.util.config;
package com.willfp.eco.core.config;
import com.willfp.eco.internal.config.AbstractConfig;
import com.willfp.eco.util.plugin.AbstractEcoPlugin;
import com.willfp.eco.internal.config.yaml.LoadableYamlConfig;
import com.willfp.eco.core.EcoPlugin;
import org.jetbrains.annotations.NotNull;
public abstract class StaticBaseConfig extends AbstractConfig {
public abstract class StaticBaseConfig extends LoadableYamlConfig {
/**
* Config implementation for configs present in the plugin's base directory (eg config.yml, lang.yml).
* <p>
@@ -14,7 +14,7 @@ public abstract class StaticBaseConfig extends AbstractConfig {
* @param plugin The plugin.
*/
protected StaticBaseConfig(@NotNull final String configName,
@NotNull final AbstractEcoPlugin plugin) {
@NotNull final EcoPlugin plugin) {
super(configName, plugin, "", plugin.getClass());
}
}

View File

@@ -0,0 +1,18 @@
package com.willfp.eco.core.config;
import com.willfp.eco.internal.config.yaml.YamlConfigWrapper;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
public abstract class YamlConfig extends YamlConfigWrapper<YamlConfiguration> {
/**
* Config implementation for passing YamlConfigurations.
* <p>
* Does not automatically update.
*
* @param config The YamlConfiguration handle.
*/
public YamlConfig(@NotNull final YamlConfiguration config) {
init(config);
}
}

View File

@@ -0,0 +1,17 @@
package com.willfp.eco.core.config.base;
import com.willfp.eco.core.config.BaseConfig;
import com.willfp.eco.core.EcoPlugin;
import org.jetbrains.annotations.NotNull;
public class ConfigYml extends BaseConfig {
/**
* Config.yml.
*
* @param plugin The plugin.
*/
public ConfigYml(@NotNull final EcoPlugin plugin) {
super("config", true, plugin);
}
}

View File

@@ -1,16 +1,16 @@
package com.willfp.eco.util.config.configs;
package com.willfp.eco.core.config.base;
import com.willfp.eco.util.config.BaseConfig;
import com.willfp.eco.util.plugin.AbstractEcoPlugin;
import com.willfp.eco.core.config.BaseConfig;
import com.willfp.eco.core.EcoPlugin;
import org.jetbrains.annotations.NotNull;
public class Lang extends BaseConfig {
public class LangYml extends BaseConfig {
/**
* Lang.yml.
*
* @param plugin The plugin.
*/
public Lang(@NotNull final AbstractEcoPlugin plugin) {
public LangYml(@NotNull final EcoPlugin plugin) {
super("lang", false, plugin);
}

View File

@@ -0,0 +1,85 @@
package com.willfp.eco.core.data;
import com.willfp.eco.core.EcoPlugin;
import com.willfp.eco.core.config.Config;
import com.willfp.eco.core.config.JSONConfig;
import com.willfp.eco.core.config.JsonStaticBaseConfig;
import com.willfp.eco.internal.config.LoadableConfig;
import com.willfp.eco.internal.config.json.JsonConfigSection;
import lombok.experimental.UtilityClass;
import org.bukkit.OfflinePlayer;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@UtilityClass
public class Data {
/**
* Instance of eco data.yml.
*/
private static JSONConfig datafile = null;
/**
* All cached player data.
*/
private static final Map<UUID, Map<EcoPlugin, JSONConfig>> PLAYER_DATA = new HashMap<>();
/**
* Initialize the player data with an instance of data.json.
*
* @param config data.json.
*/
@ApiStatus.Internal
public void init(@NotNull final JsonStaticBaseConfig config) {
datafile = config;
}
/**
* Save to data.yml.
*
* @param config Instance of data.yml.
* @throws IOException Error during saving.
*/
@ApiStatus.Internal
public void save(@NotNull final Config config) throws IOException {
for (Map.Entry<UUID, Map<EcoPlugin, JSONConfig>> entry : PLAYER_DATA.entrySet()) {
entry.getValue().forEach((plugin, jsonConfig) -> {
for (String key : jsonConfig.getKeys(false)) {
config.set("player-data." + plugin.getName().toLowerCase() + "." + entry.getKey().toString() + "." + key, jsonConfig);
}
});
}
((LoadableConfig) config).save();
}
/**
* Get the data for a player.
*
* @param player The player.
* @param plugin The plugin.
* @return The data.
*/
public JSONConfig getData(@NotNull final OfflinePlayer player,
@NotNull final EcoPlugin plugin) {
if (!PLAYER_DATA.containsKey(player.getUniqueId())) {
PLAYER_DATA.put(player.getUniqueId(), new HashMap<>());
}
JSONConfig config = PLAYER_DATA.get(player.getUniqueId()).get(plugin);
if (config == null) {
config = (JSONConfig) datafile.getSubsectionOrNull("player-data." + plugin.getName().toLowerCase() + "." + player.getUniqueId());
if (config == null) {
config = new JsonConfigSection(new HashMap<>());
}
PLAYER_DATA.get(player.getUniqueId()).put(plugin, config);
return getData(player, plugin);
}
return config;
}
}

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.display;
package com.willfp.eco.core.display;
import lombok.experimental.UtilityClass;
import org.apache.commons.lang.Validate;
@@ -16,7 +16,6 @@ import java.util.List;
import java.util.Map;
@UtilityClass
@SuppressWarnings("deprecation")
public class Display {
/**
* The prefix for lore lines.
@@ -80,7 +79,6 @@ public class Display {
List<DisplayModule> modules = MODULES.get(priority);
for (DisplayModule module : modules) {
Object[] varargs = pluginVarArgs.get(module.getPluginName());
module.display(itemStack);
module.display(itemStack, varargs);
}
}

View File

@@ -1,12 +1,12 @@
package com.willfp.eco.util.display;
package com.willfp.eco.core.display;
import com.willfp.eco.util.internal.PluginDependent;
import com.willfp.eco.util.plugin.AbstractEcoPlugin;
import com.willfp.eco.core.PluginDependent;
import com.willfp.eco.core.EcoPlugin;
import lombok.Getter;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
public abstract class DisplayModule extends PluginDependent {
public abstract class DisplayModule extends PluginDependent<EcoPlugin> {
/**
* The priority of the module.
*/
@@ -19,7 +19,7 @@ public abstract class DisplayModule extends PluginDependent {
* @param plugin The plugin that the display is for.
* @param priority The priority of the module.
*/
protected DisplayModule(@NotNull final AbstractEcoPlugin plugin,
protected DisplayModule(@NotNull final EcoPlugin plugin,
@NotNull final DisplayPriority priority) {
super(plugin);
this.priority = priority;
@@ -36,26 +36,13 @@ public abstract class DisplayModule extends PluginDependent {
// Technically optional.
}
/**
* Display an item.
* <p>
* This method exists for parity with older plugins that don't include the varargs.
*
* @param itemStack The item.
* @deprecated Use {@link this#display(ItemStack, Object...)} instead.
*/
@Deprecated
protected void display(@NotNull final ItemStack itemStack) {
// Technically optional.
}
/**
* Revert an item.
*
* @param itemStack The item.
*/
protected void revert(@NotNull final ItemStack itemStack) {
// Technically optoinal.
// Technically optional.
}
/**
@@ -74,6 +61,6 @@ public abstract class DisplayModule extends PluginDependent {
* @return The plugin name.
*/
final String getPluginName() {
return super.getPlugin().getPluginName();
return super.getPlugin().getName();
}
}

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.display;
package com.willfp.eco.core.display;
public enum DisplayPriority {
/**

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.drops;
package com.willfp.eco.core.drops;
import com.willfp.eco.internal.drops.AbstractDropQueue;
import com.willfp.eco.internal.drops.DropManager;

View File

@@ -0,0 +1,31 @@
package com.willfp.eco.core.events;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
import org.jetbrains.annotations.NotNull;
public class ArmorEquipEvent extends PlayerEvent {
private static final HandlerList HANDLERS = new HandlerList();
public ArmorEquipEvent(@NotNull final Player player) {
super(player);
}
/**
* Gets a list of handlers handling this event.
*
* @return A list of handlers handling this event.
*/
@Override
@NotNull
public HandlerList getHandlers() {
return HANDLERS;
}
public static HandlerList getHandlerList() {
return HANDLERS;
}
}

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.events.entitydeathbyentity;
package com.willfp.eco.core.events;
import lombok.Getter;
import org.bukkit.entity.Entity;

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.bukkit.events;
package com.willfp.eco.core.events;
import org.bukkit.event.Listener;

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.events.naturalexpgainevent;
package com.willfp.eco.core.events;
import lombok.Getter;
import org.bukkit.event.Event;

View File

@@ -0,0 +1,40 @@
package com.willfp.eco.core.events;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerMoveEvent;
import org.jetbrains.annotations.NotNull;
public class PlayerJumpEvent extends PlayerMoveEvent {
/**
* Internal bukkit.
*/
private static final HandlerList HANDLERS = new HandlerList();
/**
* Create a new PlayerJumpEvent.
*
* @param event The PlayerMoveEvent.
*/
public PlayerJumpEvent(@NotNull final PlayerMoveEvent event) {
super(event.getPlayer(), event.getFrom(), event.getTo());
}
/**
* Internal bukkit.
*
* @return The handlers.
*/
@Override
public @NotNull HandlerList getHandlers() {
return HANDLERS;
}
/**
* Internal bukkit.
*
* @return The handlers.
*/
public static @NotNull HandlerList getHandlerList() {
return HANDLERS;
}
}

View File

@@ -1,25 +1,25 @@
package com.willfp.eco.util.extensions;
package com.willfp.eco.core.extensions;
import com.willfp.eco.util.plugin.AbstractEcoPlugin;
import com.willfp.eco.internal.extensions.ExtensionMetadata;
import com.willfp.eco.core.EcoPlugin;
import lombok.AccessLevel;
import lombok.Getter;
import org.apache.commons.lang.Validate;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
public abstract class Extension {
/**
* The {@link AbstractEcoPlugin} that this extension is for.
* The {@link EcoPlugin} that this extension is for.
*/
@Getter(AccessLevel.PROTECTED)
private final AbstractEcoPlugin plugin;
private final EcoPlugin plugin;
/**
* Create a new extension for a plugin.
*
* @param plugin The plugin.
*/
protected Extension(@NotNull final AbstractEcoPlugin plugin) {
protected Extension(@NotNull final EcoPlugin plugin) {
this.plugin = plugin;
}
@@ -71,7 +71,7 @@ public abstract class Extension {
*/
public final String getName() {
Validate.notNull(metadata, "Metadata cannot be null!");
return this.metadata.name;
return this.metadata.name();
}
/**
@@ -81,36 +81,6 @@ public abstract class Extension {
*/
public final String getVersion() {
Validate.notNull(metadata, "Metadata cannot be null!");
return this.metadata.version;
}
/**
* Wrapper for the string and version of the extension.
* Contains versions and name.
* Designed for internal use.
*/
@ApiStatus.Internal
public static final class ExtensionMetadata {
/**
* The version of the extension.
*/
private final @NotNull String version;
/**
* The extension's name.
*/
private final @NotNull String name;
/**
* Create a new extension metadata.
*
* @param version The version for the extension to be.
* @param name The name of the extension.
*/
public ExtensionMetadata(@NotNull final String version,
@NotNull final String name) {
this.version = version;
this.name = name;
}
return this.metadata.version();
}
}

View File

@@ -1,6 +1,4 @@
package com.willfp.eco.util.extensions.loader;
import com.willfp.eco.util.extensions.Extension;
package com.willfp.eco.core.extensions;
import java.util.Set;
@@ -20,11 +18,6 @@ public interface ExtensionLoader {
*/
void unloadExtensions();
/**
* Reload all extensions.
*/
void reloadExtensions();
/**
* Retrieve a set of all loaded extensions.
*

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.extensions;
package com.willfp.eco.core.extensions;
import org.jetbrains.annotations.NotNull;

View File

@@ -0,0 +1,14 @@
package com.willfp.eco.core.factory;
import org.bukkit.metadata.FixedMetadataValue;
import org.jetbrains.annotations.NotNull;
public interface MetadataValueFactory {
/**
* Create a metadata value for a given plugin and object.
*
* @param value The object to store in metadata.
* @return The metadata value.
*/
FixedMetadataValue create(@NotNull Object value);
}

View File

@@ -0,0 +1,14 @@
package com.willfp.eco.core.factory;
import org.bukkit.NamespacedKey;
import org.jetbrains.annotations.NotNull;
public interface NamespacedKeyFactory {
/**
* Create an {@link NamespacedKey} associated with an {@link com.willfp.eco.core.EcoPlugin}.
*
* @param key The key in the {@link NamespacedKey}.
* @return The created {@link NamespacedKey}.
*/
NamespacedKey create(@NotNull String key);
}

View File

@@ -0,0 +1,16 @@
package com.willfp.eco.core.factory;
import com.willfp.eco.core.scheduling.RunnableTask;
import org.jetbrains.annotations.NotNull;
import java.util.function.Consumer;
public interface RunnableFactory {
/**
* Create a {@link RunnableTask}.
*
* @param consumer Lambda of the code to run, where the parameter represents the instance of the runnable.
* @return The created {@link RunnableTask}.
*/
RunnableTask create(@NotNull Consumer<RunnableTask> consumer);
}

View File

@@ -0,0 +1,60 @@
package com.willfp.eco.core.gui.menu;
import com.willfp.eco.core.gui.slot.Slot;
import com.willfp.eco.core.items.builder.ItemStackBuilder;
import com.willfp.eco.internal.gui.FillerSlot;
import com.willfp.eco.util.ListUtils;
import lombok.Getter;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class FillerMask {
/**
* Mask.
*/
@Getter
private final List<List<Slot>> mask;
/**
* Create a new filler mask.
*
* @param material The mask material.
* @param pattern The pattern.
*/
public FillerMask(@NotNull final Material material,
@NotNull final String... pattern) {
if (material == Material.AIR) {
throw new IllegalArgumentException("Material cannot be air!");
}
mask = ListUtils.create2DList(6, 9);
ItemStack itemStack = new ItemStackBuilder(material)
.setDisplayName("&r")
.build();
int row = 0;
for (String patternRow : pattern) {
int column = 0;
if (patternRow.length() != 9) {
throw new IllegalArgumentException("Invalid amount of columns in pattern!");
}
for (char c : patternRow.toCharArray()) {
if (c == '0') {
mask.get(row).set(column, null);
} else if (c == '1') {
mask.get(row).set(column, new FillerSlot(itemStack));
} else {
throw new IllegalArgumentException("Invalid character in pattern! (Must only be 0 and 1)");
}
column++;
}
row++;
}
}
}

View File

@@ -0,0 +1,146 @@
package com.willfp.eco.core.gui.menu;
import com.willfp.eco.core.gui.slot.Slot;
import com.willfp.eco.internal.gui.EcoMenu;
import com.willfp.eco.internal.gui.FillerSlot;
import com.willfp.eco.util.ListUtils;
import com.willfp.eco.util.StringUtils;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.function.Consumer;
public interface Menu {
/**
* Get the amount of rows.
*
* @return The amount of rows.
*/
int getRows();
/**
* Get slot at given row and column.
*
* @param row The row.
* @param column The column.
* @return The row.
*/
Slot getSlot(int row,
int column);
/**
* Get the menu title.
*
* @return The title.
*/
String getTitle();
/**
* Open the inventory for the player.
*
* @param player The player.
* @return The inventory.
*/
Inventory open(@NotNull Player player);
/**
* Create a builder with a given amount of rows.
*
* @param rows The rows.
* @return The builder.
*/
static Builder builder(final int rows) {
return new Builder(rows);
}
class Builder {
/**
* The amount of rows.
*/
private final int rows;
/**
* The title.
*/
private String title = "Menu";
/**
* The mask slots.
*/
private List<List<Slot>> maskSlots;
/**
* The slots.
*/
private final List<List<Slot>> slots;
/**
* The close event handler.
*/
private Consumer<InventoryCloseEvent> onClose = (event) -> {
};
Builder(final int rows) {
this.rows = rows;
this.slots = ListUtils.create2DList(rows, 9);
this.maskSlots = ListUtils.create2DList(rows, 9);
}
public Builder setTitle(@NotNull final String title) {
this.title = StringUtils.translate(title);
return this;
}
public Builder setSlot(final int row,
final int column,
@NotNull final Slot slot) {
if (row < 1 || row > this.rows) {
throw new IllegalArgumentException("Invalid row number!");
}
if (column < 1 || column > 9) {
throw new IllegalArgumentException("Invalid column number!");
}
slots.get(row - 1).set(column - 1, slot);
return this;
}
public Builder setMask(@NotNull final FillerMask mask) {
this.maskSlots = mask.getMask();
return this;
}
public Builder onClose(@NotNull final Consumer<InventoryCloseEvent> action) {
this.onClose = action;
return this;
}
public Menu build() {
List<List<Slot>> finalSlots = maskSlots;
for (int i = 0; i < slots.size(); i++) {
for (int j = 0; j < slots.get(i).size(); j++) {
Slot slot = slots.get(i).get(j);
if (slot != null) {
finalSlots.get(i).set(j, slot);
}
}
}
for (List<Slot> finalSlot : finalSlots) {
for (int j = 0; j < finalSlot.size(); j++) {
if (finalSlot.get(j) == null) {
finalSlot.set(j, new FillerSlot(new ItemStack(Material.AIR)));
}
}
}
return new EcoMenu(rows, finalSlots, title, onClose);
}
}
}

View File

@@ -0,0 +1,105 @@
package com.willfp.eco.core.gui.slot;
import com.willfp.eco.internal.gui.EcoSlot;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import java.util.function.BiConsumer;
import java.util.function.Function;
public interface Slot {
/**
* Get the ItemStack that would be shown to a player.
*
* @param player The player.
* @return The ItemStack.
*/
ItemStack getItemStack(@NotNull Player player);
/**
* Create a builder for an ItemStack.
*
* @param itemStack The ItemStack.
* @return The builder.
*/
static Builder builder(@NotNull final ItemStack itemStack) {
return new Builder((player) -> itemStack);
}
/**
* Create a builder for a player-specific ItemStack.
*
* @param provider The provider.
* @return The builder.
*/
static Builder builder(@NotNull final Function<Player, ItemStack> provider) {
return new Builder(provider);
}
class Builder {
/**
* Provider.
*/
private final Function<Player, ItemStack> provider;
/**
* Left click handler.
*/
private BiConsumer<InventoryClickEvent, Slot> onLeftClick = null;
/**
* Right click handler.
*/
private BiConsumer<InventoryClickEvent, Slot> onRightClick = null;
/**
* Shift-Left-Click handler.
*/
private BiConsumer<InventoryClickEvent, Slot> onShiftLeftClick = null;
/**
* Shift-Right-Click handler.
*/
private BiConsumer<InventoryClickEvent, Slot> onShiftRightClick = null;
/**
* Middle click handler.
*/
private BiConsumer<InventoryClickEvent, Slot> onMiddleClick = null;
Builder(@NotNull final Function<Player, ItemStack> provider) {
this.provider = provider;
}
public Builder onLeftClick(@NotNull final BiConsumer<InventoryClickEvent, Slot> action) {
this.onLeftClick = action;
return this;
}
public Builder onRightClick(@NotNull final BiConsumer<InventoryClickEvent, Slot> action) {
this.onRightClick = action;
return this;
}
public Builder onShiftLeftClick(@NotNull final BiConsumer<InventoryClickEvent, Slot> action) {
this.onShiftLeftClick = action;
return this;
}
public Builder onShiftRightClick(@NotNull final BiConsumer<InventoryClickEvent, Slot> action) {
this.onShiftRightClick = action;
return this;
}
public Builder onMiddleClick(@NotNull final BiConsumer<InventoryClickEvent, Slot> action) {
this.onMiddleClick = action;
return this;
}
public Slot build() {
return new EcoSlot(provider, onLeftClick, onRightClick, onShiftLeftClick, onShiftRightClick, onMiddleClick);
}
}
}

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.integrations;
package com.willfp.eco.core.integrations;
public interface Integration {
/**

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.integrations;
package com.willfp.eco.core.integrations;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;

View File

@@ -1,6 +1,6 @@
package com.willfp.eco.util.integrations.anticheat;
package com.willfp.eco.core.integrations.anticheat;
import com.willfp.eco.util.plugin.AbstractEcoPlugin;
import com.willfp.eco.core.EcoPlugin;
import lombok.experimental.UtilityClass;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
@@ -22,7 +22,7 @@ public class AnticheatManager {
* @param plugin The plugin.
* @param anticheat The anticheat to register.
*/
public void register(@NotNull final AbstractEcoPlugin plugin,
public void register(@NotNull final EcoPlugin plugin,
@NotNull final AnticheatWrapper anticheat) {
if (anticheat instanceof Listener) {
plugin.getEventManager().registerListener((Listener) anticheat);

View File

@@ -1,6 +1,6 @@
package com.willfp.eco.util.integrations.anticheat;
package com.willfp.eco.core.integrations.anticheat;
import com.willfp.eco.util.integrations.Integration;
import com.willfp.eco.core.integrations.Integration;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.integrations.antigrief;
package com.willfp.eco.core.integrations.antigrief;
import lombok.experimental.UtilityClass;
import org.bukkit.Location;

View File

@@ -1,6 +1,6 @@
package com.willfp.eco.util.integrations.antigrief;
package com.willfp.eco.core.integrations.antigrief;
import com.willfp.eco.util.integrations.Integration;
import com.willfp.eco.core.integrations.Integration;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.LivingEntity;

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.integrations.mcmmo;
package com.willfp.eco.core.integrations.mcmmo;
import lombok.experimental.UtilityClass;
import org.bukkit.block.Block;

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.integrations.mcmmo;
package com.willfp.eco.core.integrations.mcmmo;
import org.bukkit.block.Block;
import org.bukkit.event.Event;

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.integrations.placeholder;
package com.willfp.eco.core.integrations.placeholder;
import lombok.Getter;
import org.apache.commons.lang.Validate;

View File

@@ -1,6 +1,6 @@
package com.willfp.eco.util.integrations.placeholder;
package com.willfp.eco.core.integrations.placeholder;
import com.willfp.eco.util.integrations.Integration;
import com.willfp.eco.core.integrations.Integration;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.integrations.placeholder;
package com.willfp.eco.core.integrations.placeholder;
import lombok.experimental.UtilityClass;
import org.bukkit.entity.Player;
@@ -52,7 +52,7 @@ public class PlaceholderManager {
public static String getResult(@Nullable final Player player,
@NotNull final String identifier) {
Optional<PlaceholderEntry> matching = REGISTERED_PLACEHOLDERS.stream().filter(expansion -> expansion.getIdentifier().equalsIgnoreCase(identifier)).findFirst();
if (!matching.isPresent()) {
if (matching.isEmpty()) {
return null;
}
PlaceholderEntry entry = matching.get();

View File

@@ -0,0 +1,59 @@
package com.willfp.eco.core.items;
import lombok.Getter;
import org.bukkit.NamespacedKey;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.function.Predicate;
public class CustomItem implements TestableItem {
/**
* The key.
*/
@Getter
private final NamespacedKey key;
/**
* The test for ItemStacks to pass.
*/
private final Predicate<ItemStack> test;
/**
* Example Item: what the user should see.
*/
private final ItemStack item;
/**
* Create a new complex recipe part.
*
* @param key The item key.
* @param test The test.
* @param item The example ItemStacks.
*/
public CustomItem(@NotNull final NamespacedKey key,
@NotNull final Predicate<ItemStack> test,
@NotNull final ItemStack item) {
this.key = key;
this.test = test;
this.item = item;
}
@Override
public boolean matches(@Nullable final ItemStack itemStack) {
return test.test(itemStack);
}
@Override
public ItemStack getItem() {
return item;
}
/**
* Register the item.
*/
public void register() {
Items.registerCustomItem(this.getKey(), this);
}
}

View File

@@ -0,0 +1,89 @@
package com.willfp.eco.core.items;
import com.willfp.eco.core.recipe.parts.EmptyTestableItem;
import com.willfp.eco.core.recipe.parts.MaterialTestableItem;
import com.willfp.eco.core.recipe.parts.TestableStack;
import lombok.experimental.UtilityClass;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
@UtilityClass
@SuppressWarnings("deprecation")
public final class Items {
/**
* All recipe parts.
*/
private static final Map<NamespacedKey, CustomItem> REGISTRY = new HashMap<>();
/**
* Register a new recipe part.
*
* @param key The key of the recipe part.
* @param part The recipe part.
*/
public void registerCustomItem(@NotNull final NamespacedKey key,
@NotNull final CustomItem part) {
REGISTRY.put(key, part);
}
/**
* Lookup item from string.
* <p>
* Used for recipes.
*
* @param key The string to test.
* @return The found testable item, or an empty item if not found.
*/
public TestableItem lookup(@NotNull final String key) {
String[] split = key.toLowerCase().split(":");
if (split.length == 1) {
Material material = Material.getMaterial(key.toUpperCase());
if (material == null || material == Material.AIR) {
return new EmptyTestableItem();
}
return new MaterialTestableItem(material);
}
if (split.length == 2) {
CustomItem part = REGISTRY.get(new NamespacedKey(split[0], split[1]));
if (part == null) {
Material material = Material.getMaterial(split[0].toUpperCase());
if (material == null || material == Material.AIR) {
return new EmptyTestableItem();
}
return new TestableStack(new MaterialTestableItem(material), Integer.parseInt(split[1]));
} else {
return part;
}
}
if (split.length == 3) {
CustomItem part = REGISTRY.get(new NamespacedKey(split[0], split[1]));
return part == null ? new EmptyTestableItem() : new TestableStack(part, Integer.parseInt(split[2]));
}
return new EmptyTestableItem();
}
/**
* Get if itemStack is a custom item.
*
* @param itemStack The itemStack to check.
* @return If is recipe.
*/
public boolean isCustomItem(@NotNull final ItemStack itemStack) {
for (CustomItem item : REGISTRY.values()) {
if (item.matches(itemStack)) {
return true;
}
}
return false;
}
}

View File

@@ -1,9 +1,9 @@
package com.willfp.eco.util.recipe.parts;
package com.willfp.eco.core.items;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.Nullable;
public interface RecipePart {
public interface TestableItem {
/**
* If an ItemStack matches the recipe part.
*
@@ -13,10 +13,9 @@ public interface RecipePart {
boolean matches(@Nullable ItemStack itemStack);
/**
* Get a displayed itemstack, for autocraft.
* Get an example item.
*
* @return The item, displayed.
* @return The item.
*/
ItemStack getDisplayed();
ItemStack getItem();
}

View File

@@ -0,0 +1,29 @@
package com.willfp.eco.core.items.builder;
import com.willfp.eco.internal.items.AbstractItemStackBuilder;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.jetbrains.annotations.NotNull;
public class EnchantedBookBuilder extends AbstractItemStackBuilder<EnchantmentStorageMeta, EnchantedBookBuilder> {
/**
* Create a new EnchantedBookBuilder.
*/
public EnchantedBookBuilder() {
super(Material.ENCHANTED_BOOK);
}
/**
* Add an enchantment to the item.
*
* @param enchantment The enchantment.
* @param level The level.
* @return The builder.
*/
public EnchantedBookBuilder addStoredEnchantment(@NotNull final Enchantment enchantment,
final int level) {
this.getMeta().addStoredEnchant(enchantment, level, true);
return this;
}
}

View File

@@ -0,0 +1,181 @@
package com.willfp.eco.core.items.builder;
import org.bukkit.NamespacedKey;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.persistence.PersistentDataType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.function.Supplier;
public interface ItemBuilder {
/**
* Set the ItemStack amount.
*
* @param amount The amount.
* @return The builder.
*/
ItemBuilder setAmount(int amount);
/**
* Set the ItemStack amount.
*
* @param amount The amount.
* @return The builder.
*/
ItemBuilder setAmount(@NotNull Supplier<Integer> amount);
/**
* Add an enchantment to the item.
*
* @param enchantment The enchantment.
* @param level The level.
* @return The builder.r
*/
ItemBuilder addEnchantment(@NotNull Enchantment enchantment,
int level);
/**
* Add an enchantment to the item.
*
* @param enchantment The enchantment.
* @param level The level.
* @return The builder.
*/
ItemBuilder addEnchantment(@NotNull Supplier<Enchantment> enchantment,
@NotNull Supplier<Integer> level);
/**
* Set the item display name.
*
* @param name The name.
* @return The builder.
*/
ItemBuilder setDisplayName(@NotNull String name);
/**
* Set the item display name.
*
* @param name The name.
* @return The builder.
*/
ItemBuilder setDisplayName(@NotNull Supplier<String> name);
/**
* Add lore line.
*
* @param line The line.
* @return The builder.
*/
ItemBuilder addLoreLine(@NotNull String line);
/**
* Add lore line.
*
* @param line The line.
* @return The builder.
*/
ItemBuilder addLoreLine(@NotNull Supplier<String> line);
/**
* Add lore lines.
*
* @param lines The lines.
* @return The builder.
*/
ItemBuilder addLoreLines(@NotNull List<String> lines);
/**
* Add lore lines.
*
* @param lines The lines.
* @return The builder.
*/
ItemBuilder addLoreLines(@NotNull Supplier<List<String>> lines);
/**
* Add ItemFlags.
*
* @param itemFlags The flags.
* @return The builder.
*/
ItemBuilder addItemFlag(@NotNull ItemFlag... itemFlags);
/**
* Add ItemFlags.
*
* @param itemFlags The flags.
* @return The builder.
*/
ItemBuilder addItemFlag(@NotNull Supplier<ItemFlag[]> itemFlags);
/**
* Write meta key.
*
* @param key The key.
* @param type The type.
* @param value The value.
* @param <A> The type.
* @param <B> The type.
* @return The builder.
*/
<A, B> ItemBuilder writeMetaKey(@NotNull NamespacedKey key,
@NotNull PersistentDataType<A, B> type,
@NotNull B value);
/**
* Write meta key.
*
* @param key The key.
* @param type The type.
* @param value The value.
* @param <A> The type.
* @param <B> The type.
* @return The builder.
*/
<A, B> ItemBuilder writeMetaKey(@NotNull Supplier<NamespacedKey> key,
@NotNull Supplier<PersistentDataType<A, B>> type,
@NotNull Supplier<B> value);
/**
* Set unbreakable.
*
* @param unbreakable If the item should be unbreakable.
* @return The builder.
*/
ItemBuilder setUnbreakable(boolean unbreakable);
/**
* Set unbreakable.
*
* @param unbreakable If the item should be unbreakable.
* @return The builder.
*/
ItemBuilder setUnbreakable(@NotNull Supplier<Boolean> unbreakable);
/**
* Set custom model data.
*
* @param data The data.
* @return The builder.
*/
ItemBuilder setCustomModelData(@Nullable Integer data);
/**
* Set custom model data.
*
* @param data The data.
* @return The builder.
*/
ItemBuilder setCustomModelData(@NotNull Supplier<Integer> data);
/**
* Build the item.
*
* @return The item.
*/
ItemStack build();
}

View File

@@ -0,0 +1,27 @@
package com.willfp.eco.core.items.builder;
import com.willfp.eco.internal.items.AbstractItemStackBuilder;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
public class ItemStackBuilder extends AbstractItemStackBuilder<ItemMeta, ItemStackBuilder> {
/**
* Create a new ItemStackBuilder.
*
* @param material The material.
*/
public ItemStackBuilder(@NotNull final Material material) {
super(material);
}
/**
* Create a new ItemStackBuilder to modify an existing item.
*
* @param base The ItemStack to start with.
*/
public ItemStackBuilder(@NotNull final ItemStack base) {
super(base);
}
}

View File

@@ -0,0 +1,41 @@
package com.willfp.eco.core.items.builder;
import com.willfp.eco.internal.items.AbstractItemStackBuilder;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.jetbrains.annotations.NotNull;
public class LeatherArmorBuilder extends AbstractItemStackBuilder<LeatherArmorMeta, LeatherArmorBuilder> {
/**
* Create a new ItemStackBuilder.
*
* @param material The material.
*/
public LeatherArmorBuilder(@NotNull final Material material) {
super(material);
}
/**
* Create a new ItemStackBuilder to modify an existing item.
*
* @param base The ItemStack to start with.
*/
public LeatherArmorBuilder(@NotNull final ItemStack base) {
super(base);
}
/**
* Set leather color.
*
* @param color The color.
* @return The builder.
*/
public LeatherArmorBuilder setColor(@NotNull final java.awt.Color color) {
Color bukkitColor = Color.fromRGB(color.getRed(), color.getGreen(), color.getBlue());
this.getMeta().setColor(bukkitColor);
return this;
}
}

View File

@@ -0,0 +1,28 @@
package com.willfp.eco.core.items.builder;
import com.willfp.eco.internal.items.AbstractItemStackBuilder;
import com.willfp.eco.util.SkullUtils;
import org.bukkit.Material;
import org.bukkit.inventory.meta.SkullMeta;
import org.jetbrains.annotations.NotNull;
public class SkullBuilder extends AbstractItemStackBuilder<SkullMeta, SkullBuilder> {
/**
* Create a new EnchantedBookBuilder.
*/
public SkullBuilder() {
super(Material.PLAYER_HEAD);
}
/**
* Set skull texture.
*
* @param texture The texture.
* @return The builder.
*/
public SkullBuilder setSkullTexture(@NotNull final String texture) {
SkullUtils.setSkullTexture(this.getMeta(), texture);
return this;
}
}

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.proxy;
package com.willfp.eco.core.proxy;
public interface AbstractProxy {

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.proxy;
package com.willfp.eco.core.proxy;
import lombok.experimental.UtilityClass;
import org.bukkit.Bukkit;

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.proxy;
package com.willfp.eco.core.proxy;
import org.jetbrains.annotations.NotNull;

View File

@@ -0,0 +1,92 @@
package com.willfp.eco.core.recipe;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.willfp.eco.core.EcoPlugin;
import com.willfp.eco.core.items.Items;
import com.willfp.eco.core.recipe.recipes.CraftingRecipe;
import com.willfp.eco.core.recipe.recipes.ShapedCraftingRecipe;
import lombok.experimental.UtilityClass;
import org.bukkit.NamespacedKey;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
@UtilityClass
@SuppressWarnings("deprecation")
public class Recipes {
/**
* Registry of all recipes.
*/
private static final BiMap<NamespacedKey, CraftingRecipe> RECIPES = HashBiMap.create();
/**
* Register a recipe.
*
* @param recipe The recipe.
*/
public void register(@NotNull final CraftingRecipe recipe) {
RECIPES.forcePut(recipe.getKey(), recipe);
}
/**
* Get recipe matching matrix.
*
* @param matrix The matrix to test.
* @return The match, or null if not found.
*/
@Nullable
public CraftingRecipe getMatch(@NotNull final ItemStack[] matrix) {
return RECIPES.values().stream().filter(recipe -> recipe.test(matrix)).findFirst().orElse(null);
}
/**
* Get recipe by key.
*
* @param key The key.
* @return The recipe, or null if not found.
*/
@Nullable
public CraftingRecipe getRecipe(@NotNull final NamespacedKey key) {
CraftingRecipe recipe = RECIPES.get(key);
if (recipe != null) {
return recipe;
}
if (key.getKey().contains("_displayed")) {
NamespacedKey otherKey = new NamespacedKey(key.getNamespace(), key.getKey().replace("_displayed", ""));
return RECIPES.get(otherKey);
}
return null;
}
/**
* Create and register recipe.
*
* @param plugin The plugin.
* @param key The key.
* @param output The output.
* @param recipeStrings The recipe.
* @return The recipe.
*/
public CraftingRecipe createAndRegisterRecipe(@NotNull final EcoPlugin plugin,
@NotNull final String key,
@NotNull final ItemStack output,
@NotNull final List<String> recipeStrings) {
ShapedCraftingRecipe.Builder builder = ShapedCraftingRecipe.builder(plugin, key).setOutput(output);
for (int i = 0; i < 9; i++) {
builder.setRecipePart(i, Items.lookup(recipeStrings.get(i)));
}
ShapedCraftingRecipe recipe = builder.build();
recipe.register();
return recipe;
}
}

View File

@@ -1,14 +1,15 @@
package com.willfp.eco.util.recipe.parts;
package com.willfp.eco.core.recipe.parts;
import com.willfp.eco.core.items.TestableItem;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.Nullable;
public class EmptyRecipePart implements RecipePart {
public class EmptyTestableItem implements TestableItem {
/**
* Create a new empty recipe part.
*/
public EmptyRecipePart() {
public EmptyTestableItem() {
}
@@ -24,7 +25,7 @@ public class EmptyRecipePart implements RecipePart {
}
@Override
public ItemStack getDisplayed() {
public ItemStack getItem() {
return new ItemStack(Material.AIR);
}
}

View File

@@ -1,12 +1,13 @@
package com.willfp.eco.util.recipe.parts;
package com.willfp.eco.core.recipe.parts;
import com.willfp.eco.core.items.TestableItem;
import lombok.Getter;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class SimpleRecipePart implements RecipePart {
public class MaterialTestableItem implements TestableItem {
/**
* The material.
*/
@@ -18,7 +19,7 @@ public class SimpleRecipePart implements RecipePart {
*
* @param material The material.
*/
public SimpleRecipePart(@NotNull final Material material) {
public MaterialTestableItem(@NotNull final Material material) {
this.material = material;
}
@@ -34,7 +35,7 @@ public class SimpleRecipePart implements RecipePart {
}
@Override
public ItemStack getDisplayed() {
public ItemStack getItem() {
return new ItemStack(material);
}
}

View File

@@ -0,0 +1,70 @@
package com.willfp.eco.core.recipe.parts;
import com.willfp.eco.core.items.TestableItem;
import com.willfp.eco.internal.Internals;
import lombok.Getter;
import org.apache.commons.lang.Validate;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
public class TestableStack implements TestableItem {
/**
* The item.
*/
private final TestableItem handle;
/**
* The amount.
*/
@Getter
private final int amount;
/**
* Create a new testable stack.
*
* @param item The item.
* @param amount The amount.
*/
public TestableStack(@NotNull final TestableItem item,
final int amount) {
Validate.isTrue(!(item instanceof TestableStack));
this.handle = item;
this.amount = amount;
}
/**
* If the item matches the material.
*
* @param itemStack The item to test.
* @return If the item is of the specified material.
*/
@Override
public boolean matches(@Nullable final ItemStack itemStack) {
return itemStack != null && handle.matches(itemStack) && itemStack.getAmount() >= amount;
}
@Override
public ItemStack getItem() {
ItemStack temp = handle.getItem().clone();
ItemMeta meta = temp.getItemMeta();
assert meta != null;
List<String> lore = meta.hasLore() ? meta.getLore() : new ArrayList<>();
assert lore != null;
lore.add("");
String add = Internals.getInstance().getPlugin().getLangYml().getString("multiple-in-craft");
add = add.replace("%amount%", String.valueOf(amount));
lore.add(add);
meta.setLore(lore);
temp.setItemMeta(meta);
temp.setAmount(amount);
return temp;
}
}

View File

@@ -0,0 +1,51 @@
package com.willfp.eco.core.recipe.recipes;
import com.willfp.eco.core.items.TestableItem;
import org.bukkit.NamespacedKey;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public interface CraftingRecipe {
/**
* Test matrix against recipe.
*
* @param matrix The matrix to check.
* @return If the recipe matches.
*/
boolean test(@NotNull ItemStack[] matrix);
/**
* Register the recipe.
*/
void register();
/**
* The recipe parts.
*
* @return The parts.
*/
List<TestableItem> getParts();
/**
* Get the recipe key.
*
* @return The key.
*/
NamespacedKey getKey();
/**
* Get the displayed recipe key.
*
* @return The key.
*/
NamespacedKey getDisplayedKey();
/**
* Get the recipe output.
*
* @return The output.
*/
ItemStack getOutput();
}

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.recipe.recipes;
package com.willfp.eco.core.recipe.recipes;
import lombok.Getter;

View File

@@ -1,24 +1,28 @@
package com.willfp.eco.util.recipe.recipes;
package com.willfp.eco.core.recipe.recipes;
import com.willfp.eco.util.internal.PluginDependent;
import com.willfp.eco.util.plugin.AbstractEcoPlugin;
import com.willfp.eco.util.recipe.Recipes;
import com.willfp.eco.util.recipe.parts.EmptyRecipePart;
import com.willfp.eco.util.recipe.parts.RecipePart;
import com.willfp.eco.core.EcoPlugin;
import com.willfp.eco.core.PluginDependent;
import com.willfp.eco.core.items.TestableItem;
import com.willfp.eco.core.recipe.Recipes;
import com.willfp.eco.core.recipe.parts.EmptyTestableItem;
import lombok.Getter;
import org.bukkit.Material;
import org.bukkit.Bukkit;
import org.bukkit.NamespacedKey;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.RecipeChoice;
import org.bukkit.inventory.ShapedRecipe;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public final class EcoShapedRecipe extends PluginDependent {
public final class ShapedCraftingRecipe extends PluginDependent<EcoPlugin> implements CraftingRecipe {
/**
* Recipe parts.
*/
@Getter
private final RecipePart[] parts;
private final List<TestableItem> parts;
/**
* The key of the recipe.
@@ -38,10 +42,10 @@ public final class EcoShapedRecipe extends PluginDependent {
@Getter
private final ItemStack output;
private EcoShapedRecipe(@NotNull final AbstractEcoPlugin plugin,
@NotNull final String key,
@NotNull final RecipePart[] parts,
@NotNull final ItemStack output) {
private ShapedCraftingRecipe(@NotNull final EcoPlugin plugin,
@NotNull final String key,
@NotNull final List<TestableItem> parts,
@NotNull final ItemStack output) {
super(plugin);
this.parts = parts;
@@ -50,36 +54,11 @@ public final class EcoShapedRecipe extends PluginDependent {
this.output = output;
}
/**
* Get item material at a specific index.
*
* @param index The index to check.
* @return The material.
*/
public Material getMaterialAtIndex(final int index) {
return parts[index].getDisplayed().getType();
}
/**
* Get "real" item at specific index.
*
* @param index The index to check.
* @return The item.
*/
public ItemStack getDisplayedAtIndex(final int index) {
return parts[index].getDisplayed();
}
/**
* Test matrix against recipe.
*
* @param matrix The matrix to check.
* @return If the recipe matches.
*/
@Override
public boolean test(@NotNull final ItemStack[] matrix) {
boolean matches = true;
for (int i = 0; i < 9; i++) {
if (!parts[i].matches(matrix[i])) {
if (!parts.get(i).matches(matrix[i])) {
matches = false;
}
}
@@ -87,20 +66,29 @@ public final class EcoShapedRecipe extends PluginDependent {
return matches;
}
/**
* Register the recipe.
*/
@Override
public void register() {
Recipes.register(this);
}
@Override
public String toString() {
return "EcoShapedRecipe{"
+ "parts=" + Arrays.toString(parts)
+ ", key='" + key + '\''
+ ", output=" + output
+ '}';
Bukkit.getServer().removeRecipe(this.getKey());
Bukkit.getServer().removeRecipe(this.getDisplayedKey());
ShapedRecipe shapedRecipe = new ShapedRecipe(this.getKey(), this.getOutput());
shapedRecipe.shape("012", "345", "678");
for (int i = 0; i < 9; i++) {
char character = String.valueOf(i).toCharArray()[0];
shapedRecipe.setIngredient(character, parts.get(i).getItem().getType());
}
ShapedRecipe displayedRecipe = new ShapedRecipe(this.getDisplayedKey(), this.getOutput());
displayedRecipe.shape("012", "345", "678");
for (int i = 0; i < 9; i++) {
char character = String.valueOf(i).toCharArray()[0];
displayedRecipe.setIngredient(character, new RecipeChoice.ExactChoice(parts.get(i).getItem()));
}
Bukkit.getServer().addRecipe(shapedRecipe);
Bukkit.getServer().addRecipe(displayedRecipe);
}
/**
@@ -110,7 +98,7 @@ public final class EcoShapedRecipe extends PluginDependent {
* @param key The recipe key.
* @return A new builder.
*/
public static Builder builder(@NotNull final AbstractEcoPlugin plugin,
public static Builder builder(@NotNull final EcoPlugin plugin,
@NotNull final String key) {
return new Builder(plugin, key);
}
@@ -119,7 +107,7 @@ public final class EcoShapedRecipe extends PluginDependent {
/**
* The recipe parts.
*/
private final RecipePart[] recipeParts = new RecipePart[9];
private final List<TestableItem> recipeParts = new ArrayList<>(Arrays.asList(null, null, null, null, null, null, null, null, null)); // Jank
/**
* The output of the recipe.
@@ -134,7 +122,7 @@ public final class EcoShapedRecipe extends PluginDependent {
/**
* The plugin that created the recipe.
*/
private final AbstractEcoPlugin plugin;
private final EcoPlugin plugin;
/**
* Create a new recipe builder.
@@ -142,7 +130,7 @@ public final class EcoShapedRecipe extends PluginDependent {
* @param plugin The plugin that owns the recipe.
* @param key The recipe key.
*/
private Builder(@NotNull final AbstractEcoPlugin plugin,
private Builder(@NotNull final EcoPlugin plugin,
@NotNull final String key) {
this.key = key;
this.plugin = plugin;
@@ -156,8 +144,8 @@ public final class EcoShapedRecipe extends PluginDependent {
* @return The builder.
*/
public Builder setRecipePart(@NotNull final RecipePosition position,
@NotNull final RecipePart part) {
this.recipeParts[position.getIndex()] = part;
@NotNull final TestableItem part) {
recipeParts.set(position.getIndex(), part);
return this;
}
@@ -169,8 +157,8 @@ public final class EcoShapedRecipe extends PluginDependent {
* @return The builder.
*/
public Builder setRecipePart(final int position,
@NotNull final RecipePart part) {
this.recipeParts[position] = part;
@NotNull final TestableItem part) {
recipeParts.set(position, part);
return this;
}
@@ -190,14 +178,14 @@ public final class EcoShapedRecipe extends PluginDependent {
*
* @return The built recipe.
*/
public EcoShapedRecipe build() {
public ShapedCraftingRecipe build() {
for (int i = 0; i < 9; i++) {
if (recipeParts[i] == null) {
recipeParts[i] = new EmptyRecipePart();
if (recipeParts.get(i) == null) {
recipeParts.set(i, new EmptyTestableItem());
}
}
return new EcoShapedRecipe(plugin, key.toLowerCase(), recipeParts, output);
return new ShapedCraftingRecipe(plugin, key.toLowerCase(), recipeParts, output);
}
}
}

View File

@@ -0,0 +1,59 @@
package com.willfp.eco.core.scheduling;
import org.bukkit.scheduler.BukkitTask;
import org.jetbrains.annotations.NotNull;
public interface RunnableTask extends Runnable {
/**
* Run the task.
*
* @return The created {@link BukkitTask}.
*/
@NotNull BukkitTask runTask();
/**
* Run the task asynchronously.
*
* @return The created {@link BukkitTask}
*/
@NotNull BukkitTask runTaskAsynchronously();
/**
* Run the task after a specified number of ticks.
*
* @param delay The number of ticks to wait.
* @return The created {@link BukkitTask}
*/
@NotNull BukkitTask runTaskLater(long delay);
/**
* Run the task asynchronously after a specified number of ticks.
*
* @param delay The number of ticks to wait.
* @return The created {@link BukkitTask}
*/
@NotNull BukkitTask runTaskLaterAsynchronously(long delay);
/**
* Run the task repeatedly on a timer.
*
* @param delay The delay before the task is first ran (in ticks).
* @param period The ticks elapsed before the task is ran again.
* @return The created {@link BukkitTask}
*/
@NotNull BukkitTask runTaskTimer(long delay, long period);
/**
* Run the task repeatedly on a timer asynchronously.
*
* @param delay The delay before the task is first ran (in ticks).
* @param period The ticks elapsed before the task is ran again.
* @return The created {@link BukkitTask}
*/
@NotNull BukkitTask runTaskTimerAsynchronously(long delay, long period);
/**
* Cancel the task.
*/
void cancel();
}

View File

@@ -1,6 +1,6 @@
package com.willfp.eco.util.bukkit.scheduling;
package com.willfp.eco.core.scheduling;
import com.willfp.eco.util.plugin.AbstractEcoPlugin;
import com.willfp.eco.core.EcoPlugin;
import org.bukkit.scheduler.BukkitTask;
import org.jetbrains.annotations.NotNull;
@@ -68,7 +68,7 @@ public interface Scheduler {
long repeat);
/**
* Cancel all running tasks from the linked {@link AbstractEcoPlugin}.
* Cancel all running tasks from the linked {@link EcoPlugin}.
*/
void cancelAll();
}

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.tuples;
package com.willfp.eco.core.tuples;
import lombok.Getter;
import lombok.Setter;

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.tuples;
package com.willfp.eco.core.tuples;
import lombok.Getter;
import lombok.Setter;

View File

@@ -0,0 +1,100 @@
package com.willfp.eco.core.web;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class Paste {
/**
* The contents.
*/
@Getter
private final String contents;
/**
* Create a new paste.
*
* @param contents The contents.
*/
public Paste(@NotNull final String contents) {
this.contents = contents;
}
/**
* Upload to hastebin and get a token.
*
* @return The token.
*/
public String getHastebinToken() {
try {
String url = "https://hastebin.com/documents";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(URLEncoder.encode(contents, StandardCharsets.UTF_8));
wr.flush();
wr.close();
BufferedReader iny = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String output;
StringBuilder responseBuilder = new StringBuilder();
while ((output = iny.readLine()) != null) {
responseBuilder.append(output);
}
iny.close();
String responseString = responseBuilder.toString();
responseString = responseString.replace("{\"key\":\"", "");
responseString = responseString.replace("\"}", "");
return responseString;
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
/**
* Get paste from hastebin.
*
* @param token The token.
* @return The paste.
*/
public static Paste getFromHastebin(@NotNull final String token) {
try {
StringBuilder result = new StringBuilder();
URL url = new URL("https://hastebin.com/raw/" + token);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
try (var reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()))) {
for (String line; (line = reader.readLine()) != null;) {
result.append(line);
}
}
return new Paste(URLDecoder.decode(result.toString(), StandardCharsets.UTF_8));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

View File

@@ -0,0 +1,18 @@
package com.willfp.eco.internal;
import com.willfp.eco.core.EcoPlugin;
import org.jetbrains.annotations.NotNull;
public abstract class Internals {
private static Internals internals;
public static void setInterfacing(@NotNull final Internals internals) {
Internals.internals = internals;
}
public abstract EcoPlugin getPlugin();
public static Internals getInstance() {
return internals;
}
}

View File

@@ -1,7 +1,7 @@
package com.willfp.eco.util.updater;
package com.willfp.eco.internal;
import com.willfp.eco.util.internal.PluginDependent;
import com.willfp.eco.util.plugin.AbstractEcoPlugin;
import com.willfp.eco.core.PluginDependent;
import com.willfp.eco.core.EcoPlugin;
import org.bukkit.util.Consumer;
import org.jetbrains.annotations.NotNull;
@@ -10,13 +10,13 @@ import java.io.InputStream;
import java.net.URL;
import java.util.Scanner;
public class UpdateChecker extends PluginDependent {
public class UpdateChecker extends PluginDependent<EcoPlugin> {
/**
* Create an update checker for the specified spigot resource id.
*
* @param plugin The plugin to check.
*/
public UpdateChecker(@NotNull final AbstractEcoPlugin plugin) {
public UpdateChecker(@NotNull final EcoPlugin plugin) {
super(plugin);
}

View File

@@ -1,9 +1,8 @@
package com.willfp.eco.internal.arrows;
import com.willfp.eco.util.internal.PluginDependent;
import com.willfp.eco.util.plugin.AbstractEcoPlugin;
import com.willfp.eco.core.EcoPlugin;
import com.willfp.eco.core.PluginDependent;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.EventHandler;
@@ -14,16 +13,14 @@ import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
public class ArrowDataListener extends PluginDependent implements Listener {
public class ArrowDataListener extends PluginDependent<EcoPlugin> implements Listener {
/**
* Listener to add metadata to arrows about the enchantments on the bow that shot them.
*
* @param plugin The {@link AbstractEcoPlugin} that registered the listener.
* @param plugin The {@link EcoPlugin} that registered the listener.
*/
@ApiStatus.Internal
public ArrowDataListener(@NotNull final AbstractEcoPlugin plugin) {
public ArrowDataListener(@NotNull final EcoPlugin plugin) {
super(plugin);
}
@@ -34,15 +31,13 @@ public class ArrowDataListener extends PluginDependent implements Listener {
*/
@EventHandler(priority = EventPriority.LOWEST)
public void onLaunch(final ProjectileLaunchEvent event) {
if (!(event.getEntity() instanceof Arrow)) {
return;
}
if (!(event.getEntity().getShooter() instanceof LivingEntity)) {
if (!(event.getEntity() instanceof Arrow arrow)) {
return;
}
Arrow arrow = (Arrow) event.getEntity();
LivingEntity entity = (LivingEntity) arrow.getShooter();
if (!(arrow.getShooter() instanceof LivingEntity entity)) {
return;
}
if (entity.getEquipment() == null) {
return;
@@ -54,7 +49,6 @@ public class ArrowDataListener extends PluginDependent implements Listener {
return;
}
Map<Enchantment, Integer> enchantments = item.getItemMeta().getEnchants();
arrow.setMetadata("enchantments", this.getPlugin().getMetadataValueFactory().create(enchantments));
arrow.setMetadata("shot-from", this.getPlugin().getMetadataValueFactory().create(item));
}
}

View File

@@ -0,0 +1,166 @@
package com.willfp.eco.internal.commands;
import com.willfp.eco.core.EcoPlugin;
import com.willfp.eco.core.PluginDependent;
import com.willfp.eco.core.command.CommandBase;
import com.willfp.eco.core.command.CommandHandler;
import com.willfp.eco.core.command.TabCompleteHandler;
import com.willfp.eco.internal.commands.util.CommandUtils;
import lombok.AccessLevel;
import lombok.Getter;
import org.bukkit.command.CommandSender;
import org.bukkit.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public abstract class HandledCommand extends PluginDependent<EcoPlugin> implements CommandBase {
/**
* The name of the command.
*/
@Getter
private final String name;
/**
* The permission required to execute the command.
* <p>
* Written out as a string for flexibility with subclasses.
*/
@Getter
private final String permission;
/**
* Should the command only be allowed to be executed by players?
* <p>
* In other worlds, only allowed to be executed by console.
*/
@Getter
private final boolean playersOnly;
/**
* All subcommands for the command.
*/
@Getter(AccessLevel.PROTECTED)
private final List<CommandBase> subcommands;
/**
* Create a new command.
* <p>
* The name cannot be the same as an existing command as this will conflict.
*
* @param plugin Instance of a plugin.
* @param name The name used in execution.
* @param permission The permission required to execute the command.
* @param playersOnly If only players should be able to execute this command.
*/
protected HandledCommand(@NotNull final EcoPlugin plugin,
@NotNull final String name,
@NotNull final String permission,
final boolean playersOnly) {
super(plugin);
this.name = name;
this.permission = permission;
this.playersOnly = playersOnly;
this.subcommands = new ArrayList<>();
}
/**
* Add a subcommand to the command.
*
* @param subcommand The subcommand.
* @return The parent command.
*/
@Override
public final CommandBase addSubcommand(@NotNull final CommandBase subcommand) {
subcommands.add(subcommand);
return this;
}
/**
* Handle the command.
*
* @param sender The sender.
* @param args The arguments.
*/
protected final void handle(@NotNull final CommandSender sender,
@NotNull final String[] args) {
if (!CommandUtils.canExecute(sender, this, this.getPlugin())) {
return;
}
if (args.length > 0) {
for (CommandBase subcommand : this.getSubcommands()) {
if (subcommand.getName().equalsIgnoreCase(args[0])) {
if (!CommandUtils.canExecute(sender, subcommand, this.getPlugin())) {
return;
}
((HandledCommand) subcommand).handle(sender, Arrays.copyOfRange(args, 1, args.length));
return;
}
}
}
this.getHandler().onExecute(sender, Arrays.asList(args));
}
/**
* Handle the tab completion.
*
* @param sender The sender.
* @param args The arguments.
*/
protected final List<String> handleTabCompletion(@NotNull final CommandSender sender,
@NotNull final String[] args) {
if (!sender.hasPermission(this.getPermission())) {
return null;
}
if (args.length == 1) {
List<String> completions = new ArrayList<>();
StringUtil.copyPartialMatches(
args[0],
this.getSubcommands().stream().map(CommandBase::getName).collect(Collectors.toList()),
completions
);
Collections.sort(completions);
if (!completions.isEmpty()) {
return completions;
}
}
if (args.length >= 2) {
HandledCommand command = null;
for (CommandBase subcommand : this.getSubcommands()) {
if (args[0].equalsIgnoreCase(subcommand.getName())) {
command = (HandledCommand) subcommand;
}
}
if (command != null) {
return command.handleTabCompletion(sender, Arrays.copyOfRange(args, 1, args.length));
}
}
return this.getTabCompleter().tabComplete(sender, Arrays.asList(args));
}
@Override
public abstract CommandHandler getHandler();
@Override
public TabCompleteHandler getTabCompleter() {
return (sender, args) -> new ArrayList<>();
}
}

View File

@@ -0,0 +1,27 @@
package com.willfp.eco.internal.commands.util;
import com.willfp.eco.core.EcoPlugin;
import com.willfp.eco.core.command.CommandBase;
import lombok.experimental.UtilityClass;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
@UtilityClass
public class CommandUtils {
public boolean canExecute(@NotNull final CommandSender sender,
@NotNull final CommandBase command,
@NotNull final EcoPlugin plugin) {
if (command.isPlayersOnly() && !(sender instanceof Player)) {
sender.sendMessage(plugin.getLangYml().getMessage("not-player"));
return false;
}
if (!sender.hasPermission(command.getPermission()) && sender instanceof Player) {
sender.sendMessage(plugin.getLangYml().getNoPermission());
return false;
}
return true;
}
}

View File

@@ -0,0 +1,39 @@
package com.willfp.eco.internal.config;
import java.io.File;
import java.io.IOException;
public interface LoadableConfig {
/**
* Create the file.
*/
void createFile();
/**
* Get resource path as relative to base directory.
*
* @return The resource path.
*/
String getResourcePath();
/**
* Save the config.
*
* @throws IOException If error in saving.
*/
void save() throws IOException;
/**
* Get the config file.
*
* @return The file.
*/
File getConfigFile();
/**
* Get the config name (including extension)
*
* @return The name.
*/
String getName();
}

View File

@@ -0,0 +1,16 @@
package com.willfp.eco.internal.config.json;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
public class JsonConfigSection extends JsonConfigWrapper {
/**
* Config section.
*
* @param values The values.
*/
public JsonConfigSection(@NotNull final Map<String, Object> values) {
this.init(values);
}
}

View File

@@ -0,0 +1,345 @@
package com.willfp.eco.internal.config.json;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.willfp.eco.core.config.Config;
import com.willfp.eco.core.config.JSONConfig;
import com.willfp.eco.util.StringUtils;
import lombok.Getter;
import org.apache.commons.lang.Validate;
import org.bukkit.configuration.ConfigurationSection;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
@SuppressWarnings({"unchecked", "unused"})
public abstract class JsonConfigWrapper implements JSONConfig, Cloneable {
/**
* The linked {@link ConfigurationSection} where values are physically stored.
*/
@Getter
private final Gson handle = new GsonBuilder().setPrettyPrinting().create();
/**
* All stored values.
*/
@Getter
private final Map<String, Object> values = new HashMap<>();
/**
* All cached values.
*/
@Getter
private final Map<String, Object> cache = new HashMap<>();
/**
* Abstract config.
*/
protected JsonConfigWrapper() {
}
public void init(@NotNull final Map<String, Object> values) {
this.values.clear();
this.values.putAll(values);
}
@Override
public final void clearCache() {
cache.clear();
}
@Override
public String toPlaintext() {
return this.getHandle().toJson(this.getValues());
}
@Override
public boolean has(@NotNull final String path) {
return getOfKnownType(path, Object.class) != null;
}
@Nullable
protected <T> T getOfKnownType(@NotNull final String path,
@NotNull final Class<T> clazz) {
return getOfKnownType(path, clazz, true);
}
@Nullable
protected <T> T getOfKnownType(@NotNull final String path,
@NotNull final Class<T> clazz,
final boolean isBase) {
String closestPath = path;
if (cache.containsKey(path) && isBase) {
return (T) cache.get(path);
}
if (path.contains(".")) {
String[] split = path.split("\\.");
closestPath = split[0];
}
if (values.get(closestPath) instanceof Map && !path.equals(closestPath)) {
JsonConfigSection section = new JsonConfigSection((Map<String, Object>) values.get(closestPath));
return section.getOfKnownType(path.substring(closestPath.length() + 1), clazz, false);
} else {
if (values.containsKey(closestPath)) {
return (T) values.get(closestPath);
} else {
return null;
}
}
}
@NotNull
@Override
public List<String> getKeys(final boolean deep) {
if (deep) {
return new ArrayList<>(getDeepKeys(new HashSet<>(), ""));
} else {
return new ArrayList<>(values.keySet());
}
}
protected Set<String> getDeepKeys(@NotNull final Set<String> list,
@NotNull final String root) {
for (String key : values.keySet()) {
list.add(root + key);
if (values.get(key) instanceof Map) {
JsonConfigSection section = new JsonConfigSection((Map<String, Object>) values.get(key));
list.addAll(section.getDeepKeys(list, root + key + "."));
}
}
return list;
}
@Override
@Nullable
public Object get(@NotNull final String path) {
return getOfKnownType(path, Object.class);
}
@Override
public void set(@NotNull final String path,
@Nullable final Object object) {
setRecursively(path, object, true);
clearCache();
}
protected void setRecursively(@NotNull final String path,
@Nullable final Object object,
final boolean isBase) {
String closestPath = path;
if (path.contains(".")) {
String[] split = path.split("\\.");
closestPath = split[0];
}
if (values.get(closestPath) instanceof Map && !path.equals(closestPath)) {
JsonConfigSection section = new JsonConfigSection((Map<String, Object>) values.get(closestPath));
section.setRecursively(path.substring(closestPath.length() + 1), object, false);
values.put(closestPath, section.getValues());
} else {
Object obj = object;
if (object instanceof JSONConfig) {
obj = ((JsonConfigWrapper) object).getValues();
}
values.put(path, obj);
}
}
@Override
@NotNull
public Config getSubsection(@NotNull final String path) {
Config subsection = getSubsectionOrNull(path);
Validate.notNull(subsection);
return subsection;
}
@Override
@Nullable
public Config getSubsectionOrNull(@NotNull final String path) {
if (values.containsKey(path)) {
Map<String, Object> subsection = (Map<String, Object>) values.get(path);
return new JsonConfigSection(subsection);
} else {
return null;
}
}
@Override
@NotNull
public List<JSONConfig> getSubsections(@NotNull final String path) {
List<JSONConfig> subsections = getSubsectionsOrNull(path);
Validate.notNull(subsections);
return subsections;
}
@Override
@Nullable
public List<JSONConfig> getSubsectionsOrNull(@NotNull final String path) {
List<Map<String, Object>> maps = (List<Map<String, Object>>) getOfKnownType(path, Object.class);
if (maps == null) {
return null;
}
List<JSONConfig> configs = new ArrayList<>();
for (Map<String, Object> map : maps) {
configs.add(new JsonConfigSection(map));
}
return configs;
}
@Override
public int getInt(@NotNull final String path) {
// ew
return Objects.requireNonNullElse(getOfKnownType(path, Double.class), 0D).intValue();
}
@Override
@Nullable
public Integer getIntOrNull(@NotNull final String path) {
if (has(path)) {
return getInt(path);
} else {
return null;
}
}
@Override
public int getInt(@NotNull final String path,
final int def) {
return Objects.requireNonNullElse(getOfKnownType(path, Integer.class), def);
}
@Override
@NotNull
public List<Integer> getInts(@NotNull final String path) {
return (List<Integer>) Objects.requireNonNullElse(getOfKnownType(path, Object.class), new ArrayList<>());
}
@Override
@Nullable
public List<Integer> getIntsOrNull(@NotNull final String path) {
if (has(path)) {
return getInts(path);
} else {
return null;
}
}
@Override
public boolean getBool(@NotNull final String path) {
return Objects.requireNonNullElse(getOfKnownType(path, Boolean.class), false);
}
@Override
@Nullable
public Boolean getBoolOrNull(@NotNull final String path) {
if (has(path)) {
return getBool(path);
} else {
return null;
}
}
@Override
@NotNull
public List<Boolean> getBools(@NotNull final String path) {
return (List<Boolean>) Objects.requireNonNullElse(getOfKnownType(path, Object.class), new ArrayList<>());
}
@Override
@Nullable
public List<Boolean> getBoolsOrNull(@NotNull final String path) {
if (has(path)) {
return getBools(path);
} else {
return null;
}
}
@Override
@NotNull
public String getString(@NotNull final String path) {
return StringUtils.translate(Objects.requireNonNullElse(getOfKnownType(path, String.class), ""));
}
@Override
@Nullable
public String getStringOrNull(@NotNull final String path) {
if (has(path)) {
return getString(path);
} else {
return null;
}
}
@Override
@NotNull
public List<String> getStrings(@NotNull final String path) {
return StringUtils.translateList((List<String>) Objects.requireNonNullElse(getOfKnownType(path, Object.class), new ArrayList<>()));
}
@Override
@Nullable
public List<String> getStringsOrNull(@NotNull final String path) {
if (has(path)) {
return getStrings(path);
} else {
return null;
}
}
@Override
public double getDouble(@NotNull final String path) {
return Objects.requireNonNullElse(getOfKnownType(path, Double.class), 0D);
}
@Override
@Nullable
public Double getDoubleOrNull(@NotNull final String path) {
if (has(path)) {
return getDouble(path);
} else {
return null;
}
}
@Override
@NotNull
public List<Double> getDoubles(@NotNull final String path) {
return (List<Double>) Objects.requireNonNullElse(getOfKnownType(path, Object.class), new ArrayList<>());
}
@Override
@Nullable
public List<Double> getDoublesOrNull(@NotNull final String path) {
if (has(path)) {
return getDoubles(path);
} else {
return null;
}
}
@Override
public JSONConfig clone() {
return new JsonConfigSection(new HashMap<>(this.getValues()));
}
}

View File

@@ -1,36 +1,38 @@
package com.willfp.eco.internal.config;
package com.willfp.eco.internal.config.json;
import com.willfp.eco.util.plugin.AbstractEcoPlugin;
import com.willfp.eco.core.EcoPlugin;
import com.willfp.eco.internal.config.LoadableConfig;
import lombok.AccessLevel;
import lombok.Getter;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.HashMap;
public abstract class AbstractConfig extends AbstractUndefinedConfig<YamlConfiguration> {
@SuppressWarnings({"unchecked", "unused"})
public abstract class LoadableJsonConfig extends JsonConfigWrapper implements LoadableConfig {
/**
* The physical config file, as stored on disk.
*/
@Getter(AccessLevel.PROTECTED)
@Getter
private final File configFile;
/**
* Plugin handle.
*/
@Getter(AccessLevel.PROTECTED)
private final AbstractEcoPlugin plugin;
private final EcoPlugin plugin;
/**
* The full name of the config file (eg config.yml).
* The full name of the config file (eg config.json).
*/
@Getter
private final String name;
@@ -55,13 +57,12 @@ public abstract class AbstractConfig extends AbstractUndefinedConfig<YamlConfigu
* @param subDirectoryPath The subdirectory path.
* @param source The class that owns the resource.
*/
protected AbstractConfig(@NotNull final String configName,
@NotNull final AbstractEcoPlugin plugin,
@NotNull final String subDirectoryPath,
@NotNull final Class<?> source) {
super(configName);
protected LoadableJsonConfig(@NotNull final String configName,
@NotNull final EcoPlugin plugin,
@NotNull final String subDirectoryPath,
@NotNull final Class<?> source) {
this.plugin = plugin;
this.name = configName + ".yml";
this.name = configName + ".json";
this.source = source;
this.subDirectoryPath = subDirectoryPath;
@@ -75,10 +76,18 @@ public abstract class AbstractConfig extends AbstractUndefinedConfig<YamlConfigu
}
this.configFile = new File(directory, this.name);
init(YamlConfiguration.loadConfiguration(configFile));
try {
init(this.configFile);
} catch (IOException e) {
e.printStackTrace();
}
plugin.getConfigHandler().addConfig(this);
}
private void createFile() {
@Override
public void createFile() {
String resourcePath = getResourcePath();
InputStream in = source.getResourceAsStream(resourcePath);
@@ -110,7 +119,8 @@ public abstract class AbstractConfig extends AbstractUndefinedConfig<YamlConfigu
*
* @return The resource path.
*/
protected String getResourcePath() {
@Override
public String getResourcePath() {
String resourcePath;
if (subDirectoryPath.isEmpty()) {
@@ -123,36 +133,23 @@ public abstract class AbstractConfig extends AbstractUndefinedConfig<YamlConfigu
}
/**
* Get YamlConfiguration as found in jar.
* Save the config.
*
* @return The YamlConfiguration.
* @throws IOException If error in saving.
*/
protected YamlConfiguration getConfigInJar() {
InputStream newIn = source.getResourceAsStream(getResourcePath());
if (newIn == null) {
throw new NullPointerException(name + " is null?");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(newIn, StandardCharsets.UTF_8));
YamlConfiguration newConfig = new YamlConfiguration();
try {
newConfig.load(reader);
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
}
return newConfig;
@Override
public void save() throws IOException {
configFile.delete();
Files.write(configFile.toPath(), this.toPlaintext().getBytes(), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
}
/**
* Get config handle.
* Initialize the config.
*
* @return The config.
* @param file The config file.
* @throws FileNotFoundException If the file doesn't exist.
*/
@Deprecated
public YamlConfiguration getConfig() {
return (YamlConfiguration) super.config;
public void init(@NotNull final File file) throws FileNotFoundException {
super.init(this.getHandle().fromJson(new FileReader(file), HashMap.class));
}
}

View File

@@ -0,0 +1,108 @@
package com.willfp.eco.internal.config.updating;
import com.willfp.eco.core.EcoPlugin;
import com.willfp.eco.core.PluginDependent;
import com.willfp.eco.core.config.ConfigHandler;
import com.willfp.eco.core.config.ConfigUpdater;
import com.willfp.eco.internal.config.LoadableConfig;
import com.willfp.eco.internal.config.updating.exceptions.InvalidUpdatableClassException;
import com.willfp.eco.internal.config.updating.exceptions.InvalidUpdateMethodException;
import com.willfp.eco.internal.config.yaml.UpdatableYamlConfig;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class EcoConfigHandler extends PluginDependent<EcoPlugin> implements ConfigHandler {
/**
* A set of all configs that can be saved.
*/
private final List<LoadableConfig> configs = new ArrayList<>();
/**
* A set of all classes that can be updated.
*/
private final Set<Class<?>> updatableClasses = new HashSet<>();
/**
* Creates a new config handler and links it to an {@link EcoPlugin}.
*
* @param plugin The plugin to manage.
*/
public EcoConfigHandler(@NotNull final EcoPlugin plugin) {
super(plugin);
}
@Override
public void callUpdate() {
updatableClasses.forEach(clazz -> Arrays.stream(clazz.getDeclaredMethods()).forEach(method -> {
if (method.isAnnotationPresent(ConfigUpdater.class)) {
if (!Modifier.isStatic(method.getModifiers())) {
throw new InvalidUpdateMethodException("Update method must be static.");
}
try {
if (method.getParameterCount() == 0) {
method.invoke(null);
} else if (method.getParameterCount() == 1) {
method.invoke(null, this.getPlugin());
} else {
throw new InvalidUpdateMethodException("Update method must have 0 parameters or a plugin parameter.");
}
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
throw new InvalidUpdateMethodException("Update method generated an exception.");
}
}
}));
}
@Override
public void registerUpdatableClass(@NotNull final Class<?> updatableClass) {
boolean isValid = false;
for (Method method : updatableClass.getDeclaredMethods()) {
if (Modifier.isStatic(method.getModifiers()) && (method.getParameterCount() == 0 || method.getParameterCount() == 1) && method.isAnnotationPresent(ConfigUpdater.class)) {
isValid = true;
break;
}
}
if (!isValid) {
throw new InvalidUpdatableClassException("Registered updatable class " + updatableClass + " must have an annotated static method with no modifiers.");
}
updatableClasses.add(updatableClass);
}
@Override
public void saveAllConfigs() {
try {
for (LoadableConfig config : configs) {
config.save();
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void addConfig(@NotNull final LoadableConfig config) {
configs.add(config);
}
@Override
public void updateConfigs() {
for (LoadableConfig config : configs) {
if (config instanceof UpdatableYamlConfig updatableYamlConfig) {
updatableYamlConfig.update();
}
}
}
}

View File

@@ -1,11 +1,11 @@
package com.willfp.eco.util.config.updating.exceptions;
package com.willfp.eco.internal.config.updating.exceptions;
import com.willfp.eco.util.config.updating.ConfigHandler;
import com.willfp.eco.internal.config.updating.EcoConfigHandler;
import org.jetbrains.annotations.NotNull;
public class InvalidUpdatableClassException extends RuntimeException {
/**
* Called when an updatable class is registered into an {@link ConfigHandler}.
* Called when an updatable class is registered into an {@link EcoConfigHandler}.
*
* @param message The error message.
*/

View File

@@ -1,4 +1,4 @@
package com.willfp.eco.util.config.updating.exceptions;
package com.willfp.eco.internal.config.updating.exceptions;
import org.jetbrains.annotations.NotNull;

View File

@@ -0,0 +1,124 @@
package com.willfp.eco.internal.config.yaml;
import com.willfp.eco.core.EcoPlugin;
import com.willfp.eco.internal.config.LoadableConfig;
import lombok.AccessLevel;
import lombok.Getter;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public abstract class LoadableYamlConfig extends YamlConfigWrapper<YamlConfiguration> implements LoadableConfig {
/**
* The physical config file, as stored on disk.
*/
@Getter
private final File configFile;
/**
* Plugin handle.
*/
@Getter(AccessLevel.PROTECTED)
private final EcoPlugin plugin;
/**
* The full name of the config file (eg config.yml).
*/
@Getter
private final String name;
/**
* The subdirectory path.
*/
@Getter(AccessLevel.PROTECTED)
private final String subDirectoryPath;
/**
* The provider of the config.
*/
@Getter(AccessLevel.PROTECTED)
private final Class<?> source;
/**
* Abstract config.
*
* @param configName The name of the config
* @param plugin The plugin.
* @param subDirectoryPath The subdirectory path.
* @param source The class that owns the resource.
*/
protected LoadableYamlConfig(@NotNull final String configName,
@NotNull final EcoPlugin plugin,
@NotNull final String subDirectoryPath,
@NotNull final Class<?> source) {
this.plugin = plugin;
this.name = configName + ".yml";
this.source = source;
this.subDirectoryPath = subDirectoryPath;
File directory = new File(this.getPlugin().getDataFolder(), subDirectoryPath);
if (!directory.exists()) {
directory.mkdirs();
}
if (!new File(directory, this.name).exists()) {
createFile();
}
this.configFile = new File(directory, this.name);
init(YamlConfiguration.loadConfiguration(configFile));
}
@Override
public void createFile() {
String resourcePath = getResourcePath();
InputStream in = source.getResourceAsStream(resourcePath);
File outFile = new File(this.getPlugin().getDataFolder(), resourcePath);
int lastIndex = resourcePath.lastIndexOf('/');
File outDir = new File(this.getPlugin().getDataFolder(), resourcePath.substring(0, Math.max(lastIndex, 0)));
if (!outDir.exists()) {
outDir.mkdirs();
}
try {
if (!outFile.exists()) {
OutputStream out = new FileOutputStream(outFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
}
} catch (IOException ignored) {
}
plugin.getConfigHandler().addConfig(this);
}
@Override
public String getResourcePath() {
String resourcePath;
if (subDirectoryPath.isEmpty()) {
resourcePath = name;
} else {
resourcePath = subDirectoryPath + name;
}
return "/" + resourcePath;
}
@Override
public void save() throws IOException {
this.getHandle().save(this.getConfigFile());
}
}

View File

@@ -1,16 +1,20 @@
package com.willfp.eco.internal.config;
package com.willfp.eco.internal.config.yaml;
import com.willfp.eco.util.plugin.AbstractEcoPlugin;
import com.willfp.eco.core.EcoPlugin;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public abstract class AbstractUpdatableConfig extends AbstractConfig {
public abstract class UpdatableYamlConfig extends LoadableYamlConfig {
/**
* Whether keys not in the base config should be removed on update.
*/
@@ -31,12 +35,12 @@ public abstract class AbstractUpdatableConfig extends AbstractConfig {
* @param removeUnused Whether keys not present in the default config should be removed on update.
* @param updateBlacklist Substring of keys to not add/remove keys for.
*/
protected AbstractUpdatableConfig(@NotNull final String configName,
@NotNull final AbstractEcoPlugin plugin,
@NotNull final String subDirectoryPath,
@NotNull final Class<?> source,
final boolean removeUnused,
@NotNull final String... updateBlacklist) {
protected UpdatableYamlConfig(@NotNull final String configName,
@NotNull final EcoPlugin plugin,
@NotNull final String subDirectoryPath,
@NotNull final Class<?> source,
final boolean removeUnused,
@NotNull final String... updateBlacklist) {
super(configName, plugin, subDirectoryPath, source);
this.removeUnused = removeUnused;
this.updateBlacklist = new ArrayList<>(Arrays.asList(updateBlacklist));
@@ -53,35 +57,54 @@ public abstract class AbstractUpdatableConfig extends AbstractConfig {
public void update() {
super.clearCache();
try {
config.load(this.getConfigFile());
this.getHandle().load(this.getConfigFile());
YamlConfiguration newConfig = this.getConfigInJar();
if (newConfig.getKeys(true).equals(config.getKeys(true))) {
if (newConfig.getKeys(true).equals(this.getHandle().getKeys(true))) {
return;
}
newConfig.getKeys(true).forEach((s -> {
if (!config.getKeys(true).contains(s)) {
if (!this.getHandle().getKeys(true).contains(s)) {
if (updateBlacklist.stream().noneMatch(s::contains)) {
config.set(s, newConfig.get(s));
this.getHandle().set(s, newConfig.get(s));
}
}
}));
if (this.removeUnused) {
config.getKeys(true).forEach((s -> {
this.getHandle().getKeys(true).forEach((s -> {
if (!newConfig.getKeys(true).contains(s)) {
if (updateBlacklist.stream().noneMatch(s::contains)) {
config.set(s, null);
this.getHandle().set(s, null);
}
}
}));
}
config.save(this.getConfigFile());
this.getHandle().save(this.getConfigFile());
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
}
}
public YamlConfiguration getConfigInJar() {
InputStream newIn = this.getSource().getResourceAsStream(getResourcePath());
if (newIn == null) {
throw new NullPointerException(this.getName() + " is null?");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(newIn, StandardCharsets.UTF_8));
YamlConfiguration newConfig = new YamlConfiguration();
try {
newConfig.load(reader);
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
}
return newConfig;
}
}

View File

@@ -0,0 +1,15 @@
package com.willfp.eco.internal.config.yaml;
import org.bukkit.configuration.ConfigurationSection;
import org.jetbrains.annotations.NotNull;
public class YamlConfigSection extends YamlConfigWrapper<ConfigurationSection> {
/**
* Config section.
*
* @param section The section.
*/
public YamlConfigSection(@NotNull final ConfigurationSection section) {
this.init(section);
}
}

View File

@@ -1,11 +1,11 @@
package com.willfp.eco.internal.config;
package com.willfp.eco.internal.config.yaml;
import com.willfp.eco.util.SerializationUtils;
import com.willfp.eco.core.config.Config;
import com.willfp.eco.util.StringUtils;
import com.willfp.eco.util.config.Config;
import com.willfp.eco.util.serialization.EcoSerializable;
import lombok.Getter;
import org.apache.commons.lang.Validate;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.MemorySection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -15,12 +15,13 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
@SuppressWarnings({"unchecked", "unused", "DeprecatedIsStillUsed"})
public abstract class AbstractUndefinedConfig<T extends ConfigurationSection> implements Config {
@SuppressWarnings({"unchecked", "unused"})
public abstract class YamlConfigWrapper<T extends ConfigurationSection> implements Config {
/**
* The linked {@link MemorySection} where values are physically stored.
* The linked {@link ConfigurationSection} where values are physically stored.
*/
protected T config = null;
@Getter
private T handle = null;
/**
* Cached values for faster reading.
@@ -29,18 +30,25 @@ public abstract class AbstractUndefinedConfig<T extends ConfigurationSection> im
/**
* Abstract config.
*
* @param configName The name of the config
*/
protected AbstractUndefinedConfig(@NotNull final String configName) {
protected YamlConfigWrapper() {
}
protected Config init(@NotNull final T config) {
this.config = config;
this.handle = config;
return this;
}
@Override
public String toPlaintext() {
YamlConfiguration temp = new YamlConfiguration();
for (String key : handle.getKeys(true)) {
temp.set(key, handle.get(key));
}
return temp.saveToString();
}
@Override
public final void clearCache() {
cache.clear();
@@ -48,98 +56,50 @@ public abstract class AbstractUndefinedConfig<T extends ConfigurationSection> im
@Override
public boolean has(@NotNull final String path) {
return config.contains(path);
return handle.contains(path);
}
@NotNull
@Override
public List<String> getKeys(final boolean deep) {
return new ArrayList<>(config.getKeys(deep));
return new ArrayList<>(handle.getKeys(deep));
}
@Override
@Nullable
public Object get(@NotNull final String path) {
return handle.get(path);
}
@Override
public void set(@NotNull final String path,
@NotNull final EcoSerializable<?> object) {
Config serializedConfig = object.serialize();
for (String key : serializedConfig.getKeys(true)) {
Object raw = serializedConfig.getRaw(key);
config.set(path + "." + key, raw);
cache.put(path + "." + key, raw);
}
}
@Override
@Nullable
public Object getRaw(@NotNull final String path) {
return config.get(path);
}
@Override
@NotNull
public <T extends EcoSerializable<T>> T get(@NotNull final String path,
@NotNull final Class<T> clazz) {
T object = getOrNull(path, clazz);
if (object == null) {
throw new NullPointerException("Object cannot be null!");
} else {
return object;
}
}
@Override
@Nullable
public <T extends EcoSerializable<T>> T getOrNull(@NotNull final String path,
@NotNull final Class<T> clazz) {
if (cache.containsKey(path)) {
return (T) cache.get(path);
} else {
Config section = getSubsectionOrNull(path);
if (section == null) {
return null;
}
cache.put(path, SerializationUtils.deserialize(section, clazz));
return getOrNull(path, clazz);
}
}
@Override
@NotNull
@Deprecated
public ConfigurationSection getSection(@NotNull final String path) {
ConfigurationSection section = getSectionOrNull(path);
if (section == null) {
throw new NullPointerException("Section cannot be null!");
} else {
return section;
}
}
@Override
@Nullable
@Deprecated
public ConfigurationSection getSectionOrNull(@NotNull final String path) {
if (cache.containsKey(path)) {
return (ConfigurationSection) cache.get(path);
} else {
cache.put(path, config.getConfigurationSection(path));
return getSectionOrNull(path);
}
@Nullable final Object object) {
cache.remove(path);
handle.set(path, object);
}
@Override
@NotNull
public Config getSubsection(@NotNull final String path) {
return new ConfigSection(this.getSection(path));
Config subsection = getSubsectionOrNull(path);
Validate.notNull(subsection);
return subsection;
}
@Override
@Nullable
public Config getSubsectionOrNull(@NotNull final String path) {
ConfigurationSection section = this.getSectionOrNull(path);
if (section == null) {
return null;
if (cache.containsKey(path)) {
return (Config) cache.get(path);
} else {
ConfigurationSection raw = handle.getConfigurationSection(path);
if (raw == null) {
cache.put(path, null);
} else {
cache.put(path, new YamlConfigSection(raw));
}
return getSubsectionOrNull(path);
}
return new ConfigSection(section);
}
@Override
@@ -147,7 +107,7 @@ public abstract class AbstractUndefinedConfig<T extends ConfigurationSection> im
if (cache.containsKey(path)) {
return (int) cache.get(path);
} else {
cache.put(path, config.getInt(path, 0));
cache.put(path, handle.getInt(path, 0));
return getInt(path);
}
}
@@ -168,7 +128,7 @@ public abstract class AbstractUndefinedConfig<T extends ConfigurationSection> im
if (cache.containsKey(path)) {
return (int) cache.get(path);
} else {
cache.put(path, config.getInt(path, def));
cache.put(path, handle.getInt(path, def));
return getInt(path);
}
}
@@ -179,7 +139,7 @@ public abstract class AbstractUndefinedConfig<T extends ConfigurationSection> im
if (cache.containsKey(path)) {
return (List<Integer>) cache.get(path);
} else {
cache.put(path, has(path) ? new ArrayList<>(config.getIntegerList(path)) : new ArrayList<>());
cache.put(path, has(path) ? new ArrayList<>(handle.getIntegerList(path)) : new ArrayList<>());
return getInts(path);
}
}
@@ -199,7 +159,7 @@ public abstract class AbstractUndefinedConfig<T extends ConfigurationSection> im
if (cache.containsKey(path)) {
return (boolean) cache.get(path);
} else {
cache.put(path, config.getBoolean(path));
cache.put(path, handle.getBoolean(path));
return getBool(path);
}
}
@@ -220,7 +180,7 @@ public abstract class AbstractUndefinedConfig<T extends ConfigurationSection> im
if (cache.containsKey(path)) {
return (List<Boolean>) cache.get(path);
} else {
cache.put(path, has(path) ? new ArrayList<>(config.getBooleanList(path)) : new ArrayList<>());
cache.put(path, has(path) ? new ArrayList<>(handle.getBooleanList(path)) : new ArrayList<>());
return getBools(path);
}
}
@@ -241,7 +201,7 @@ public abstract class AbstractUndefinedConfig<T extends ConfigurationSection> im
if (cache.containsKey(path)) {
return (String) cache.get(path);
} else {
cache.put(path, StringUtils.translate(Objects.requireNonNull(config.getString(path, ""))));
cache.put(path, StringUtils.translate(Objects.requireNonNull(handle.getString(path, ""))));
return getString(path);
}
}
@@ -260,9 +220,9 @@ public abstract class AbstractUndefinedConfig<T extends ConfigurationSection> im
@NotNull
public List<String> getStrings(@NotNull final String path) {
if (cache.containsKey(path)) {
return (List<String>) cache.get(path);
return StringUtils.translateList((List<String>) cache.get(path));
} else {
cache.put(path, has(path) ? new ArrayList<>(config.getStringList(path)) : new ArrayList<>());
cache.put(path, has(path) ? new ArrayList<>(handle.getStringList(path)) : new ArrayList<>());
return getStrings(path);
}
}
@@ -282,7 +242,7 @@ public abstract class AbstractUndefinedConfig<T extends ConfigurationSection> im
if (cache.containsKey(path)) {
return (double) cache.get(path);
} else {
cache.put(path, config.getDouble(path));
cache.put(path, handle.getDouble(path));
return getDouble(path);
}
}
@@ -303,7 +263,7 @@ public abstract class AbstractUndefinedConfig<T extends ConfigurationSection> im
if (cache.containsKey(path)) {
return (List<Double>) cache.get(path);
} else {
cache.put(path, has(path) ? new ArrayList<>(config.getDoubleList(path)) : new ArrayList<>());
cache.put(path, has(path) ? new ArrayList<>(handle.getDoubleList(path)) : new ArrayList<>());
return getDoubles(path);
}
}

View File

@@ -1,7 +1,7 @@
package com.willfp.eco.internal.drops.impl;
import com.willfp.eco.internal.drops.AbstractDropQueue;
import com.willfp.eco.util.drops.telekinesis.TelekinesisUtils;
import com.willfp.eco.util.TelekinesisUtils;
import lombok.AccessLevel;
import lombok.Getter;
import org.bukkit.Bukkit;

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