From bc9c579f6d89eda91730b02f952c25e1bd5002d8 Mon Sep 17 00:00:00 2001 From: TDR Date: Sat, 25 Mar 2023 15:37:01 +0100 Subject: [PATCH 01/60] bump 1.6-SNAPSHOT --- API/pom.xml | 2 +- .../core/api/misc/DurationFormatUtils.java | 38 ++----- AdventureAPI/pom.xml | 8 +- .../core/adventure/api/AdventureAPI.java | 2 +- .../adventure/api/MessageRepresentation.java | 39 +++++++ AdventureCore/pom.xml | 4 +- .../core/adventure/AdventureCore.java | 2 +- Core/pom.xml | 4 +- .../main/java/net/juligames/core/Core.java | 4 +- HazelAPI/pom.xml | 4 +- Master/dependency-reduced-pom.xml | 85 +++++++------- Master/pom.xml | 4 +- MiniGameAPI/pom.xml | 4 +- PaperAPI/pom.xml | 4 +- .../core/paper/plugin/CorePlugin.java | 2 + PaperCore/dependency-reduced-pom.xml | 105 +++++++++--------- PaperCore/pom.xml | 8 +- VelocityAPI/pom.xml | 4 +- VelocityCore/dependency-reduced-pom.xml | 105 +++++++++--------- VelocityCore/pom.xml | 8 +- .../juligames/core/velocity/VelocityCore.java | 2 +- .../src/main/java/test/ConversationTest.java | 46 ++++++++ pom.xml | 2 +- 23 files changed, 280 insertions(+), 206 deletions(-) create mode 100644 AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java create mode 100644 VelocityCore/src/main/java/test/ConversationTest.java diff --git a/API/pom.xml b/API/pom.xml index ddf41928..9e141cfe 100644 --- a/API/pom.xml +++ b/API/pom.xml @@ -6,7 +6,7 @@ JuliGamesCore net.juligames.core - 1.5 + 1.6-SNAPSHOT 4.0.0 diff --git a/API/src/main/java/net/juligames/core/api/misc/DurationFormatUtils.java b/API/src/main/java/net/juligames/core/api/misc/DurationFormatUtils.java index 6285d582..63ef04bb 100644 --- a/API/src/main/java/net/juligames/core/api/misc/DurationFormatUtils.java +++ b/API/src/main/java/net/juligames/core/api/misc/DurationFormatUtils.java @@ -22,7 +22,6 @@ import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.text.StrBuilder; import org.apache.commons.lang.time.DateUtils; -import org.checkerframework.checker.units.qual.A; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -669,7 +668,7 @@ static Token[] lexx(String format) { Object value = null; switch (ch) { // TODO: Need to handle escaping of ' - case '\'': + case '\'' -> { if (inLiteral) { buffer = null; inLiteral = false; @@ -678,34 +677,21 @@ static Token[] lexx(String format) { list.add(new Token(buffer)); inLiteral = true; } - break; - case 'y': - value = y; - break; - case 'M': - value = M; - break; - case 'd': - value = d; - break; - case 'H': - value = H; - break; - case 'm': - value = m; - break; - case 's': - value = s; - break; - case 'S': - value = S; - break; - default: + } + case 'y' -> value = y; + case 'M' -> value = M; + case 'd' -> value = d; + case 'H' -> value = H; + case 'm' -> value = m; + case 's' -> value = s; + case 'S' -> value = S; + default -> { if (buffer == null) { buffer = new StringBuffer(); list.add(new Token(buffer)); } buffer.append(ch); + } } if (value != null) { @@ -719,7 +705,7 @@ static Token[] lexx(String format) { buffer = null; } } - return (Token[]) list.toArray(new Token[list.size()]); + return (Token[]) list.toArray(new Token[0]); } diff --git a/AdventureAPI/pom.xml b/AdventureAPI/pom.xml index a183bb67..4fa17adc 100644 --- a/AdventureAPI/pom.xml +++ b/AdventureAPI/pom.xml @@ -6,7 +6,7 @@ JuliGamesCore net.juligames.core - 1.5 + 1.6-SNAPSHOT 4.0.0 @@ -24,7 +24,7 @@ net.juligames.core API - 1.5 + 1.6-SNAPSHOT @@ -45,6 +45,10 @@ 4.11.0 compile + + de.bentzin + ConversationLib + \ No newline at end of file diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/AdventureAPI.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/AdventureAPI.java index 0ddd9055..ec9f07dd 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/AdventureAPI.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/AdventureAPI.java @@ -18,7 +18,7 @@ * Please make sure the modules (AdventureAPI & AdventureCore) are the same version to avoid issues while execution! */ public interface AdventureAPI { - @NotNull String API_VERSION = "1.5"; + @NotNull String API_VERSION = "1.6-SNAPSHOT"; static @NotNull AdventureAPI get() { AdventureAPI api = AdventureAPICore.getAPI(); diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java new file mode 100644 index 00000000..a9e20945 --- /dev/null +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java @@ -0,0 +1,39 @@ +package net.juligames.core.adventure.api; + +import net.juligames.core.adventure.AdventureTagManager; +import net.juligames.core.api.message.Message; +import net.juligames.core.api.message.MiniMessageSerializer; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.ComponentLike; +import org.jetbrains.annotations.NotNull; + +/** + * @author Ture Bentzin + * 25.03.2023 + */ +public class MessageRepresentation implements ComponentLike { + + + + private final @NotNull AdventureTagManager adventureTagManager; + private final @NotNull Message message; + + public MessageRepresentation(@NotNull AdventureTagManager adventureTagManager, @NotNull Message message){ + this.adventureTagManager = adventureTagManager; + this.message = message; + } + + public MessageRepresentation(@NotNull Message message){ + this.adventureTagManager = AdventureAPI.get().getAdventureTagManager(); + this.message = message; + } + + @Override + public @NotNull Component asComponent() { + return adventureTagManager.resolve(message); + } + + public Message getMessage() { + return message; + } +} diff --git a/AdventureCore/pom.xml b/AdventureCore/pom.xml index a75dd7db..8cdcd15d 100644 --- a/AdventureCore/pom.xml +++ b/AdventureCore/pom.xml @@ -6,7 +6,7 @@ JuliGamesCore net.juligames.core - 1.5 + 1.6-SNAPSHOT 4.0.0 @@ -22,7 +22,7 @@ net.juligames.core AdventureAPI - 1.5 + 1.6-SNAPSHOT diff --git a/AdventureCore/src/main/java/net/juligames/core/adventure/AdventureCore.java b/AdventureCore/src/main/java/net/juligames/core/adventure/AdventureCore.java index 0a6bd57d..adc28832 100644 --- a/AdventureCore/src/main/java/net/juligames/core/adventure/AdventureCore.java +++ b/AdventureCore/src/main/java/net/juligames/core/adventure/AdventureCore.java @@ -21,7 +21,7 @@ * support it. Because of this the AdventureAPI will only function as intended when bundled with the API you are using! */ public class AdventureCore implements AdventureAPI { - final String CORE_VERSION = "1.5"; + final String CORE_VERSION = "1.6-SNAPSHOT"; private CoreAdventureTagManager adventureTagManager; private Logger logger; diff --git a/Core/pom.xml b/Core/pom.xml index d9e9e55d..53a56847 100644 --- a/Core/pom.xml +++ b/Core/pom.xml @@ -6,7 +6,7 @@ JuliGamesCore net.juligames.core - 1.5 + 1.6-SNAPSHOT 4.0.0 @@ -24,7 +24,7 @@ net.juligames.core HazelAPI - 1.5 + 1.6-SNAPSHOT org.jdbi diff --git a/Core/src/main/java/net/juligames/core/Core.java b/Core/src/main/java/net/juligames/core/Core.java index 0c5e00a1..4bc82b80 100644 --- a/Core/src/main/java/net/juligames/core/Core.java +++ b/Core/src/main/java/net/juligames/core/Core.java @@ -48,9 +48,9 @@ public final class Core implements API { * This can be set depending on the build of the Core */ public static final String CORE_BRAND = "Core"; - public static final String CORE_VERSION_NUMBER = "1.5"; + public static final String CORE_VERSION_NUMBER = "1.6-SNAPSHOT"; public static final String CORE_SPECIFICATION = "Gustav"; - private static final String BUILD_VERSION = "1.5"; //POM VERSION + private static final String BUILD_VERSION = "1.6-SNAPSHOT"; //POM VERSION private static Core core; private final Registerator> hazelcastPostPreparationWorkers = new Registerator<>("hazelcastPostPreparationWorkers"); diff --git a/HazelAPI/pom.xml b/HazelAPI/pom.xml index d08ccce7..b8843393 100644 --- a/HazelAPI/pom.xml +++ b/HazelAPI/pom.xml @@ -6,7 +6,7 @@ JuliGamesCore net.juligames.core - 1.5 + 1.6-SNAPSHOT 4.0.0 @@ -28,7 +28,7 @@ net.juligames.core API - 1.5 + 1.6-SNAPSHOT compile diff --git a/Master/dependency-reduced-pom.xml b/Master/dependency-reduced-pom.xml index b5fcafe4..e002a95d 100644 --- a/Master/dependency-reduced-pom.xml +++ b/Master/dependency-reduced-pom.xml @@ -1,45 +1,44 @@ - - - JuliGamesCore - net.juligames.core - 1.5 - - 4.0.0 - Master - - - - maven-shade-plugin - 3.4.1 - - - package - - shade - - - - - - - maven-jar-plugin - 3.3.0 - - - - true - net.juligames.core.master.CoreMaster - - - - - - - - 17 - 17 - UTF-8 - + + + JuliGamesCore + net.juligames.core + 1.6-SNAPSHOT + + 4.0.0 + Master + + + + maven-shade-plugin + 3.4.1 + + + package + + shade + + + + + + + maven-jar-plugin + 3.3.0 + + + + true + net.juligames.core.master.CoreMaster + + + + + + + + 17 + 17 + UTF-8 + diff --git a/Master/pom.xml b/Master/pom.xml index 54452e2e..049c8fb0 100644 --- a/Master/pom.xml +++ b/Master/pom.xml @@ -6,7 +6,7 @@ JuliGamesCore net.juligames.core - 1.5 + 1.6-SNAPSHOT 4.0.0 @@ -22,7 +22,7 @@ net.juligames.core Core - 1.5 + 1.6-SNAPSHOT org.jetbrains diff --git a/MiniGameAPI/pom.xml b/MiniGameAPI/pom.xml index 8fce11d3..ec8386c7 100644 --- a/MiniGameAPI/pom.xml +++ b/MiniGameAPI/pom.xml @@ -6,7 +6,7 @@ JuliGamesCore net.juligames.core - 1.5 + 1.6-SNAPSHOT 4.0.0 @@ -22,7 +22,7 @@ net.juligames.core PaperAPI - 1.5 + 1.6-SNAPSHOT provided diff --git a/PaperAPI/pom.xml b/PaperAPI/pom.xml index b529d78b..3da1fa01 100644 --- a/PaperAPI/pom.xml +++ b/PaperAPI/pom.xml @@ -6,7 +6,7 @@ JuliGamesCore net.juligames.core - 1.5 + 1.6-SNAPSHOT 4.0.0 @@ -28,7 +28,7 @@ net.juligames.core AdventureAPI - 1.5 + 1.6-SNAPSHOT compile diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/plugin/CorePlugin.java b/PaperAPI/src/main/java/net/juligames/core/paper/plugin/CorePlugin.java index 90befe9e..3872387b 100644 --- a/PaperAPI/src/main/java/net/juligames/core/paper/plugin/CorePlugin.java +++ b/PaperAPI/src/main/java/net/juligames/core/paper/plugin/CorePlugin.java @@ -56,6 +56,8 @@ protected CorePlugin(@NotNull final CorePluginLoader loader, @NotNull final Plug throw new IllegalStateException("Cannot use initialization constructor at runtime"); } init(loader, loader.server, description, dataFolder, file, classLoader); + + PaperC } /** diff --git a/PaperCore/dependency-reduced-pom.xml b/PaperCore/dependency-reduced-pom.xml index ca50dabb..94138164 100644 --- a/PaperCore/dependency-reduced-pom.xml +++ b/PaperCore/dependency-reduced-pom.xml @@ -1,55 +1,54 @@ - - - JuliGamesCore - net.juligames.core - 1.5 - - 4.0.0 - PaperCore - - - - true - src/main/resources - - - - - maven-shade-plugin - 3.4.1 - - - package - - shade - - - - - false - - - - - - - papermc - https://repo.papermc.io/repository/maven-public/ - - - - - io.papermc.paper - paper-api - 1.18.2-R0.1-SNAPSHOT - provided - - - - 17 - 17 - UTF-8 - + + + JuliGamesCore + net.juligames.core + 1.6-SNAPSHOT + + 4.0.0 + PaperCore + + + + true + src/main/resources + + + + + maven-shade-plugin + 3.4.1 + + + package + + shade + + + + + false + + + + + + + papermc + https://repo.papermc.io/repository/maven-public/ + + + + + io.papermc.paper + paper-api + 1.18.2-R0.1-SNAPSHOT + provided + + + + 17 + 17 + UTF-8 + diff --git a/PaperCore/pom.xml b/PaperCore/pom.xml index 7fb7f88f..17466f35 100644 --- a/PaperCore/pom.xml +++ b/PaperCore/pom.xml @@ -6,7 +6,7 @@ JuliGamesCore net.juligames.core - 1.5 + 1.6-SNAPSHOT 4.0.0 @@ -16,19 +16,19 @@ net.juligames.core PaperAPI - 1.5 + 1.6-SNAPSHOT compile net.juligames.core Core - 1.5 + 1.6-SNAPSHOT compile net.juligames.core AdventureCore - 1.5 + 1.6-SNAPSHOT compile diff --git a/VelocityAPI/pom.xml b/VelocityAPI/pom.xml index afdfeaf7..b08aaaf6 100644 --- a/VelocityAPI/pom.xml +++ b/VelocityAPI/pom.xml @@ -7,7 +7,7 @@ JuliGamesCore net.juligames.core - 1.5 + 1.6-SNAPSHOT 4.0.0 @@ -30,7 +30,7 @@ net.juligames.core AdventureAPI - 1.5 + 1.6-SNAPSHOT compile diff --git a/VelocityCore/dependency-reduced-pom.xml b/VelocityCore/dependency-reduced-pom.xml index bdd4a20c..e9183dcb 100644 --- a/VelocityCore/dependency-reduced-pom.xml +++ b/VelocityCore/dependency-reduced-pom.xml @@ -1,55 +1,54 @@ - - - JuliGamesCore - net.juligames.core - 1.5 - - 4.0.0 - VelocityCore - - - - maven-shade-plugin - 3.4.1 - - - package - - shade - - - - - false - - - - - - - papermc - papermc - https://repo.papermc.io/repository/maven-public/ - - - juligames-juligames - Juligames Maven - https://maven.juligames.net/juligames - - - - - com.velocitypowered - velocity-api - 3.1.1 - provided - - - - 17 - 17 - UTF-8 - + + + JuliGamesCore + net.juligames.core + 1.6-SNAPSHOT + + 4.0.0 + VelocityCore + + + + maven-shade-plugin + 3.4.1 + + + package + + shade + + + + + false + + + + + + + papermc + papermc + https://repo.papermc.io/repository/maven-public/ + + + juligames-juligames + Juligames Maven + https://maven.juligames.net/juligames + + + + + com.velocitypowered + velocity-api + 3.1.1 + provided + + + + 17 + 17 + UTF-8 + diff --git a/VelocityCore/pom.xml b/VelocityCore/pom.xml index 0cbb5179..4b6a161f 100644 --- a/VelocityCore/pom.xml +++ b/VelocityCore/pom.xml @@ -6,7 +6,7 @@ JuliGamesCore net.juligames.core - 1.5 + 1.6-SNAPSHOT 4.0.0 @@ -22,7 +22,7 @@ net.juligames.core VelocityAPI - 1.5 + 1.6-SNAPSHOT compile @@ -34,13 +34,13 @@ net.juligames.core Core - 1.5 + 1.6-SNAPSHOT compile net.juligames.core AdventureCore - 1.5 + 1.6-SNAPSHOT compile diff --git a/VelocityCore/src/main/java/net/juligames/core/velocity/VelocityCore.java b/VelocityCore/src/main/java/net/juligames/core/velocity/VelocityCore.java index 577c53da..dc4d1e55 100644 --- a/VelocityCore/src/main/java/net/juligames/core/velocity/VelocityCore.java +++ b/VelocityCore/src/main/java/net/juligames/core/velocity/VelocityCore.java @@ -23,7 +23,7 @@ * 03.12.2022 */ -@Plugin(id = "velocitycore", name = "JuliGames Velocity Core", version = "1.5", +@Plugin(id = "velocitycore", name = "JuliGames Velocity Core", version = "1.6-SNAPSHOT", url = "https://github.com/JuliGames/JuliGamesCore", description = "Velocity Client for the core - necessary to provide the API here", authors = {"Ture Bentzin"}) public final class VelocityCore { diff --git a/VelocityCore/src/main/java/test/ConversationTest.java b/VelocityCore/src/main/java/test/ConversationTest.java new file mode 100644 index 00000000..822598ca --- /dev/null +++ b/VelocityCore/src/main/java/test/ConversationTest.java @@ -0,0 +1,46 @@ +package test; + +import de.bentzin.conversationlib.ConversationContext; +import de.bentzin.conversationlib.manager.ConversationManager; +import de.bentzin.conversationlib.prompt.BooleanPrompt; +import de.bentzin.conversationlib.prompt.LambdaPrompt; +import de.bentzin.conversationlib.prompt.Prompt; +import net.juligames.core.adventure.api.MessageRepresentation; +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.ComponentLike; +import org.checkerframework.checker.units.qual.A; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * @author Ture Bentzin + * 25.03.2023 + */ +public class ConversationTest { + public static void demo(){ + + ConversationManager conversationManager = new ConversationManager(); + Audience player = Audience.empty(); + + conversationManager.newBuilder().prefix( context -> Component.text("> ")) + .firstPrompt( + new LambdaPrompt(conversationContext -> Component.text("Bitte Name angeben:"), + conversationContext -> true, + (conversationContext, s) -> { + conversationContext.setData("name",s); + return new BooleanPrompt() { + @Override + protected @Nullable Prompt acceptValidatedInput(@NotNull ConversationContext context, boolean input) { + return MessageRepresentation.; + } + + @Override + public @NotNull ComponentLike getPromptMessage(@NotNull ConversationContext conversationContext) { + return MessageRepresentation.represent("ley.key", conversationContext.target()); + } + } + })) + + } +} diff --git a/pom.xml b/pom.xml index 3f1f5127..ffb1fbe1 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ net.juligames.core JuliGamesCore pom - 1.5 + 1.6-SNAPSHOT PaperCore Core From 38aacd9243d98359399ec36989b0f87f7e92e2be Mon Sep 17 00:00:00 2001 From: TDR Date: Sat, 25 Mar 2023 15:38:15 +0100 Subject: [PATCH 02/60] add prompts --- .gitignore | 1 + AdventureAPI/pom.xml | 1 + .../adventure/api/MessageRepresentation.java | 63 +++++++++++++++++-- .../adventure/prompt/IndexBackedPrompt.java | 43 +++++++++++++ .../prompt/NamedTextColorPrompt.java | 28 +++++++++ .../core/paper/prompt/MaterialPrompt.java | 29 +++++++++ .../core/paper/prompt/PlayerPrompt.java | 26 ++++++++ .../paper/prompt/PluginManagerPrompt.java | 14 +++++ .../core/paper/prompt/PluginPrompt.java | 24 +++++++ .../core/paper/prompt/ServerPrompt.java | 13 ++++ .../velocity/prompt/PartiallPlayerPrompt.java | 35 +++++++++++ .../core/velocity/prompt/PlayerPrompt.java | 31 +++++++++ .../velocity/prompt/PluginManagerPrompt.java | 14 +++++ .../core/velocity/prompt/PluginPrompt.java | 26 ++++++++ .../velocity/prompt/ProxyServerPrompt.java | 12 ++++ .../core/velocity/prompt/ServerPrompt.java | 26 ++++++++ 16 files changed, 380 insertions(+), 6 deletions(-) create mode 100644 AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/IndexBackedPrompt.java create mode 100644 AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/NamedTextColorPrompt.java create mode 100644 PaperAPI/src/main/java/net/juligames/core/paper/prompt/MaterialPrompt.java create mode 100644 PaperAPI/src/main/java/net/juligames/core/paper/prompt/PlayerPrompt.java create mode 100644 PaperAPI/src/main/java/net/juligames/core/paper/prompt/PluginManagerPrompt.java create mode 100644 PaperAPI/src/main/java/net/juligames/core/paper/prompt/PluginPrompt.java create mode 100644 PaperAPI/src/main/java/net/juligames/core/paper/prompt/ServerPrompt.java create mode 100644 VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PartiallPlayerPrompt.java create mode 100644 VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PlayerPrompt.java create mode 100644 VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PluginManagerPrompt.java create mode 100644 VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PluginPrompt.java create mode 100644 VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/ProxyServerPrompt.java create mode 100644 VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/ServerPrompt.java diff --git a/.gitignore b/.gitignore index 75c1a8ad..2e7a81c5 100644 --- a/.gitignore +++ b/.gitignore @@ -39,3 +39,4 @@ latest.log.lck config/messageSystem.properties= Core/src/main/java/net/juligames/core/Test.java config/messageSystem.properties +VelocityCore/src/main/java/test/ConversationTest.java diff --git a/AdventureAPI/pom.xml b/AdventureAPI/pom.xml index 4fa17adc..a6df11f7 100644 --- a/AdventureAPI/pom.xml +++ b/AdventureAPI/pom.xml @@ -48,6 +48,7 @@ de.bentzin ConversationLib + 1.2 diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java index a9e20945..593b2c34 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java @@ -1,33 +1,84 @@ package net.juligames.core.adventure.api; import net.juligames.core.adventure.AdventureTagManager; +import net.juligames.core.api.API; +import net.juligames.core.api.jdbi.DBLocale; +import net.juligames.core.api.jdbi.DBMessage; import net.juligames.core.api.message.Message; -import net.juligames.core.api.message.MiniMessageSerializer; +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.identity.Identity; +import net.kyori.adventure.pointer.Pointer; +import net.kyori.adventure.pointer.Pointered; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.ComponentLike; +import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; +import java.util.Locale; + /** * @author Ture Bentzin * 25.03.2023 */ public class MessageRepresentation implements ComponentLike { - - private final @NotNull AdventureTagManager adventureTagManager; private final @NotNull Message message; - - public MessageRepresentation(@NotNull AdventureTagManager adventureTagManager, @NotNull Message message){ + public MessageRepresentation(@NotNull AdventureTagManager adventureTagManager, @NotNull Message message) { this.adventureTagManager = adventureTagManager; this.message = message; } - public MessageRepresentation(@NotNull Message message){ + public MessageRepresentation(@NotNull Message message) { this.adventureTagManager = AdventureAPI.get().getAdventureTagManager(); this.message = message; } + @Contract("_, _ -> new") + public static @NotNull MessageRepresentation represent(String messageKey, String locale) { + return new MessageRepresentation(API.get().getMessageApi().getMessageSmart(messageKey, locale)); + } + + @Contract("_, _, _ -> new") + public static @NotNull MessageRepresentation represent(String messageKey, String locale, String... replacements) { + return new MessageRepresentation(API.get().getMessageApi().getMessageSmart(messageKey, locale, replacements)); + } + + @Contract("_, _ -> new") + public static @NotNull MessageRepresentation represent(String messageKey, Locale locale) { + return new MessageRepresentation(API.get().getMessageApi().getMessageSmart(messageKey, locale)); + } + + @Contract("_, _, _ -> new") + public static @NotNull MessageRepresentation represent(String messageKey, Locale locale, String... replacements) { + return new MessageRepresentation(API.get().getMessageApi().getMessageSmart(messageKey, locale, replacements)); + } + + @Contract("_, _ -> new") + public static @NotNull MessageRepresentation represent(String messageKey, DBLocale locale) { + return new MessageRepresentation(API.get().getMessageApi().getMessageSmart(messageKey, locale)); + } + + @Contract("_, _, _ -> new") + public static @NotNull MessageRepresentation represent(String messageKey, DBLocale locale, String... replacements) { + return new MessageRepresentation(API.get().getMessageApi().getMessageSmart(messageKey, locale, replacements)); + } + + //Personal + + @Contract("_, _ -> new") + public static @NotNull MessageRepresentation represent(String messageKey, Pointered pointered) { + return new MessageRepresentation(API.get().getMessageApi().getMessageSmart(messageKey, + pointered.get(Identity.LOCALE).orElseThrow())); + } + + @Contract("_, _, _ -> new") + public static @NotNull MessageRepresentation represent(String messageKey, Pointered pointered, String... replacements) { + return new MessageRepresentation(API.get().getMessageApi().getMessageSmart(messageKey, pointered.get(Identity.LOCALE).orElseThrow(), replacements)); + } + + + @Override public @NotNull Component asComponent() { return adventureTagManager.resolve(message); diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/IndexBackedPrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/IndexBackedPrompt.java new file mode 100644 index 00000000..173854ba --- /dev/null +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/IndexBackedPrompt.java @@ -0,0 +1,43 @@ +package net.juligames.core.adventure.prompt; + +import de.bentzin.conversationlib.ConversationContext; +import de.bentzin.conversationlib.prompt.Prompt; +import de.bentzin.conversationlib.prompt.ValidatingPrompt; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.util.Index; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Objects; +import java.util.stream.Stream; + +/** + * @author Ture Bentzin + * 25.03.2023 + */ +public abstract class IndexBackedPrompt extends ValidatingPrompt { + + private final Index index; + + public IndexBackedPrompt(@NotNull Index index) { + this.index = index; + } + + @Override + protected boolean isInputValid(@NotNull ConversationContext context, @NotNull String input) { + return index.keys().contains(input); + } + + @Override + protected @Nullable Prompt acceptValidatedInput(@NotNull ConversationContext context, @NotNull String input) { + return acceptIndexBackedInput(context, Objects.requireNonNull(index.value(input))); + } + + public abstract @Nullable Prompt acceptIndexBackedInput(@NotNull ConversationContext context, @NotNull V v); + + @Override + protected @Nullable Component getFailedValidationText(@NotNull ConversationContext context, @NotNull String invalidInput) { + Stream stringStream = index.keys().stream().filter(s -> s.contains(invalidInput)); + return Component.text(" -> " + stringStream.toList() + "?"); + } +} diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/NamedTextColorPrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/NamedTextColorPrompt.java new file mode 100644 index 00000000..ee052f06 --- /dev/null +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/NamedTextColorPrompt.java @@ -0,0 +1,28 @@ +package net.juligames.core.adventure.prompt; + +import de.bentzin.conversationlib.ConversationContext; +import de.bentzin.conversationlib.prompt.Prompt; +import de.bentzin.conversationlib.prompt.ValidatingPrompt; +import net.kyori.adventure.text.format.NamedTextColor; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Objects; + +/** + * @author Ture Bentzin + * 25.03.2023 + */ +public abstract class NamedTextColorPrompt extends ValidatingPrompt { + @Override + protected boolean isInputValid(@NotNull ConversationContext context, @NotNull String input) { + return NamedTextColor.NAMES.value(input) != null; + } + + @Override + protected @Nullable Prompt acceptValidatedInput(@NotNull ConversationContext context, @NotNull String input) { + return acceptTextColorInput(context, Objects.requireNonNull(NamedTextColor.NAMES.value(input))); + } + + public abstract @Nullable Prompt acceptTextColorInput(@NotNull ConversationContext context, @NotNull NamedTextColor namedTextColor); +} diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/prompt/MaterialPrompt.java b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/MaterialPrompt.java new file mode 100644 index 00000000..bf3e00a3 --- /dev/null +++ b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/MaterialPrompt.java @@ -0,0 +1,29 @@ +package net.juligames.core.paper.prompt; + +import de.bentzin.conversationlib.ConversationContext; +import de.bentzin.conversationlib.prompt.Prompt; +import de.bentzin.conversationlib.prompt.ValidatingPrompt; +import org.bukkit.Material; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Objects; + +/** + * @author Ture Bentzin + * 25.03.2023 + */ +public abstract class MaterialPrompt extends ValidatingPrompt { + @Override + protected boolean isInputValid(@NotNull ConversationContext context, @NotNull String input) { + return Material.getMaterial(input) != null; + } + + @Override + protected @Nullable Prompt acceptValidatedInput(@NotNull ConversationContext context, @NotNull String input) { + return acceptMaterialInput(context, Objects.requireNonNull(Material.getMaterial(input))); + } + + public abstract Prompt acceptMaterialInput(@NotNull ConversationContext context, @NotNull Material material); + +} diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/prompt/PlayerPrompt.java b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/PlayerPrompt.java new file mode 100644 index 00000000..f9db3555 --- /dev/null +++ b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/PlayerPrompt.java @@ -0,0 +1,26 @@ +package net.juligames.core.paper.prompt; + +import de.bentzin.conversationlib.prompt.FixedSetPrompt; +import org.bukkit.Server; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.util.Collections; + +/** + * @author Ture Bentzin + * 25.03.2023 + */ +public abstract class PlayerPrompt extends FixedSetPrompt implements ServerPrompt { + private final Server server; + + public PlayerPrompt(@NotNull Server server) { + super(server::getPlayer, Collections.unmodifiableCollection(server.getOnlinePlayers())); + this.server = server; + } + + @Override + public Server getServer() { + return server; + } +} diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/prompt/PluginManagerPrompt.java b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/PluginManagerPrompt.java new file mode 100644 index 00000000..0197e622 --- /dev/null +++ b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/PluginManagerPrompt.java @@ -0,0 +1,14 @@ +package net.juligames.core.paper.prompt; + +import de.bentzin.conversationlib.prompt.Prompt; +import org.bukkit.plugin.PluginManager; +import org.jetbrains.annotations.NotNull; + +/** + * @author Ture Bentzin + * 25.03.2023 + */ +public interface PluginManagerPrompt extends Prompt { + + @NotNull PluginManager getPluginManager(); +} diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/prompt/PluginPrompt.java b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/PluginPrompt.java new file mode 100644 index 00000000..8bb040bc --- /dev/null +++ b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/PluginPrompt.java @@ -0,0 +1,24 @@ +package net.juligames.core.paper.prompt; + +import de.bentzin.conversationlib.prompt.FixedSetPrompt; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginManager; +import org.jetbrains.annotations.NotNull; + +/** + * @author Ture Bentzin + * 25.03.2023 + */ +public abstract class PluginPrompt extends FixedSetPrompt implements PluginManagerPrompt { + private final PluginManager pluginManager; + + public PluginPrompt(@NotNull PluginManager pluginManager) { + super(pluginManager::getPlugin, pluginManager.getPlugins()); + this.pluginManager = pluginManager; + } + + @Override + public @NotNull PluginManager getPluginManager() { + return pluginManager; + } +} \ No newline at end of file diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/prompt/ServerPrompt.java b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/ServerPrompt.java new file mode 100644 index 00000000..c0a5aef0 --- /dev/null +++ b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/ServerPrompt.java @@ -0,0 +1,13 @@ +package net.juligames.core.paper.prompt; + +import de.bentzin.conversationlib.prompt.Prompt; +import org.bukkit.Server; + +/** + * @author Ture Bentzin + * 25.03.2023 + */ +public interface ServerPrompt extends Prompt { + + Server getServer(); +} diff --git a/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PartiallPlayerPrompt.java b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PartiallPlayerPrompt.java new file mode 100644 index 00000000..f7893422 --- /dev/null +++ b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PartiallPlayerPrompt.java @@ -0,0 +1,35 @@ +package net.juligames.core.velocity.prompt; + +import com.velocitypowered.api.plugin.PluginManager; +import com.velocitypowered.api.proxy.Player; +import com.velocitypowered.api.proxy.ProxyServer; +import de.bentzin.conversationlib.prompt.FixedSetPrompt; +import org.jetbrains.annotations.NotNull; + +import java.util.Collection; +import java.util.Collections; + +/** + * @author Ture Bentzin + * 25.03.2023 + */ +public abstract class PartiallPlayerPrompt extends FixedSetPrompt> implements ProxyServerPrompt, PluginManagerPrompt { + + private final ProxyServer proxyServer; + + public PartiallPlayerPrompt(@NotNull ProxyServer proxyServer) { + super(s -> Collections.singleton(proxyServer.matchPlayer(s).stream().findFirst().orElse(null)), + proxyServer.getAllPlayers()); + this.proxyServer = proxyServer; + } + + @Override + public ProxyServer getProxy() { + return proxyServer; + } + + @Override + public @NotNull PluginManager getPluginManager() { + return getProxy().getPluginManager(); + } +} diff --git a/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PlayerPrompt.java b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PlayerPrompt.java new file mode 100644 index 00000000..4dca20b1 --- /dev/null +++ b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PlayerPrompt.java @@ -0,0 +1,31 @@ +package net.juligames.core.velocity.prompt; + +import com.velocitypowered.api.plugin.PluginManager; +import com.velocitypowered.api.proxy.Player; +import com.velocitypowered.api.proxy.ProxyServer; +import de.bentzin.conversationlib.prompt.FixedSetPrompt; +import org.jetbrains.annotations.NotNull; + +/** + * @author Ture Bentzin + * 25.03.2023 + */ +public abstract class PlayerPrompt extends FixedSetPrompt implements ProxyServerPrompt, PluginManagerPrompt { + + private final ProxyServer proxyServer; + + public PlayerPrompt(@NotNull ProxyServer proxyServer) { + super(s -> proxyServer.getPlayer(s).orElse(null), proxyServer.getAllPlayers()); + this.proxyServer = proxyServer; + } + + @Override + public ProxyServer getProxy() { + return proxyServer; + } + + @Override + public @NotNull PluginManager getPluginManager() { + return getProxy().getPluginManager(); + } +} diff --git a/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PluginManagerPrompt.java b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PluginManagerPrompt.java new file mode 100644 index 00000000..1733e001 --- /dev/null +++ b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PluginManagerPrompt.java @@ -0,0 +1,14 @@ +package net.juligames.core.velocity.prompt; + +import com.velocitypowered.api.plugin.PluginManager; +import de.bentzin.conversationlib.prompt.Prompt; +import org.jetbrains.annotations.NotNull; + +/** + * @author Ture Bentzin + * 25.03.2023 + */ +public interface PluginManagerPrompt extends Prompt { + + @NotNull PluginManager getPluginManager(); +} diff --git a/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PluginPrompt.java b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PluginPrompt.java new file mode 100644 index 00000000..6e326245 --- /dev/null +++ b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PluginPrompt.java @@ -0,0 +1,26 @@ +package net.juligames.core.velocity.prompt; + +import com.velocitypowered.api.plugin.PluginContainer; +import com.velocitypowered.api.proxy.ProxyServer; +import de.bentzin.conversationlib.prompt.FixedSetPrompt; +import org.jetbrains.annotations.NotNull; + +/** + * @author Ture Bentzin + * 25.03.2023 + */ +public abstract class PluginPrompt extends FixedSetPrompt implements ProxyServerPrompt { + + private final ProxyServer proxyServer; + + public PluginPrompt(@NotNull ProxyServer proxyServer) { + super(s -> proxyServer.getPluginManager().getPlugin(s).orElse(null), + proxyServer.getPluginManager().getPlugins()); + this.proxyServer = proxyServer; + } + + @Override + public ProxyServer getProxy() { + return proxyServer; + } +} \ No newline at end of file diff --git a/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/ProxyServerPrompt.java b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/ProxyServerPrompt.java new file mode 100644 index 00000000..8392df0c --- /dev/null +++ b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/ProxyServerPrompt.java @@ -0,0 +1,12 @@ +package net.juligames.core.velocity.prompt; + +import com.velocitypowered.api.proxy.ProxyServer; +import de.bentzin.conversationlib.prompt.Prompt; + +/** + * @author Ture Bentzin + * 25.03.2023 + */ +public interface ProxyServerPrompt extends Prompt { + ProxyServer getProxy(); +} diff --git a/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/ServerPrompt.java b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/ServerPrompt.java new file mode 100644 index 00000000..3d4890ee --- /dev/null +++ b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/ServerPrompt.java @@ -0,0 +1,26 @@ +package net.juligames.core.velocity.prompt; + +import com.velocitypowered.api.proxy.Player; +import com.velocitypowered.api.proxy.ProxyServer; +import com.velocitypowered.api.proxy.server.RegisteredServer; +import de.bentzin.conversationlib.prompt.FixedSetPrompt; +import org.jetbrains.annotations.NotNull; + +/** + * @author Ture Bentzin + * 25.03.2023 + */ +public abstract class ServerPrompt extends FixedSetPrompt implements ProxyServerPrompt { + + private final ProxyServer proxyServer; + + public ServerPrompt(@NotNull ProxyServer proxyServer) { + super(s -> proxyServer.getServer(s).orElse(null), proxyServer.getAllServers()); + this.proxyServer = proxyServer; + } + + @Override + public ProxyServer getProxy() { + return proxyServer; + } +} From c34a500167c92a6119ed4e950cf2531bd822c176 Mon Sep 17 00:00:00 2001 From: TDR Date: Sat, 25 Mar 2023 16:47:32 +0100 Subject: [PATCH 03/60] add even more prompts just to torture bommels --- .../core/api/config/ConfigurationAPI.java | 7 ++++ .../adventure/api/MessageRepresentation.java | 2 + .../prompt/ConfigurationAPIPrompt.java | 16 ++++++++ .../adventure/prompt/ConfigurationPrompt.java | 41 +++++++++++++++++++ .../adventure/prompt/IndexBackedPrompt.java | 2 + .../adventure/prompt/MiniMessagePrompt.java | 40 ++++++++++++++++++ .../prompt/NamedTextColorPrompt.java | 22 +++------- .../core/config/CoreConfigurationApi.java | 21 ++++++++++ .../core/paper/prompt/MaterialPrompt.java | 2 + .../core/paper/prompt/PlayerPrompt.java | 2 + .../paper/prompt/PluginManagerPrompt.java | 2 + .../core/paper/prompt/PluginPrompt.java | 2 + .../core/paper/prompt/ServerPrompt.java | 2 + .../velocity/prompt/PartiallPlayerPrompt.java | 2 + .../core/velocity/prompt/PlayerPrompt.java | 2 + .../velocity/prompt/PluginManagerPrompt.java | 2 + .../core/velocity/prompt/PluginPrompt.java | 2 + .../velocity/prompt/ProxyServerPrompt.java | 2 + .../core/velocity/prompt/ServerPrompt.java | 3 +- .../src/main/java/test/ConversationTest.java | 31 +------------- 20 files changed, 157 insertions(+), 48 deletions(-) create mode 100644 AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/ConfigurationAPIPrompt.java create mode 100644 AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/ConfigurationPrompt.java create mode 100644 AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/MiniMessagePrompt.java diff --git a/API/src/main/java/net/juligames/core/api/config/ConfigurationAPI.java b/API/src/main/java/net/juligames/core/api/config/ConfigurationAPI.java index e73287ec..ff32427c 100644 --- a/API/src/main/java/net/juligames/core/api/config/ConfigurationAPI.java +++ b/API/src/main/java/net/juligames/core/api/config/ConfigurationAPI.java @@ -3,6 +3,7 @@ import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Unmodifiable; import java.util.Collection; import java.util.Comparator; @@ -140,4 +141,10 @@ default void spiltAndWrite(@NotNull Collection collection, @NotNull Inter */ @ApiStatus.AvailableSince("1.5") @NotNull Configuration createSectionClone(@NotNull Configuration root, @NotNull String section); + + @ApiStatus.AvailableSince("1.6") + @NotNull @Unmodifiable Collection getAll(); + + @ApiStatus.AvailableSince("1.6") + @NotNull @Unmodifiable Collection getAllHazels(); } diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java index 593b2c34..637b6725 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java @@ -11,6 +11,7 @@ import net.kyori.adventure.pointer.Pointered; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.ComponentLike; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; @@ -20,6 +21,7 @@ * @author Ture Bentzin * 25.03.2023 */ +@ApiStatus.AvailableSince("1.6") public class MessageRepresentation implements ComponentLike { private final @NotNull AdventureTagManager adventureTagManager; diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/ConfigurationAPIPrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/ConfigurationAPIPrompt.java new file mode 100644 index 00000000..93d5a656 --- /dev/null +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/ConfigurationAPIPrompt.java @@ -0,0 +1,16 @@ +package net.juligames.core.adventure.prompt; + +import de.bentzin.conversationlib.prompt.Prompt; +import net.juligames.core.api.config.ConfigurationAPI; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +/** + * @author Ture Bentzin + * 25.03.2023 + */ +@ApiStatus.AvailableSince("1.6") +public interface ConfigurationAPIPrompt extends Prompt { + + @NotNull ConfigurationAPI getConfigurationApi(); +} diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/ConfigurationPrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/ConfigurationPrompt.java new file mode 100644 index 00000000..ad899494 --- /dev/null +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/ConfigurationPrompt.java @@ -0,0 +1,41 @@ +package net.juligames.core.adventure.prompt; + +import de.bentzin.conversationlib.ConversationContext; +import de.bentzin.conversationlib.prompt.FixedSetPrompt; +import de.bentzin.conversationlib.prompt.Prompt; +import net.juligames.core.api.config.Configuration; +import net.juligames.core.api.config.ConfigurationAPI; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * @author Ture Bentzin + * 25.03.2023 + */ +@ApiStatus.AvailableSince("1.6") +public abstract class ConfigurationPrompt extends FixedSetPrompt implements ConfigurationAPIPrompt { + + private final ConfigurationAPI configurationAPI; + + public ConfigurationPrompt(@NotNull ConfigurationAPI configurationAPI) { + super(configurationAPI::getOrCreate, configurationAPI.getAll()); + this.configurationAPI = configurationAPI; + } + + @Override + protected @Nullable Prompt acceptValidatedInput(@NotNull ConversationContext context, @NotNull String input) { + return acceptConfigurationInput(context, configurationAPI.getOrCreate(input)); + } + + public abstract Prompt acceptConfigurationInput(@NotNull ConversationContext context, @NotNull Configuration configuration); + + public ConfigurationAPI getConfigurationAPI() { + return configurationAPI; + } + + @Override + public @NotNull ConfigurationAPI getConfigurationApi() { + return configurationAPI; + } +} diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/IndexBackedPrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/IndexBackedPrompt.java index 173854ba..5954e3a5 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/IndexBackedPrompt.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/IndexBackedPrompt.java @@ -5,6 +5,7 @@ import de.bentzin.conversationlib.prompt.ValidatingPrompt; import net.kyori.adventure.text.Component; import net.kyori.adventure.util.Index; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -15,6 +16,7 @@ * @author Ture Bentzin * 25.03.2023 */ +@ApiStatus.AvailableSince("1.6") public abstract class IndexBackedPrompt extends ValidatingPrompt { private final Index index; diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/MiniMessagePrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/MiniMessagePrompt.java new file mode 100644 index 00000000..418810cd --- /dev/null +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/MiniMessagePrompt.java @@ -0,0 +1,40 @@ +package net.juligames.core.adventure.prompt; + +import de.bentzin.conversationlib.ConversationContext; +import de.bentzin.conversationlib.prompt.Prompt; +import net.juligames.core.adventure.AdventureTagManager; +import net.kyori.adventure.text.Component; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * @author Ture Bentzin + * 25.03.2023 + */ +@ApiStatus.AvailableSince("1.6") +public abstract class MiniMessagePrompt implements Prompt { + + private final @NotNull AdventureTagManager adventureTagManager; + + protected MiniMessagePrompt(@NotNull AdventureTagManager adventureTagManager) { + this.adventureTagManager = adventureTagManager; + } + + + @Override + public boolean blocksForInput(@NotNull ConversationContext context) { + return true; + } + + @Override + public @Nullable Prompt getNextPrompt(@NotNull ConversationContext conversationContext, @Nullable String input) { + if (input != null) { + return acceptComponentInput(conversationContext, adventureTagManager.resolve(input)); + } + return acceptComponentInput(conversationContext, null); + } + + public abstract @Nullable Prompt acceptComponentInput(@NotNull ConversationContext conversationContext, @Nullable Component component); +} + diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/NamedTextColorPrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/NamedTextColorPrompt.java index ee052f06..8cc1fbb5 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/NamedTextColorPrompt.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/NamedTextColorPrompt.java @@ -1,28 +1,16 @@ package net.juligames.core.adventure.prompt; -import de.bentzin.conversationlib.ConversationContext; -import de.bentzin.conversationlib.prompt.Prompt; -import de.bentzin.conversationlib.prompt.ValidatingPrompt; import net.kyori.adventure.text.format.NamedTextColor; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.Objects; +import org.jetbrains.annotations.ApiStatus; /** * @author Ture Bentzin * 25.03.2023 */ -public abstract class NamedTextColorPrompt extends ValidatingPrompt { - @Override - protected boolean isInputValid(@NotNull ConversationContext context, @NotNull String input) { - return NamedTextColor.NAMES.value(input) != null; - } - - @Override - protected @Nullable Prompt acceptValidatedInput(@NotNull ConversationContext context, @NotNull String input) { - return acceptTextColorInput(context, Objects.requireNonNull(NamedTextColor.NAMES.value(input))); +@ApiStatus.AvailableSince("1.6") +public abstract class NamedTextColorPrompt extends IndexBackedPrompt { + public NamedTextColorPrompt() { + super(NamedTextColor.NAMES); } - public abstract @Nullable Prompt acceptTextColorInput(@NotNull ConversationContext context, @NotNull NamedTextColor namedTextColor); } diff --git a/Core/src/main/java/net/juligames/core/config/CoreConfigurationApi.java b/Core/src/main/java/net/juligames/core/config/CoreConfigurationApi.java index a6c41cd0..107dc41b 100644 --- a/Core/src/main/java/net/juligames/core/config/CoreConfigurationApi.java +++ b/Core/src/main/java/net/juligames/core/config/CoreConfigurationApi.java @@ -1,5 +1,6 @@ package net.juligames.core.config; +import com.hazelcast.core.DistributedObject; import net.juligames.core.Core; import net.juligames.core.api.config.ConfigWriter; import net.juligames.core.api.config.Configuration; @@ -8,6 +9,7 @@ import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Unmodifiable; import java.util.*; import java.util.stream.Collectors; @@ -167,4 +169,23 @@ public Configuration database() { return Map.entry(section + "_" + after.substring(0, after.indexOf("_")), s.getValue()); }).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)))); } + + @Override + public @NotNull @Unmodifiable Collection getAll() { + return getAllHazels() + .stream() + .map(this::getOrCreate) + .collect(Collectors.toUnmodifiableSet()); + } + + @Override + public @NotNull @Unmodifiable Collection getAllHazels() { + return Core.getInstance() + .getHazelDataApi() + .getAll() + .stream() + .map(DistributedObject::getName) + .filter(s -> s.startsWith("config:")) + .collect(Collectors.toUnmodifiableSet()); + } } diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/prompt/MaterialPrompt.java b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/MaterialPrompt.java index bf3e00a3..ccec998b 100644 --- a/PaperAPI/src/main/java/net/juligames/core/paper/prompt/MaterialPrompt.java +++ b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/MaterialPrompt.java @@ -4,6 +4,7 @@ import de.bentzin.conversationlib.prompt.Prompt; import de.bentzin.conversationlib.prompt.ValidatingPrompt; import org.bukkit.Material; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -13,6 +14,7 @@ * @author Ture Bentzin * 25.03.2023 */ +@ApiStatus.AvailableSince("1.6") public abstract class MaterialPrompt extends ValidatingPrompt { @Override protected boolean isInputValid(@NotNull ConversationContext context, @NotNull String input) { diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/prompt/PlayerPrompt.java b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/PlayerPrompt.java index f9db3555..e9499ea9 100644 --- a/PaperAPI/src/main/java/net/juligames/core/paper/prompt/PlayerPrompt.java +++ b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/PlayerPrompt.java @@ -3,6 +3,7 @@ import de.bentzin.conversationlib.prompt.FixedSetPrompt; import org.bukkit.Server; import org.bukkit.entity.Player; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import java.util.Collections; @@ -11,6 +12,7 @@ * @author Ture Bentzin * 25.03.2023 */ +@ApiStatus.AvailableSince("1.6") public abstract class PlayerPrompt extends FixedSetPrompt implements ServerPrompt { private final Server server; diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/prompt/PluginManagerPrompt.java b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/PluginManagerPrompt.java index 0197e622..fac8bbbf 100644 --- a/PaperAPI/src/main/java/net/juligames/core/paper/prompt/PluginManagerPrompt.java +++ b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/PluginManagerPrompt.java @@ -2,12 +2,14 @@ import de.bentzin.conversationlib.prompt.Prompt; import org.bukkit.plugin.PluginManager; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; /** * @author Ture Bentzin * 25.03.2023 */ +@ApiStatus.AvailableSince("1.6") public interface PluginManagerPrompt extends Prompt { @NotNull PluginManager getPluginManager(); diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/prompt/PluginPrompt.java b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/PluginPrompt.java index 8bb040bc..fbb3291d 100644 --- a/PaperAPI/src/main/java/net/juligames/core/paper/prompt/PluginPrompt.java +++ b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/PluginPrompt.java @@ -3,12 +3,14 @@ import de.bentzin.conversationlib.prompt.FixedSetPrompt; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; /** * @author Ture Bentzin * 25.03.2023 */ +@ApiStatus.AvailableSince("1.6") public abstract class PluginPrompt extends FixedSetPrompt implements PluginManagerPrompt { private final PluginManager pluginManager; diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/prompt/ServerPrompt.java b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/ServerPrompt.java index c0a5aef0..25bd81a9 100644 --- a/PaperAPI/src/main/java/net/juligames/core/paper/prompt/ServerPrompt.java +++ b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/ServerPrompt.java @@ -2,11 +2,13 @@ import de.bentzin.conversationlib.prompt.Prompt; import org.bukkit.Server; +import org.jetbrains.annotations.ApiStatus; /** * @author Ture Bentzin * 25.03.2023 */ +@ApiStatus.AvailableSince("1.6") public interface ServerPrompt extends Prompt { Server getServer(); diff --git a/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PartiallPlayerPrompt.java b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PartiallPlayerPrompt.java index f7893422..5bf5b594 100644 --- a/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PartiallPlayerPrompt.java +++ b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PartiallPlayerPrompt.java @@ -4,6 +4,7 @@ import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.ProxyServer; import de.bentzin.conversationlib.prompt.FixedSetPrompt; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import java.util.Collection; @@ -13,6 +14,7 @@ * @author Ture Bentzin * 25.03.2023 */ +@ApiStatus.AvailableSince("1.6") public abstract class PartiallPlayerPrompt extends FixedSetPrompt> implements ProxyServerPrompt, PluginManagerPrompt { private final ProxyServer proxyServer; diff --git a/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PlayerPrompt.java b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PlayerPrompt.java index 4dca20b1..0bf379d8 100644 --- a/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PlayerPrompt.java +++ b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PlayerPrompt.java @@ -4,12 +4,14 @@ import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.ProxyServer; import de.bentzin.conversationlib.prompt.FixedSetPrompt; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; /** * @author Ture Bentzin * 25.03.2023 */ +@ApiStatus.AvailableSince("1.6") public abstract class PlayerPrompt extends FixedSetPrompt implements ProxyServerPrompt, PluginManagerPrompt { private final ProxyServer proxyServer; diff --git a/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PluginManagerPrompt.java b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PluginManagerPrompt.java index 1733e001..67f942d3 100644 --- a/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PluginManagerPrompt.java +++ b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PluginManagerPrompt.java @@ -2,12 +2,14 @@ import com.velocitypowered.api.plugin.PluginManager; import de.bentzin.conversationlib.prompt.Prompt; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; /** * @author Ture Bentzin * 25.03.2023 */ +@ApiStatus.AvailableSince("1.6") public interface PluginManagerPrompt extends Prompt { @NotNull PluginManager getPluginManager(); diff --git a/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PluginPrompt.java b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PluginPrompt.java index 6e326245..6aefe390 100644 --- a/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PluginPrompt.java +++ b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PluginPrompt.java @@ -3,12 +3,14 @@ import com.velocitypowered.api.plugin.PluginContainer; import com.velocitypowered.api.proxy.ProxyServer; import de.bentzin.conversationlib.prompt.FixedSetPrompt; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; /** * @author Ture Bentzin * 25.03.2023 */ +@ApiStatus.AvailableSince("1.6") public abstract class PluginPrompt extends FixedSetPrompt implements ProxyServerPrompt { private final ProxyServer proxyServer; diff --git a/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/ProxyServerPrompt.java b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/ProxyServerPrompt.java index 8392df0c..fbfea51c 100644 --- a/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/ProxyServerPrompt.java +++ b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/ProxyServerPrompt.java @@ -2,11 +2,13 @@ import com.velocitypowered.api.proxy.ProxyServer; import de.bentzin.conversationlib.prompt.Prompt; +import org.jetbrains.annotations.ApiStatus; /** * @author Ture Bentzin * 25.03.2023 */ +@ApiStatus.AvailableSince("1.6") public interface ProxyServerPrompt extends Prompt { ProxyServer getProxy(); } diff --git a/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/ServerPrompt.java b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/ServerPrompt.java index 3d4890ee..6a24dc69 100644 --- a/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/ServerPrompt.java +++ b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/ServerPrompt.java @@ -1,15 +1,16 @@ package net.juligames.core.velocity.prompt; -import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.ProxyServer; import com.velocitypowered.api.proxy.server.RegisteredServer; import de.bentzin.conversationlib.prompt.FixedSetPrompt; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; /** * @author Ture Bentzin * 25.03.2023 */ +@ApiStatus.AvailableSince("1.6") public abstract class ServerPrompt extends FixedSetPrompt implements ProxyServerPrompt { private final ProxyServer proxyServer; diff --git a/VelocityCore/src/main/java/test/ConversationTest.java b/VelocityCore/src/main/java/test/ConversationTest.java index 822598ca..5ce248ee 100644 --- a/VelocityCore/src/main/java/test/ConversationTest.java +++ b/VelocityCore/src/main/java/test/ConversationTest.java @@ -1,46 +1,17 @@ package test; -import de.bentzin.conversationlib.ConversationContext; import de.bentzin.conversationlib.manager.ConversationManager; -import de.bentzin.conversationlib.prompt.BooleanPrompt; -import de.bentzin.conversationlib.prompt.LambdaPrompt; -import de.bentzin.conversationlib.prompt.Prompt; -import net.juligames.core.adventure.api.MessageRepresentation; import net.kyori.adventure.audience.Audience; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.ComponentLike; -import org.checkerframework.checker.units.qual.A; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; /** * @author Ture Bentzin * 25.03.2023 */ public class ConversationTest { - public static void demo(){ + public static void demo() { ConversationManager conversationManager = new ConversationManager(); Audience player = Audience.empty(); - conversationManager.newBuilder().prefix( context -> Component.text("> ")) - .firstPrompt( - new LambdaPrompt(conversationContext -> Component.text("Bitte Name angeben:"), - conversationContext -> true, - (conversationContext, s) -> { - conversationContext.setData("name",s); - return new BooleanPrompt() { - @Override - protected @Nullable Prompt acceptValidatedInput(@NotNull ConversationContext context, boolean input) { - return MessageRepresentation.; - } - - @Override - public @NotNull ComponentLike getPromptMessage(@NotNull ConversationContext conversationContext) { - return MessageRepresentation.represent("ley.key", conversationContext.target()); - } - } - })) - } } From fdd4640b1469d774e97d22f9ad84e1ae87f0fd2a Mon Sep 17 00:00:00 2001 From: TDR Date: Sat, 25 Mar 2023 16:49:52 +0100 Subject: [PATCH 04/60] update ConversationLib to 1.3 --- AdventureAPI/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AdventureAPI/pom.xml b/AdventureAPI/pom.xml index a6df11f7..c93f43ed 100644 --- a/AdventureAPI/pom.xml +++ b/AdventureAPI/pom.xml @@ -48,7 +48,7 @@ de.bentzin ConversationLib - 1.2 + 1.3 From 016e7d32660f41d8ae0f00662333b45d126a5812 Mon Sep 17 00:00:00 2001 From: TDR Date: Sat, 25 Mar 2023 17:02:22 +0100 Subject: [PATCH 05/60] Create AdventureWebuiEditorAPI.java --- .../api/external/AdventureWebuiEditorAPI.java | 135 ++++++++++++++++++ 1 file changed, 135 insertions(+) create mode 100644 API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java diff --git a/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java b/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java new file mode 100644 index 00000000..e3e07b68 --- /dev/null +++ b/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java @@ -0,0 +1,135 @@ +package net.juligames.core.api.external; +/* + * This file is part of adventure-webui, licensed under the MIT License. + * + * Copyright (c) 2021 KyoriPowered + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * The adventure-webui editor API. + */ +public final class AdventureWebuiEditorAPI { + private static final Pattern TOKEN_PATTERN = Pattern.compile("\"(.*?)\""); + + private final URI root; + private final HttpClient client; + + /** + * Creates a new instance of the editor API with the given root URI. + * + * @param root the root URI + */ + public AdventureWebuiEditorAPI(final @NotNull URI root) { + this(root, HttpClient.newHttpClient()); + } + + /** + * Creates a new instance of the editor API with the given root URI and a client. + * + * @param root the root URI + * @param client the client + */ + public AdventureWebuiEditorAPI(final @NotNull URI root, final @NotNull HttpClient client) { + this.root = Objects.requireNonNull(root, "root"); + this.client = Objects.requireNonNull(client, "client"); + } + + /** + * Starts a session, returning the token. + * + * @param input the input + * @param command the command + * @param application the application name + * @return a completable future that will provide the token + */ + public @NotNull CompletableFuture startSession(final @NotNull String input, final @NotNull String command, final @NotNull String application) { + final HttpRequest request = HttpRequest.newBuilder() + .POST(HttpRequest.BodyPublishers.ofString(constructBody(input, command, application))) + .uri(root.resolve(URI.create("/api/editor/input"))) + .build(); + final CompletableFuture result = new CompletableFuture<>(); + + this.client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).thenApply(stringHttpResponse -> { + if (stringHttpResponse.statusCode() != 200) { + result.completeExceptionally(new IOException("The server could not handle the request.")); + } else { + final String body = stringHttpResponse.body(); + final Matcher matcher = TOKEN_PATTERN.matcher(body); + + while (matcher.find()) { + final String group = matcher.group(0); + if (group.equalsIgnoreCase("token")) { + result.complete(group); + } + } + + result.completeExceptionally(new IOException("The result did not contain a token.")); + } + return null; + }); + + return result; + } + + /** + * Retrieves the result of a session, given a token. + * + * @param token the token + * @return the resulting MiniMessage string in a completable future + */ + public @NotNull CompletableFuture retrieveSession(final @NotNull String token) { + final HttpRequest request = HttpRequest.newBuilder() + .GET() + .uri(root.resolve(URI.create("/api/editor/output?token=" + token))) + .build(); + final CompletableFuture result = new CompletableFuture<>(); + + this.client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).thenApply(stringHttpResponse -> { + final int statusCode = stringHttpResponse.statusCode(); + if (statusCode == 404) { + result.complete(null); + } else if (statusCode != 200) { + result.completeExceptionally(new IOException("The server could not handle the request.")); + } else { + result.complete(stringHttpResponse.body()); + } + return null; + }); + + return result; + } + + private @NotNull String constructBody(final @NotNull String input, final @NotNull String command, final @NotNull String application) { + return String.format("{\"input\":\"%s\",\"command\":\"%s\",\"application\":\"%s\"}", input, command, application); + } +} \ No newline at end of file From 61887f6fee81a372d8f41556ee08855c5b5e6a17 Mon Sep 17 00:00:00 2001 From: TDR Date: Sat, 25 Mar 2023 17:05:06 +0100 Subject: [PATCH 06/60] Create tokenfix.diff --- .../net/juligames/core/api/external/tokenfix.diff | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 API/src/main/java/net/juligames/core/api/external/tokenfix.diff diff --git a/API/src/main/java/net/juligames/core/api/external/tokenfix.diff b/API/src/main/java/net/juligames/core/api/external/tokenfix.diff new file mode 100644 index 00000000..f10ad452 --- /dev/null +++ b/API/src/main/java/net/juligames/core/api/external/tokenfix.diff @@ -0,0 +1,12 @@ +41c41 +< private static final Pattern TOKEN_PATTERN = Pattern.compile("\"(.*?)\""); +--- +> private static final Pattern TOKEN_PATTERN = Pattern.compile("\\{\"token\": \"(.*?)\"\\}"); +89,92c89,90 +< final String group = matcher.group(0); +< if (group.equalsIgnoreCase("token")) { +< result.complete(group); +< } +--- +> final String group = matcher.group(1); +> result.complete(group); \ No newline at end of file From b620675615eb2b04a38590685693ef4415c3ae0c Mon Sep 17 00:00:00 2001 From: TDR Date: Sat, 25 Mar 2023 17:11:44 +0100 Subject: [PATCH 07/60] modify api hosts --- .../api/external/AdventureWebuiEditorAPI.java | 212 ++++++++++-------- 1 file changed, 121 insertions(+), 91 deletions(-) diff --git a/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java b/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java index e3e07b68..322077a8 100644 --- a/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java +++ b/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java @@ -24,9 +24,11 @@ */ import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.TestOnly; import java.io.IOException; import java.net.URI; +import java.net.URISyntaxException; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; @@ -39,97 +41,125 @@ * The adventure-webui editor API. */ public final class AdventureWebuiEditorAPI { - private static final Pattern TOKEN_PATTERN = Pattern.compile("\"(.*?)\""); - - private final URI root; - private final HttpClient client; - - /** - * Creates a new instance of the editor API with the given root URI. - * - * @param root the root URI - */ - public AdventureWebuiEditorAPI(final @NotNull URI root) { - this(root, HttpClient.newHttpClient()); - } - - /** - * Creates a new instance of the editor API with the given root URI and a client. - * - * @param root the root URI - * @param client the client - */ - public AdventureWebuiEditorAPI(final @NotNull URI root, final @NotNull HttpClient client) { - this.root = Objects.requireNonNull(root, "root"); - this.client = Objects.requireNonNull(client, "client"); - } - - /** - * Starts a session, returning the token. - * - * @param input the input - * @param command the command - * @param application the application name - * @return a completable future that will provide the token - */ - public @NotNull CompletableFuture startSession(final @NotNull String input, final @NotNull String command, final @NotNull String application) { - final HttpRequest request = HttpRequest.newBuilder() - .POST(HttpRequest.BodyPublishers.ofString(constructBody(input, command, application))) - .uri(root.resolve(URI.create("/api/editor/input"))) - .build(); - final CompletableFuture result = new CompletableFuture<>(); - - this.client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).thenApply(stringHttpResponse -> { - if (stringHttpResponse.statusCode() != 200) { - result.completeExceptionally(new IOException("The server could not handle the request.")); - } else { - final String body = stringHttpResponse.body(); - final Matcher matcher = TOKEN_PATTERN.matcher(body); - - while (matcher.find()) { - final String group = matcher.group(0); - if (group.equalsIgnoreCase("token")) { - result.complete(group); - } + public static final URI JULIGAMES_API_PRODUCTION; + private static final Pattern TOKEN_PATTERN = Pattern.compile("\\{\"token\": \"(.*?)\"}"); + @TestOnly + public static URI JULIGAMES_API_DEVELOPMENT_A; + @TestOnly + public static URI JULIGAMES_API_DEVELOPMENT_B; + + @TestOnly + public static URI JULIGAMES_API_DEVELOPMENT_LOCAL; + + static { + try { + JULIGAMES_API_PRODUCTION = new URI("https://editor.juligames.net"); + //JULIGAMES_API_DEVELOPMENT_A = new URI("censored"); + //JULIGAMES_API_DEVELOPMENT_B = new URI("censored"); + JULIGAMES_API_DEVELOPMENT_LOCAL = new URI("https://localhost"); + } catch (URISyntaxException e) { + throw new RuntimeException(e); } + } + + private final URI root; + private final HttpClient client; + + /** + * Creates a new instance of the editor API with the given root URI. + * + * @param root the root URI + */ + public AdventureWebuiEditorAPI(final @NotNull URI root) { + this(root, HttpClient.newHttpClient()); + } + + /** + * Creates a new instance of the editor API with the default JuliGames api + */ + public AdventureWebuiEditorAPI() { + this(JULIGAMES_API_PRODUCTION, HttpClient.newHttpClient()); + } + + /** + * Creates a new instance of the editor API with the given root URI and a client. + * + * @param root the root URI + * @param client the client + */ + public AdventureWebuiEditorAPI(final @NotNull URI root, final @NotNull HttpClient client) { + this.root = Objects.requireNonNull(root, "root"); + this.client = Objects.requireNonNull(client, "client"); + } + + /** + * Creates a new instance of the editor API with the default JuliGames api and a default client. + * + * @param client the client + */ + public AdventureWebuiEditorAPI(final @NotNull HttpClient client) { + this.root = Objects.requireNonNull(JULIGAMES_API_PRODUCTION, "root"); + this.client = Objects.requireNonNull(client, "client"); + } + + /** + * Starts a session, returning the token. + * + * @param input the input + * @param command the command + * @param application the application name + * @return a completable future that will provide the token + */ + public @NotNull CompletableFuture startSession(final @NotNull String input, final @NotNull String command, final @NotNull String application) { + final HttpRequest request = HttpRequest.newBuilder().POST(HttpRequest.BodyPublishers.ofString(constructBody(input, command, application))).uri(root.resolve(URI.create("/api/editor/input"))).build(); + final CompletableFuture result = new CompletableFuture<>(); + + this.client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).thenApply(stringHttpResponse -> { + if (stringHttpResponse.statusCode() != 200) { + result.completeExceptionally(new IOException("The server could not handle the request.")); + } else { + final String body = stringHttpResponse.body(); + final Matcher matcher = TOKEN_PATTERN.matcher(body); + + while (matcher.find()) { + final String group = matcher.group(1); + result.complete(group); + } + + result.completeExceptionally(new IOException("The result did not contain a token.")); + } + return null; + }); + + return result; + } + + /** + * Retrieves the result of a session, given a token. + * + * @param token the token + * @return the resulting MiniMessage string in a completable future + */ + public @NotNull CompletableFuture retrieveSession(final @NotNull String token) { + final HttpRequest request = HttpRequest.newBuilder().GET().uri(root.resolve(URI.create("/api/editor/output?token=" + token))).build(); + final CompletableFuture result = new CompletableFuture<>(); + + this.client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).thenApply(stringHttpResponse -> { + final int statusCode = stringHttpResponse.statusCode(); + if (statusCode == 404) { + result.complete(null); + } else if (statusCode != 200) { + result.completeExceptionally(new IOException("The server could not handle the request.")); + } else { + result.complete(stringHttpResponse.body()); + } + return null; + }); + + return result; + } - result.completeExceptionally(new IOException("The result did not contain a token.")); - } - return null; - }); - - return result; - } - - /** - * Retrieves the result of a session, given a token. - * - * @param token the token - * @return the resulting MiniMessage string in a completable future - */ - public @NotNull CompletableFuture retrieveSession(final @NotNull String token) { - final HttpRequest request = HttpRequest.newBuilder() - .GET() - .uri(root.resolve(URI.create("/api/editor/output?token=" + token))) - .build(); - final CompletableFuture result = new CompletableFuture<>(); - - this.client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).thenApply(stringHttpResponse -> { - final int statusCode = stringHttpResponse.statusCode(); - if (statusCode == 404) { - result.complete(null); - } else if (statusCode != 200) { - result.completeExceptionally(new IOException("The server could not handle the request.")); - } else { - result.complete(stringHttpResponse.body()); - } - return null; - }); - - return result; - } - - private @NotNull String constructBody(final @NotNull String input, final @NotNull String command, final @NotNull String application) { - return String.format("{\"input\":\"%s\",\"command\":\"%s\",\"application\":\"%s\"}", input, command, application); - } + private @NotNull String constructBody(final @NotNull String input, final @NotNull String command, final @NotNull String application) { + return String.format("{\"input\":\"%s\",\"command\":\"%s\",\"application\":\"%s\"}", input, command, application); + } } \ No newline at end of file From f7f1126a0029d95944b72b5e05d7684f59b4de88 Mon Sep 17 00:00:00 2001 From: TDR Date: Sat, 25 Mar 2023 17:28:46 +0100 Subject: [PATCH 08/60] Update AdventureWebuiEditorAPI.java --- .../api/external/AdventureWebuiEditorAPI.java | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java b/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java index 322077a8..88e8cd44 100644 --- a/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java +++ b/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java @@ -34,6 +34,7 @@ import java.net.http.HttpResponse; import java.util.Objects; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -42,7 +43,7 @@ */ public final class AdventureWebuiEditorAPI { public static final URI JULIGAMES_API_PRODUCTION; - private static final Pattern TOKEN_PATTERN = Pattern.compile("\\{\"token\": \"(.*?)\"}"); + private static final Pattern TOKEN_PATTERN = Pattern.compile("\\{\"token\":\"(.*?)\"}"); @TestOnly public static URI JULIGAMES_API_DEVELOPMENT_A; @TestOnly @@ -51,6 +52,18 @@ public final class AdventureWebuiEditorAPI { @TestOnly public static URI JULIGAMES_API_DEVELOPMENT_LOCAL; + public static void main(String[] args) { + AdventureWebuiEditorAPI api = new AdventureWebuiEditorAPI(); + CompletableFuture juliGamesCore = api.startSession("hallo VS.json", "/reject", "JuliGamesCore"); + try { + System.out.println(juliGamesCore.get()); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } catch (ExecutionException e) { + throw new RuntimeException(e); + } + } + static { try { JULIGAMES_API_PRODUCTION = new URI("https://editor.juligames.net"); @@ -121,9 +134,10 @@ public AdventureWebuiEditorAPI(final @NotNull HttpClient client) { final String body = stringHttpResponse.body(); final Matcher matcher = TOKEN_PATTERN.matcher(body); - while (matcher.find()) { + if (matcher.find()) { final String group = matcher.group(1); result.complete(group); + return result; } result.completeExceptionally(new IOException("The result did not contain a token.")); From 01cf8052c4e43e0cccf4fb5070d0947e63276168 Mon Sep 17 00:00:00 2001 From: TDR Date: Sat, 25 Mar 2023 17:29:44 +0100 Subject: [PATCH 09/60] pattern fixed by DSeeLP Co-Authored-By: DSeeLP <46624152+Dseelp@users.noreply.github.com> --- .../juligames/core/api/external/AdventureWebuiEditorAPI.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java b/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java index 88e8cd44..83db4d6f 100644 --- a/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java +++ b/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java @@ -43,7 +43,7 @@ */ public final class AdventureWebuiEditorAPI { public static final URI JULIGAMES_API_PRODUCTION; - private static final Pattern TOKEN_PATTERN = Pattern.compile("\\{\"token\":\"(.*?)\"}"); + private static final Pattern TOKEN_PATTERN = Pattern.compile("\\{\"token\" :\"(.*?)\"}"); @TestOnly public static URI JULIGAMES_API_DEVELOPMENT_A; @TestOnly From 56fc7d48cd28323eb7d8789d4a383dd597884b99 Mon Sep 17 00:00:00 2001 From: TDR Date: Sat, 25 Mar 2023 17:30:51 +0100 Subject: [PATCH 10/60] Revert "pattern fixed by DSeeLP" This reverts commit 01cf8052c4e43e0cccf4fb5070d0947e63276168. --- .../juligames/core/api/external/AdventureWebuiEditorAPI.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java b/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java index 83db4d6f..88e8cd44 100644 --- a/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java +++ b/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java @@ -43,7 +43,7 @@ */ public final class AdventureWebuiEditorAPI { public static final URI JULIGAMES_API_PRODUCTION; - private static final Pattern TOKEN_PATTERN = Pattern.compile("\\{\"token\" :\"(.*?)\"}"); + private static final Pattern TOKEN_PATTERN = Pattern.compile("\\{\"token\":\"(.*?)\"}"); @TestOnly public static URI JULIGAMES_API_DEVELOPMENT_A; @TestOnly From de14a733d151708b3a710caceedc65ed5a19c923 Mon Sep 17 00:00:00 2001 From: TDR Date: Sat, 25 Mar 2023 17:31:32 +0100 Subject: [PATCH 11/60] Pattern fixed by DSeeLP Co-Authored-By: DSeeLP <46624152+Dseelp@users.noreply.github.com> --- .../juligames/core/api/external/AdventureWebuiEditorAPI.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java b/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java index 88e8cd44..b7db68dd 100644 --- a/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java +++ b/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java @@ -43,7 +43,7 @@ */ public final class AdventureWebuiEditorAPI { public static final URI JULIGAMES_API_PRODUCTION; - private static final Pattern TOKEN_PATTERN = Pattern.compile("\\{\"token\":\"(.*?)\"}"); + private static final Pattern TOKEN_PATTERN = Pattern.compile("\\{\"token\" *: *\"(.*?)\""); @TestOnly public static URI JULIGAMES_API_DEVELOPMENT_A; @TestOnly From 8f94ea7fe694c46204d88fd920d35d087b0f9fff Mon Sep 17 00:00:00 2001 From: TDR Date: Sat, 25 Mar 2023 17:43:46 +0100 Subject: [PATCH 12/60] add core specific methods to the AdventureWebuiEditorAPI --- .../api/external/AdventureWebuiEditorAPI.java | 98 ++++++++++++++++--- 1 file changed, 85 insertions(+), 13 deletions(-) diff --git a/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java b/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java index b7db68dd..30601a65 100644 --- a/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java +++ b/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java @@ -23,6 +23,9 @@ * SOFTWARE. */ +import net.juligames.core.api.API; +import net.juligames.core.api.message.Message; +import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.TestOnly; @@ -35,6 +38,8 @@ import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -52,18 +57,6 @@ public final class AdventureWebuiEditorAPI { @TestOnly public static URI JULIGAMES_API_DEVELOPMENT_LOCAL; - public static void main(String[] args) { - AdventureWebuiEditorAPI api = new AdventureWebuiEditorAPI(); - CompletableFuture juliGamesCore = api.startSession("hallo VS.json", "/reject", "JuliGamesCore"); - try { - System.out.println(juliGamesCore.get()); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } catch (ExecutionException e) { - throw new RuntimeException(e); - } - } - static { try { JULIGAMES_API_PRODUCTION = new URI("https://editor.juligames.net"); @@ -86,7 +79,6 @@ public static void main(String[] args) { public AdventureWebuiEditorAPI(final @NotNull URI root) { this(root, HttpClient.newHttpClient()); } - /** * Creates a new instance of the editor API with the default JuliGames api */ @@ -115,6 +107,24 @@ public AdventureWebuiEditorAPI(final @NotNull HttpClient client) { this.client = Objects.requireNonNull(client, "client"); } + public static void main(String[] args) { + AdventureWebuiEditorAPI api = new AdventureWebuiEditorAPI(); + String app = api.startSessionAndGenerateLink("hsasdhjasdasldjha", "/rainbow", "app"); + System.out.println(app); + } + + public static void maidn(String[] args) { + AdventureWebuiEditorAPI api = new AdventureWebuiEditorAPI(); + CompletableFuture juliGamesCore = api.retrieveSession("6bd7388acd3a4743867dfbd02debe9ff"); + try { + System.out.println(juliGamesCore.get()); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } catch (ExecutionException e) { + throw new RuntimeException(e); + } + } + /** * Starts a session, returning the token. * @@ -173,6 +183,68 @@ public AdventureWebuiEditorAPI(final @NotNull HttpClient client) { return result; } + @Contract(pure = true) + public @NotNull String generateLink(String token) { + return root.toString() + "?token=" + token; + } + + /** + * @param input initial miniMessage + * @param command command with {token} + * @param app app name + * @return the link + */ + @Contract(pure = true) + public @NotNull String startSessionAndGenerateLink(String input, String command, String app) { + try { + return generateLink(startSession(input, command, app).get(10, TimeUnit.SECONDS)); + } catch (InterruptedException | ExecutionException | TimeoutException e) { + throw new RuntimeException(e); + } + } + + /** + * @param command command with {token} + * @return the link + */ + @Contract(pure = true) + public @NotNull String startSessionAndGenerateLink(String command) { + try { + return generateLink(startSession("", command, API.get().getVersion()).get(10, TimeUnit.SECONDS)); + } catch (InterruptedException | ExecutionException | TimeoutException e) { + throw new RuntimeException(e); + } + } + + /** + * @param command command with {token} + * @param app app + * @return the link + */ + @Contract(pure = true) + public @NotNull String startSessionAndGenerateLink(String command, String app) { + try { + return generateLink(startSession("", command, app).get(10, TimeUnit.SECONDS)); + } catch (InterruptedException | ExecutionException | TimeoutException e) { + throw new RuntimeException(e); + } + } + + /** + * @param message the initial message + * @param command command with {token} + * @param app app + * @return the link + */ + @Contract(pure = true) + public @NotNull String startSessionAndGenerateLink(@NotNull Message message, String command, String app) { + try { + return generateLink(startSession(message.getMiniMessage(), command, app).get(10, TimeUnit.SECONDS)); + } catch (InterruptedException | ExecutionException | TimeoutException e) { + throw new RuntimeException(e); + } + } + private @NotNull String constructBody(final @NotNull String input, final @NotNull String command, final @NotNull String application) { return String.format("{\"input\":\"%s\",\"command\":\"%s\",\"application\":\"%s\"}", input, command, application); } From de389a29127e18dc0e52e4dbe564d959e7c7f427 Mon Sep 17 00:00:00 2001 From: TDR Date: Sun, 26 Mar 2023 17:50:23 +0200 Subject: [PATCH 13/60] moved files --- .../java/net/juligames/core/api/TODO.java | 2 +- .../api/external/AdventureWebuiEditorAPI.java | 23 +++-------- AdventureAPI/pom.xml | 2 +- .../prompt/ConfigurationAPIPrompt.java | 2 +- .../{ => api}/prompt/ConfigurationPrompt.java | 2 +- .../{ => api}/prompt/IndexBackedPrompt.java | 2 +- .../{ => api}/prompt/MiniMessagePrompt.java | 2 +- .../prompt/NamedTextColorPrompt.java | 2 +- .../core/paper/PaperConversationManager.java | 36 +++++++++++++++++ .../core/paper/plugin/CorePlugin.java | 1 - .../juligames/core/paper/PaperCorePlugin.java | 4 ++ .../conversation/ConversationListener.java | 33 ++++++++++++++++ .../velocity/VelocityConversationManager.java | 39 +++++++++++++++++++ .../juligames/core/velocity/VelocityCore.java | 2 + 14 files changed, 126 insertions(+), 26 deletions(-) rename AdventureAPI/src/main/java/net/juligames/core/adventure/{ => api}/prompt/ConfigurationAPIPrompt.java (88%) rename AdventureAPI/src/main/java/net/juligames/core/adventure/{ => api}/prompt/ConfigurationPrompt.java (96%) rename AdventureAPI/src/main/java/net/juligames/core/adventure/{ => api}/prompt/IndexBackedPrompt.java (96%) rename AdventureAPI/src/main/java/net/juligames/core/adventure/{ => api}/prompt/MiniMessagePrompt.java (96%) rename AdventureAPI/src/main/java/net/juligames/core/adventure/{ => api}/prompt/NamedTextColorPrompt.java (87%) create mode 100644 PaperAPI/src/main/java/net/juligames/core/paper/PaperConversationManager.java create mode 100644 PaperCore/src/main/java/net/juligames/core/paper/conversation/ConversationListener.java create mode 100644 VelocityAPI/src/main/java/net/juligames/core/velocity/VelocityConversationManager.java diff --git a/API/src/main/java/net/juligames/core/api/TODO.java b/API/src/main/java/net/juligames/core/api/TODO.java index bc7364ba..1c407060 100644 --- a/API/src/main/java/net/juligames/core/api/TODO.java +++ b/API/src/main/java/net/juligames/core/api/TODO.java @@ -8,5 +8,5 @@ */ @SuppressWarnings("JavadocDeclaration") public @interface TODO { - boolean doNotcall(); + boolean doNotcall() default false; } diff --git a/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java b/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java index 30601a65..5895b2da 100644 --- a/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java +++ b/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java @@ -107,24 +107,6 @@ public AdventureWebuiEditorAPI(final @NotNull HttpClient client) { this.client = Objects.requireNonNull(client, "client"); } - public static void main(String[] args) { - AdventureWebuiEditorAPI api = new AdventureWebuiEditorAPI(); - String app = api.startSessionAndGenerateLink("hsasdhjasdasldjha", "/rainbow", "app"); - System.out.println(app); - } - - public static void maidn(String[] args) { - AdventureWebuiEditorAPI api = new AdventureWebuiEditorAPI(); - CompletableFuture juliGamesCore = api.retrieveSession("6bd7388acd3a4743867dfbd02debe9ff"); - try { - System.out.println(juliGamesCore.get()); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } catch (ExecutionException e) { - throw new RuntimeException(e); - } - } - /** * Starts a session, returning the token. * @@ -248,4 +230,9 @@ public static void maidn(String[] args) { private @NotNull String constructBody(final @NotNull String input, final @NotNull String command, final @NotNull String application) { return String.format("{\"input\":\"%s\",\"command\":\"%s\",\"application\":\"%s\"}", input, command, application); } + + @Contract(pure = true) + public @NotNull String getClientInformation() { + return client + "@" + root; + } } \ No newline at end of file diff --git a/AdventureAPI/pom.xml b/AdventureAPI/pom.xml index c93f43ed..75e234f4 100644 --- a/AdventureAPI/pom.xml +++ b/AdventureAPI/pom.xml @@ -48,7 +48,7 @@ de.bentzin ConversationLib - 1.3 + 1.3.1 diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/ConfigurationAPIPrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/ConfigurationAPIPrompt.java similarity index 88% rename from AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/ConfigurationAPIPrompt.java rename to AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/ConfigurationAPIPrompt.java index 93d5a656..22373388 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/ConfigurationAPIPrompt.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/ConfigurationAPIPrompt.java @@ -1,4 +1,4 @@ -package net.juligames.core.adventure.prompt; +package net.juligames.core.adventure.api.prompt; import de.bentzin.conversationlib.prompt.Prompt; import net.juligames.core.api.config.ConfigurationAPI; diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/ConfigurationPrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/ConfigurationPrompt.java similarity index 96% rename from AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/ConfigurationPrompt.java rename to AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/ConfigurationPrompt.java index ad899494..bae79d26 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/ConfigurationPrompt.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/ConfigurationPrompt.java @@ -1,4 +1,4 @@ -package net.juligames.core.adventure.prompt; +package net.juligames.core.adventure.api.prompt; import de.bentzin.conversationlib.ConversationContext; import de.bentzin.conversationlib.prompt.FixedSetPrompt; diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/IndexBackedPrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/IndexBackedPrompt.java similarity index 96% rename from AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/IndexBackedPrompt.java rename to AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/IndexBackedPrompt.java index 5954e3a5..b7d22cde 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/IndexBackedPrompt.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/IndexBackedPrompt.java @@ -1,4 +1,4 @@ -package net.juligames.core.adventure.prompt; +package net.juligames.core.adventure.api.prompt; import de.bentzin.conversationlib.ConversationContext; import de.bentzin.conversationlib.prompt.Prompt; diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/MiniMessagePrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/MiniMessagePrompt.java similarity index 96% rename from AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/MiniMessagePrompt.java rename to AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/MiniMessagePrompt.java index 418810cd..999a7ad9 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/MiniMessagePrompt.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/MiniMessagePrompt.java @@ -1,4 +1,4 @@ -package net.juligames.core.adventure.prompt; +package net.juligames.core.adventure.api.prompt; import de.bentzin.conversationlib.ConversationContext; import de.bentzin.conversationlib.prompt.Prompt; diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/NamedTextColorPrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/NamedTextColorPrompt.java similarity index 87% rename from AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/NamedTextColorPrompt.java rename to AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/NamedTextColorPrompt.java index 8cc1fbb5..12798eb1 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/prompt/NamedTextColorPrompt.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/NamedTextColorPrompt.java @@ -1,4 +1,4 @@ -package net.juligames.core.adventure.prompt; +package net.juligames.core.adventure.api.prompt; import net.kyori.adventure.text.format.NamedTextColor; import org.jetbrains.annotations.ApiStatus; diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/PaperConversationManager.java b/PaperAPI/src/main/java/net/juligames/core/paper/PaperConversationManager.java new file mode 100644 index 00000000..890dc99f --- /dev/null +++ b/PaperAPI/src/main/java/net/juligames/core/paper/PaperConversationManager.java @@ -0,0 +1,36 @@ +package net.juligames.core.paper; + +import de.bentzin.conversationlib.Converser; +import de.bentzin.conversationlib.manager.ConversationManager; +import net.kyori.adventure.audience.Audience; +import org.jetbrains.annotations.NotNull; + +import java.util.Map; + +/** + * @author Ture Bentzin + * 25.03.2023 + */ +public class PaperConversationManager extends ConversationManager { + + private static PaperConversationManager instance; + + public static PaperConversationManager getInstance() { + return instance; + } + + public PaperConversationManager(@NotNull Map audienceConverserMap) { + super(audienceConverserMap); + if(instance != null) { + throw new IllegalStateException("instance is already present!"); + } + instance = this; + } + + public PaperConversationManager() { + if(instance != null) { + throw new IllegalStateException("instance is already present!"); + } + instance = this; + } +} \ No newline at end of file diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/plugin/CorePlugin.java b/PaperAPI/src/main/java/net/juligames/core/paper/plugin/CorePlugin.java index 3872387b..bdb677bd 100644 --- a/PaperAPI/src/main/java/net/juligames/core/paper/plugin/CorePlugin.java +++ b/PaperAPI/src/main/java/net/juligames/core/paper/plugin/CorePlugin.java @@ -57,7 +57,6 @@ protected CorePlugin(@NotNull final CorePluginLoader loader, @NotNull final Plug } init(loader, loader.server, description, dataFolder, file, classLoader); - PaperC } /** diff --git a/PaperCore/src/main/java/net/juligames/core/paper/PaperCorePlugin.java b/PaperCore/src/main/java/net/juligames/core/paper/PaperCorePlugin.java index 2d3e7da7..3a4b8a13 100644 --- a/PaperCore/src/main/java/net/juligames/core/paper/PaperCorePlugin.java +++ b/PaperCore/src/main/java/net/juligames/core/paper/PaperCorePlugin.java @@ -8,7 +8,9 @@ import net.juligames.core.api.jdbi.MessageDAO; import net.juligames.core.api.minigame.BasicMiniGame; import net.juligames.core.caching.MessageCaching; +import net.juligames.core.command.CoreCommandNotificationListener; import net.juligames.core.paper.bstats.Metrics; +import net.juligames.core.paper.conversation.ConversationListener; import net.juligames.core.paper.events.ServerBootFinishedEvent; import net.juligames.core.paper.minigame.StartCommand; import net.juligames.core.paper.notification.EventNotificationListener; @@ -58,6 +60,7 @@ public void onEnable() { getLogger().info("starting adventureCore v." + AdventureCore.API_VERSION); adventureCore = new AdventureCore(); adventureCore.start(); + new PaperConversationManager(); core.setOnlineRecipientProvider(() -> { List paperMessageRecipients = new java.util.ArrayList<>(Bukkit.getOnlinePlayers().stream().map(PaperMessageRecipient::new).toList()); paperMessageRecipients.add(new PaperMessageRecipient(Bukkit.getConsoleSender())); @@ -76,6 +79,7 @@ public void onEnable() { Objects.requireNonNull(getCommand("printMessageCache")).setExecutor(new PrintMessageCacheCommand()); Bukkit.getPluginManager().registerEvents(new PaperCoreEventListener(), this); + Bukkit.getPluginManager().registerEvents(new ConversationListener(), this); //Register NotificationEvent core.getNotificationApi().registerListener(new EventNotificationListener()); diff --git a/PaperCore/src/main/java/net/juligames/core/paper/conversation/ConversationListener.java b/PaperCore/src/main/java/net/juligames/core/paper/conversation/ConversationListener.java new file mode 100644 index 00000000..a8eb2d8a --- /dev/null +++ b/PaperCore/src/main/java/net/juligames/core/paper/conversation/ConversationListener.java @@ -0,0 +1,33 @@ +package net.juligames.core.paper.conversation; + +import net.juligames.core.paper.PaperConversationManager; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.server.ServerCommandEvent; +import org.jetbrains.annotations.NotNull; + +/** + * @author Ture Bentzin + * 25.03.2023 + */ +public class ConversationListener implements Listener { + + @SuppressWarnings("deprecation") + @EventHandler + public void onChat(@NotNull AsyncPlayerChatEvent event) { + //Player + if (PaperConversationManager.getInstance().handleInput(event.getPlayer(), event.getMessage())) { + event.setCancelled(true); + } + } + + @EventHandler + public void onCommand(@NotNull ServerCommandEvent serverCommandEvent) { + if (PaperConversationManager.getInstance().handleInput(serverCommandEvent.getSender(), + serverCommandEvent.getCommand())){ + serverCommandEvent.setCancelled(true); + } + } + +} diff --git a/VelocityAPI/src/main/java/net/juligames/core/velocity/VelocityConversationManager.java b/VelocityAPI/src/main/java/net/juligames/core/velocity/VelocityConversationManager.java new file mode 100644 index 00000000..c83f08ea --- /dev/null +++ b/VelocityAPI/src/main/java/net/juligames/core/velocity/VelocityConversationManager.java @@ -0,0 +1,39 @@ +package net.juligames.core.velocity; + +import de.bentzin.conversationlib.Converser; +import de.bentzin.conversationlib.manager.ConversationManager; +import net.juligames.core.api.TODO; +import net.kyori.adventure.audience.Audience; +import org.jetbrains.annotations.NotNull; + +import java.util.Map; + +/** + * @author Ture Bentzin + * 25.03.2023 + * @apiNote This currently does not support automatic input insertion! + */ +@TODO +public class VelocityConversationManager extends ConversationManager { + + private static VelocityConversationManager instance; + + public VelocityConversationManager(@NotNull Map audienceConverserMap) { + super(audienceConverserMap); + if (instance != null) { + throw new IllegalStateException("instance is already present!"); + } + instance = this; + } + + public VelocityConversationManager() { + if (instance != null) { + throw new IllegalStateException("instance is already present!"); + } + instance = this; + } + + public static VelocityConversationManager getInstance() { + return instance; + } +} diff --git a/VelocityCore/src/main/java/net/juligames/core/velocity/VelocityCore.java b/VelocityCore/src/main/java/net/juligames/core/velocity/VelocityCore.java index dc4d1e55..ee26b788 100644 --- a/VelocityCore/src/main/java/net/juligames/core/velocity/VelocityCore.java +++ b/VelocityCore/src/main/java/net/juligames/core/velocity/VelocityCore.java @@ -65,6 +65,8 @@ public void onProxyInitialization(ProxyInitializeEvent event) { adventureCore = new AdventureCore(); adventureCore.start(); + new VelocityConversationManager(); + core.setOnlineRecipientProvider(() -> { Collection recipients = new ArrayList<>(); //1. players From aaeb0febb7c891758de198115d42591d732be08c Mon Sep 17 00:00:00 2001 From: TDR Date: Sun, 26 Mar 2023 18:07:46 +0200 Subject: [PATCH 14/60] fixed exception of #33 but made everything way worse --- .../core/adventure/api/MessageRepresentation.java | 8 ++++++-- .../java/net/juligames/core/message/CoreMessageApi.java | 6 +++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java index 637b6725..9fcb4d13 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java @@ -71,12 +71,12 @@ public MessageRepresentation(@NotNull Message message) { @Contract("_, _ -> new") public static @NotNull MessageRepresentation represent(String messageKey, Pointered pointered) { return new MessageRepresentation(API.get().getMessageApi().getMessageSmart(messageKey, - pointered.get(Identity.LOCALE).orElseThrow())); + pointered.get(Identity.LOCALE).orElse(defaultLocale()))); } @Contract("_, _, _ -> new") public static @NotNull MessageRepresentation represent(String messageKey, Pointered pointered, String... replacements) { - return new MessageRepresentation(API.get().getMessageApi().getMessageSmart(messageKey, pointered.get(Identity.LOCALE).orElseThrow(), replacements)); + return new MessageRepresentation(API.get().getMessageApi().getMessageSmart(messageKey, pointered.get(Identity.LOCALE).orElse(defaultLocale()), replacements)); } @@ -89,4 +89,8 @@ public MessageRepresentation(@NotNull Message message) { public Message getMessage() { return message; } + + private static @NotNull Locale defaultLocale() { + return API.get().getMessageApi().defaultUtilLocale(); + } } diff --git a/Core/src/main/java/net/juligames/core/message/CoreMessageApi.java b/Core/src/main/java/net/juligames/core/message/CoreMessageApi.java index cfb949b9..e412480d 100644 --- a/Core/src/main/java/net/juligames/core/message/CoreMessageApi.java +++ b/Core/src/main/java/net/juligames/core/message/CoreMessageApi.java @@ -106,7 +106,7 @@ public CoreMessageApi() { } @Override - public @NotNull CoreMessage getMessage(@NotNull String messageKey, @NotNull String locale, String... replacements) { + public @NotNull CoreMessage getMessage(@NotNull String messageKey, @NotNull String locale, @Nullable String... replacements) { CoreMessage message = getMessage(messageKey, locale); Core.getInstance().getCoreLogger().debug("inserting replacements: " + Arrays.toString(replacements) + " to " + message.getMiniMessage() + "@" + message.getMessageData().getMessageKey()); insertReplacements(message, replacements); @@ -514,7 +514,7 @@ public boolean hasMessage(@NotNull String messageKey, @NotNull DBLocale locale) Collection messages = new ArrayList<>(); for (String messageKey : messageKeys) { for (MessageRecipient messageRecipient : messageRecipients) { - CoreMessage message = getMessage(messageKey, messageRecipient.supplyLocaleOrDefault()); //no fallback?! oh, fuck this could get interesting | This may cause NullPointerException - let us hope it does not... + CoreMessage message = getMessage(messageKey, Objects.requireNonNull(messageRecipient.supplyLocaleOrDefault())); //no fallback?! oh, fuck this could get interesting | This may cause NullPointerException - let us hope it does not... insertReplacements(message, replacements); if (messages.stream().noneMatch(message1 -> message1.getMessageData().getMessageKey().equals(message.getMessageData().getMessageKey()))) { messages.add(message); @@ -648,7 +648,7 @@ public boolean hasMessage(@NotNull String messageKey, @NotNull DBLocale locale) }; } - private void insertReplacements(CoreMessage coreMessage, String @NotNull ... replacements) { + private void insertReplacements(@NotNull CoreMessage coreMessage, @Nullable String... replacements) { Map map = new HashMap<>(); if (replacements == null) return; From 4688a2df2ebb174f187cfb88b1ebdd24d3cf44a3 Mon Sep 17 00:00:00 2001 From: TDR Date: Mon, 3 Apr 2023 10:32:24 +0200 Subject: [PATCH 15/60] add nowPlusThen --- .../net/juligames/core/message/CoreMessageApi.java | 13 ++++++++++++- .../paper/conversation/ConversationListener.java | 3 +++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/Core/src/main/java/net/juligames/core/message/CoreMessageApi.java b/Core/src/main/java/net/juligames/core/message/CoreMessageApi.java index e412480d..a104d7bf 100644 --- a/Core/src/main/java/net/juligames/core/message/CoreMessageApi.java +++ b/Core/src/main/java/net/juligames/core/message/CoreMessageApi.java @@ -18,6 +18,8 @@ import java.security.InvalidParameterException; import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.time.temporal.TemporalAmount; import java.util.*; import java.util.function.Function; import java.util.stream.Stream; @@ -621,6 +623,16 @@ public boolean hasMessage(@NotNull String messageKey, @NotNull DBLocale locale) return Date.from(Instant.now()); } + @Contract("_ -> new") + private @NotNull Date nowPlusThen(long fluxCompensator) { + return Date.from(Instant.now().plus(fluxCompensator, ChronoUnit.MILLIS)); + } + + @Contract("_ -> new") + private @NotNull Date nowPlusThen(TemporalAmount fluxCompensator) { + return Date.from(Instant.now().plus(fluxCompensator)); + } + /** * Support for the old replacement handling * @@ -639,7 +651,6 @@ public boolean hasMessage(@NotNull String messageKey, @NotNull DBLocale locale) Core.getInstance().getCoreLogger().debug("insert start: " + miniMessage); for (int i = 0; i < replacements.length; i++) { if (replacements[i] == null) replacements[i] = "null"; - //TODO replacements[i] = replacements[i].replace("","blank"); miniMessage = miniMessage.replace(buildPattern(i), replacements[i]); Core.getInstance().getCoreLogger().debug("insert step: " + i + " :" + miniMessage); } diff --git a/PaperCore/src/main/java/net/juligames/core/paper/conversation/ConversationListener.java b/PaperCore/src/main/java/net/juligames/core/paper/conversation/ConversationListener.java index a8eb2d8a..6a1a5f73 100644 --- a/PaperCore/src/main/java/net/juligames/core/paper/conversation/ConversationListener.java +++ b/PaperCore/src/main/java/net/juligames/core/paper/conversation/ConversationListener.java @@ -1,5 +1,7 @@ package net.juligames.core.paper.conversation; +import net.juligames.core.Core; +import net.juligames.core.api.API; import net.juligames.core.paper.PaperConversationManager; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; @@ -18,6 +20,7 @@ public class ConversationListener implements Listener { public void onChat(@NotNull AsyncPlayerChatEvent event) { //Player if (PaperConversationManager.getInstance().handleInput(event.getPlayer(), event.getMessage())) { + Core.getInstance().getCoreLogger().debug("handled input for conversing: " + event.getPlayer().getName() + ": " + event.getMessage()); event.setCancelled(true); } } From 085261518a93e75f74f19a1a61979cfc64befdb4 Mon Sep 17 00:00:00 2001 From: TDR Date: Mon, 3 Apr 2023 10:32:39 +0200 Subject: [PATCH 16/60] introducing: SUPERCORE --- SuperCore/SUPERCORE | 0 SuperCore/pom.xml | 90 +++++++++++++++++++++++++++++++++++++++++++++ pom.xml | 1 + 3 files changed, 91 insertions(+) create mode 100644 SuperCore/SUPERCORE create mode 100644 SuperCore/pom.xml diff --git a/SuperCore/SUPERCORE b/SuperCore/SUPERCORE new file mode 100644 index 00000000..e69de29b diff --git a/SuperCore/pom.xml b/SuperCore/pom.xml new file mode 100644 index 00000000..01e4b5b1 --- /dev/null +++ b/SuperCore/pom.xml @@ -0,0 +1,90 @@ + + + 4.0.0 + + net.juligames.core + JuliGamesCore + 1.6-SNAPSHOT + + + SuperCore + + + 17 + 17 + UTF-8 + + + + + + net.juligames.core + Master + 1.6-SNAPSHOT + + + net.juligames.core + PaperCore + 1.6-SNAPSHOT + + + net.juligames.core + VelocityCore + 1.6-SNAPSHOT + + + net.juligames.core + MiniGameAPI + 1.6-SNAPSHOT + + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.4.1 + + + SuperCore-${project.version}-EXPERIMENTAL + false + + + + package + + shade + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.3.0 + + + + true + net.juligames.core.master.CoreMaster + + + + + + + + + + + + juligames + Juligames Maven + https://maven.juligames.net/juligames + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index ffb1fbe1..0f61b20f 100644 --- a/pom.xml +++ b/pom.xml @@ -20,6 +20,7 @@ VelocityAPI VelocityCore MiniGameAPI + SuperCore From a135a07923d934096bfa878eb49bf8843494c62b Mon Sep 17 00:00:00 2001 From: TDR Date: Mon, 10 Apr 2023 22:12:48 +0200 Subject: [PATCH 17/60] Introduced SuperCore That was still not committed? --- SuperCore.iml | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 SuperCore.iml diff --git a/SuperCore.iml b/SuperCore.iml new file mode 100644 index 00000000..c4622759 --- /dev/null +++ b/SuperCore.iml @@ -0,0 +1,12 @@ + + + + + + + ADVENTURE + + + + + \ No newline at end of file From bf53053d47336e3ac0f2eeb3a819d7c43a5ca392 Mon Sep 17 00:00:00 2001 From: TDR Date: Mon, 10 Apr 2023 22:12:58 +0200 Subject: [PATCH 18/60] add useless Prompts --- .../adventure/api/prompt/BackedPrompt.java | 145 ++++++++++++++++++ .../api/prompt/DictionaryBackedPrompt.java | 46 ++++++ .../adventure/api/prompt/MapBackedPrompt.java | 45 ++++++ 3 files changed, 236 insertions(+) create mode 100644 AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/BackedPrompt.java create mode 100644 AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/DictionaryBackedPrompt.java create mode 100644 AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/MapBackedPrompt.java diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/BackedPrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/BackedPrompt.java new file mode 100644 index 00000000..ed8b56b1 --- /dev/null +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/BackedPrompt.java @@ -0,0 +1,145 @@ +package net.juligames.core.adventure.api.prompt; + +import de.bentzin.conversationlib.ConversationContext; +import de.bentzin.conversationlib.prompt.Prompt; +import de.bentzin.conversationlib.prompt.ValidatingPrompt; +import de.bentzin.tools.misc.SubscribableType; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.function.Function; + +/** + * @author Ture Bentzin + * 10.04.2023 + */ +public abstract class BackedPrompt extends ValidatingPrompt { + + private final @NotNull PromptBacker promptBacker; + + public BackedPrompt(@NotNull PromptBacker promptBacker) { + this.promptBacker = promptBacker; + } + + protected @NotNull PromptBacker getPromptBacker() { + return promptBacker; + } + + protected boolean isInputValid(@NotNull ConversationContext context, @NotNull String input) { + return promptBacker.canProvide(input); + } + + @Override + protected @Nullable Prompt acceptValidatedInput(@NotNull ConversationContext context, @NotNull String input) { + return acceptIndexBackedInput(context, promptBacker.provide(input)); + } + + public abstract @Nullable Prompt acceptIndexBackedInput(@NotNull ConversationContext context, @NotNull V v); + + public interface PromptBacker { + + static @NotNull PromptBacker fromFunction(@NotNull Function function) { + return new SimplePromptBacker() { + @Override + public boolean canProvide(@NotNull String string) { + return provideOrNull(string) != null; + } + + @Override + public @Nullable V provideOrNull(@NotNull String string) { + return function.apply(string); + } + }; + } + + boolean canProvide(@NotNull String string); + + @NotNull + V provide(@NotNull String string) throws NoSuchElementException; + + @Nullable + V provideOrNull(@NotNull String string); + + @NotNull + V provideOr(@NotNull String string, @NotNull V v); + + @NotNull + Optional asOptional(@NotNull String string); + + @NotNull + SubscribableType asType(@NotNull String string); + } + + /** + * A PromptBacker that works backed from the #provideOrNull(String) + * + * @param v + */ + public abstract static class SimplePromptBacker implements PromptBacker { + + @Override + public abstract boolean canProvide(@NotNull String string); + + @Override + public abstract @Nullable V provideOrNull(@NotNull String string); + + @Override + public @NotNull V provide(@NotNull String string) throws NoSuchElementException { + boolean b; + try { + b = canProvide(string); + } catch (Exception e) { + throw new NoSuchElementException("wasn't able to provide because of a failed #canProvide(String) check", e); + } + if (!b) { + throw new NoSuchElementException("wasn't able to provide for string: " + string); + } else { + try { + final V provideOrNull = provideOrNull(string); + + if (provideOrNull == null) { + throw new NoSuchElementException("Missmatch!! #canProvide indicated providing for " + string + + " was possible, but #provideOrNull returned null! NAG AUTHOR!!"); + } else { + //oh, finally + return provideOrNull; + } + + } catch (Exception e) { + throw new NoSuchElementException("wasn't able to provide because of failed #provideOrNull(String)", e); + } + + } + } + + @Override + public @NotNull V provideOr(@NotNull String string, @NotNull V v) { + return canProvide(string) ? or(this::provideOrNull, string, v) : v; + } + + @Override + public @NotNull Optional asOptional(@NotNull String string) { + return Optional.ofNullable(provideOrNull(string)); + } + + @Override + public @NotNull SubscribableType asType(@NotNull String string) { + SubscribableType vSubscribableType = new SubscribableType<>(); + if (canProvide(string)) { + vSubscribableType.set(provideOrNull(string)); + } + return vSubscribableType; + } + + private @NotNull V or(@NotNull Function function, @NotNull String string, @NotNull V backup) { + @NotNull V apply = function.apply(string); + if (apply == null) { + return backup; + } + return apply; + } + + } +} diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/DictionaryBackedPrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/DictionaryBackedPrompt.java new file mode 100644 index 00000000..68d25531 --- /dev/null +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/DictionaryBackedPrompt.java @@ -0,0 +1,46 @@ +package net.juligames.core.adventure.api.prompt; + +import de.bentzin.conversationlib.ConversationContext; +import de.bentzin.conversationlib.prompt.Prompt; +import de.bentzin.conversationlib.prompt.ValidatingPrompt; +import net.kyori.adventure.text.Component; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Collections; +import java.util.Dictionary; +import java.util.Objects; +import java.util.stream.Stream; + +/** + * @author Ture Bentzin + * 10.04.2023 + */ +@ApiStatus.AvailableSince("1.6") +public abstract class DictionaryBackedPrompt extends ValidatingPrompt { + + private final Dictionary dictionary; + + public DictionaryBackedPrompt(Dictionary index) { + this.dictionary = index; + } + + @Override + protected boolean isInputValid(@NotNull ConversationContext context, @NotNull String input) { + return Collections.list(dictionary.keys()).contains(input); + } + + @Override + protected @Nullable Prompt acceptValidatedInput(@NotNull ConversationContext context, @NotNull String input) { + return acceptIndexBackedInput(context, Objects.requireNonNull(dictionary.get(input))); + } + + public abstract @Nullable Prompt acceptIndexBackedInput(@NotNull ConversationContext context, @NotNull V v); + + @Override + protected @Nullable Component getFailedValidationText(@NotNull ConversationContext context, @NotNull String invalidInput) { + Stream stringStream = Collections.list(dictionary.keys()).stream().filter(s -> s.contains(invalidInput)); + return Component.text(" -> " + stringStream.toList() + "?"); + } +} diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/MapBackedPrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/MapBackedPrompt.java new file mode 100644 index 00000000..2ca50ae9 --- /dev/null +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/MapBackedPrompt.java @@ -0,0 +1,45 @@ +package net.juligames.core.adventure.api.prompt; + +import de.bentzin.conversationlib.ConversationContext; +import de.bentzin.conversationlib.prompt.Prompt; +import de.bentzin.conversationlib.prompt.ValidatingPrompt; +import net.kyori.adventure.text.Component; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Map; +import java.util.Objects; +import java.util.stream.Stream; + +/** + * @author Ture Bentzin + * 25.03.2023 + */ +@ApiStatus.AvailableSince("1.6") +public abstract class MapBackedPrompt extends ValidatingPrompt { + + private final Map map; + + public MapBackedPrompt(@NotNull Map map) { + this.map = map; + } + + @Override + protected boolean isInputValid(@NotNull ConversationContext context, @NotNull String input) { + return map.containsKey(input); + } + + @Override + protected @Nullable Prompt acceptValidatedInput(@NotNull ConversationContext context, @NotNull String input) { + return acceptIndexBackedInput(context, Objects.requireNonNull(map.get(input))); + } + + public abstract @Nullable Prompt acceptIndexBackedInput(@NotNull ConversationContext context, @NotNull V v); + + @Override + protected @Nullable Component getFailedValidationText(@NotNull ConversationContext context, @NotNull String invalidInput) { + Stream stringStream = map.keySet().stream().filter(s -> s.contains(invalidInput)); + return Component.text(" -> " + stringStream.toList() + "?"); + } +} From 5a472f04d3db56c569ba3544e14e1659d68d1ddb Mon Sep 17 00:00:00 2001 From: TDR Date: Mon, 10 Apr 2023 22:21:56 +0200 Subject: [PATCH 19/60] Create APIUtils.java --- .../net/juligames/core/api/misc/APIUtils.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 API/src/main/java/net/juligames/core/api/misc/APIUtils.java diff --git a/API/src/main/java/net/juligames/core/api/misc/APIUtils.java b/API/src/main/java/net/juligames/core/api/misc/APIUtils.java new file mode 100644 index 00000000..8759a11d --- /dev/null +++ b/API/src/main/java/net/juligames/core/api/misc/APIUtils.java @@ -0,0 +1,35 @@ +package net.juligames.core.api.misc; + +import org.jetbrains.annotations.NotNull; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +/** + * @author Ture Bentzin + * 10.04.2023 + */ +public class APIUtils { + + private APIUtils() { + + } + + public static boolean executedWithoutException(@NotNull Runnable runnable, Exception... exceptions) { + return executedWithoutException(runnable, List.of(exceptions)); + } + + public static boolean executedWithoutException(@NotNull Runnable runnable) { + return executedWithoutException(runnable, Collections.emptyList()); + } + + public static boolean executedWithoutException(@NotNull Runnable runnable, Collection exceptions) { + try { + runnable.run(); + return true; + } catch (Exception e) { + return !exceptions.contains(e); + } + } +} From aabca37cb0c710c4bcbb8e2dc94eb1bb355dbdfe Mon Sep 17 00:00:00 2001 From: TDR Date: Mon, 10 Apr 2023 22:28:28 +0200 Subject: [PATCH 20/60] new Misc --- .../net/juligames/core/api/misc/APIUtils.java | 23 ++++++++++++++++--- .../core/api/misc/ThrowingRunnable.java | 19 +++++++++++++++ 2 files changed, 39 insertions(+), 3 deletions(-) create mode 100644 API/src/main/java/net/juligames/core/api/misc/ThrowingRunnable.java diff --git a/API/src/main/java/net/juligames/core/api/misc/APIUtils.java b/API/src/main/java/net/juligames/core/api/misc/APIUtils.java index 8759a11d..1d9453d7 100644 --- a/API/src/main/java/net/juligames/core/api/misc/APIUtils.java +++ b/API/src/main/java/net/juligames/core/api/misc/APIUtils.java @@ -16,15 +16,32 @@ private APIUtils() { } - public static boolean executedWithoutException(@NotNull Runnable runnable, Exception... exceptions) { + public static boolean executedWithoutException(@NotNull ThrowingRunnable runnable, Exception... exceptions) { return executedWithoutException(runnable, List.of(exceptions)); } - public static boolean executedWithoutException(@NotNull Runnable runnable) { + public static boolean executedWithoutException(@NotNull ThrowingRunnable runnable) { return executedWithoutException(runnable, Collections.emptyList()); } - public static boolean executedWithoutException(@NotNull Runnable runnable, Collection exceptions) { + public static boolean executedWithoutException(@NotNull ThrowingRunnable runnable, Collection exceptions) { + try { + runnable.run(); + return true; + } catch (Exception e) { + return !exceptions.contains(e); + } + } + + public static boolean executedWithoutExceptionL(@NotNull Runnable runnable, Exception... exceptions) { + return executedWithoutExceptionL(runnable, List.of(exceptions)); + } + + public static boolean executedWithoutExceptionL(@NotNull Runnable runnable) { + return executedWithoutExceptionL(runnable, Collections.emptyList()); + } + + public static boolean executedWithoutExceptionL(@NotNull Runnable runnable, Collection exceptions) { try { runnable.run(); return true; diff --git a/API/src/main/java/net/juligames/core/api/misc/ThrowingRunnable.java b/API/src/main/java/net/juligames/core/api/misc/ThrowingRunnable.java new file mode 100644 index 00000000..f6dba906 --- /dev/null +++ b/API/src/main/java/net/juligames/core/api/misc/ThrowingRunnable.java @@ -0,0 +1,19 @@ +package net.juligames.core.api.misc; + +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + +/** + * Like a normal {@link Runnable} but it accepts Exceptions + * @author Ture Bentzin + * 10.04.2023 + */ +public interface ThrowingRunnable { + + @Contract(pure = true) + static @NotNull ThrowingRunnable fromRunnable(@NotNull Runnable runnable) { + return runnable::run; + } + + void run() throws Exception; +} From 597120eddca8745a024177dc82d43f016b5ccd81 Mon Sep 17 00:00:00 2001 From: TDR Date: Mon, 10 Apr 2023 22:28:42 +0200 Subject: [PATCH 21/60] made the useless class even more useless --- .../adventure/api/prompt/BackedPrompt.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/BackedPrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/BackedPrompt.java index ed8b56b1..6ba1cae3 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/BackedPrompt.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/BackedPrompt.java @@ -4,6 +4,8 @@ import de.bentzin.conversationlib.prompt.Prompt; import de.bentzin.conversationlib.prompt.ValidatingPrompt; import de.bentzin.tools.misc.SubscribableType; +import net.juligames.core.api.config.Interpreter; +import net.juligames.core.api.misc.APIUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -54,6 +56,24 @@ public boolean canProvide(@NotNull String string) { }; } + static @NotNull PromptBacker fromInterpreter(@NotNull Interpreter vInterpreter) { + return new SimplePromptBacker() { + @Override + public boolean canProvide(@NotNull String string) { + return APIUtils.executedWithoutException(() -> vInterpreter.interpret(string)); + } + + @Override + public @NotNull V provideOrNull(@NotNull String string) { + try { + return vInterpreter.interpret(string); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + }; + } + boolean canProvide(@NotNull String string); @NotNull From ec4ce79337baa982a1c38c04393ed2094b322e61 Mon Sep 17 00:00:00 2001 From: TDR Date: Wed, 12 Apr 2023 21:38:00 +0200 Subject: [PATCH 22/60] add primitive interfaces for interpreting and reversing --- .../core/api/config/Interpreter.java | 14 ++++++++++- .../core/api/config/PrimitiveInterpreter.java | 23 +++++++++++++++++ .../juligames/core/api/config/Reverser.java | 25 +++++++++++++++++++ 3 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 API/src/main/java/net/juligames/core/api/config/PrimitiveInterpreter.java create mode 100644 API/src/main/java/net/juligames/core/api/config/Reverser.java diff --git a/API/src/main/java/net/juligames/core/api/config/Interpreter.java b/API/src/main/java/net/juligames/core/api/config/Interpreter.java index 996faabc..7d12739b 100644 --- a/API/src/main/java/net/juligames/core/api/config/Interpreter.java +++ b/API/src/main/java/net/juligames/core/api/config/Interpreter.java @@ -1,5 +1,6 @@ package net.juligames.core.api.config; +import de.bentzin.tools.DoNotOverride; import org.jetbrains.annotations.NotNull; import java.util.function.Function; @@ -10,7 +11,7 @@ * @see BuildInInterpreters */ -public interface Interpreter { +public non-sealed interface Interpreter extends Reverser, PrimitiveInterpreter { @NotNull T interpret(final String input) throws Exception; @NotNull String reverse(T t); @@ -22,4 +23,15 @@ default R reverseAndThen(@NotNull T t, @NotNull Function function default R interpretAndThen(@NotNull String input, @NotNull Function function) throws Exception { return function.apply(interpret(input)); } + + @DoNotOverride + default Reverser asReverser() { + return this; + } + + @DoNotOverride + default PrimitiveInterpreter asIInterpreter() { + return this; + } + } diff --git a/API/src/main/java/net/juligames/core/api/config/PrimitiveInterpreter.java b/API/src/main/java/net/juligames/core/api/config/PrimitiveInterpreter.java new file mode 100644 index 00000000..f0cdf22c --- /dev/null +++ b/API/src/main/java/net/juligames/core/api/config/PrimitiveInterpreter.java @@ -0,0 +1,23 @@ +package net.juligames.core.api.config; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +/** + * This might be used later outside of this package + * @author Ture Bentzin + * 12.04.2023 + */ +@ApiStatus.Internal +public sealed interface PrimitiveInterpreter permits Interpreter{ + + /** + * Converts the given input according to this implementation to a given Object of the provided Type. + * This process is known as "interpreting the input as an instance of Type T" + * @param input the input to be interpreted + * @return the instance of T that results the interpretation + * @throws Exception will be thrown if the input cant be interpreted according to this implementation + */ + @SuppressWarnings("override") + @NotNull T interpret(final String input) throws Exception; +} diff --git a/API/src/main/java/net/juligames/core/api/config/Reverser.java b/API/src/main/java/net/juligames/core/api/config/Reverser.java new file mode 100644 index 00000000..3d993292 --- /dev/null +++ b/API/src/main/java/net/juligames/core/api/config/Reverser.java @@ -0,0 +1,25 @@ +package net.juligames.core.api.config; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +/** + * This might be used later outside of this package + * @author Ture Bentzin + * 12.04.2023 + */ +@ApiStatus.Internal +public sealed interface Reverser permits Interpreter { + + /** + * Converts the given instance of T according to this implementation to a String with the intention that this string + * can be interpreted back to the instance of T with the correct implementation of {@link Interpreter} that + * implements this {@link Reverser}. + * It should always be possible to convert t to a string! + * This process is known as "reversing the interpretation of a string back to the string" + * @param t the object to be reversed + * @return the string that was reversed from the instance of T + */ + @SuppressWarnings("override") + @NotNull String reverse(T t); +} From b7abf0b1f4f7b8c09b379ef92efe7231c26c49e2 Mon Sep 17 00:00:00 2001 From: TDR Date: Wed, 12 Apr 2023 21:54:05 +0200 Subject: [PATCH 23/60] add PrivateReversers --- .../juligames/core/api/config/Reverser.java | 68 ++++++++++++++++++- 1 file changed, 67 insertions(+), 1 deletion(-) diff --git a/API/src/main/java/net/juligames/core/api/config/Reverser.java b/API/src/main/java/net/juligames/core/api/config/Reverser.java index 3d993292..356f0837 100644 --- a/API/src/main/java/net/juligames/core/api/config/Reverser.java +++ b/API/src/main/java/net/juligames/core/api/config/Reverser.java @@ -1,15 +1,69 @@ package net.juligames.core.api.config; import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; +import java.util.function.Function; + /** * This might be used later outside of this package + * * @author Ture Bentzin * 12.04.2023 */ @ApiStatus.Internal -public sealed interface Reverser permits Interpreter { +public sealed interface Reverser permits Interpreter, Reverser.PrivateReverser { + + /** + * The function#apply should never return null + * @param function the function + * @return a reverser based on the function + * @param Type + */ + @Contract(pure = true) + static @NotNull Reverser ofFunctional(@NotNull Function function) { + return (PrivateReverser) function::apply; + } + + /** + * This will return a new {@link Reverser} that will execute the {@link #reverse(Object)} method from the given + * tReverser. This only benefits of you want to prevent casting this {@link Reverser} to a {@link Interpreter}! + * @param tReverser the reverser + * @return a new reverser + * @param T + */ + @ApiStatus.Experimental + @Contract(pure = true) + static @NotNull Reverser linkOf(@NotNull Reverser tReverser) { + return ofFunctional(tReverser::reverse); + } + + /** + * This {@link Reverser} will reverse the given object ONLY based on its toString! + * Should only be used with EXTREME caution! + * This does not respect {@link CustomInterpretable} + * @return a new reverser + * @param T + */ + @ApiStatus.Experimental + @Contract(pure = true) + static @NotNull Reverser fromToString() { + return (PrivateReverser) Object::toString; + } + + /** + * This {@link Reverser} will reverse the given object ONLY based on its {@link String#valueOf(Object)}! + * Should only be used with EXTREME caution! + * This does not respect {@link CustomInterpretable} + * @return a new reverser + * @param T + */ + @ApiStatus.Experimental + @Contract(pure = true) + static @NotNull Reverser fromValueOf() { + return (PrivateReverser) String::valueOf; + } /** * Converts the given instance of T according to this implementation to a String with the intention that this string @@ -17,9 +71,21 @@ public sealed interface Reverser permits Interpreter { * implements this {@link Reverser}. * It should always be possible to convert t to a string! * This process is known as "reversing the interpretation of a string back to the string" + * * @param t the object to be reversed * @return the string that was reversed from the instance of T */ @SuppressWarnings("override") @NotNull String reverse(T t); + + /** + * Meant ONLY for use with {@link #ofFunctional(Function)} + * @param the type + */ + @ApiStatus.Internal + @ApiStatus.Experimental + non-sealed interface PrivateReverser extends Reverser { + @Override + public abstract @NotNull String reverse(T t); + } } From edc8df7330b617156d710ff0c24614b03927fc76 Mon Sep 17 00:00:00 2001 From: TDR Date: Wed, 12 Apr 2023 21:56:58 +0200 Subject: [PATCH 24/60] added missing Annotations --- .../main/java/net/juligames/core/api/config/Interpreter.java | 3 +++ .../net/juligames/core/api/config/PrimitiveInterpreter.java | 1 + .../main/java/net/juligames/core/api/config/Reverser.java | 1 + .../juligames/core/adventure/api/prompt/BackedPrompt.java | 5 ++++- 4 files changed, 9 insertions(+), 1 deletion(-) diff --git a/API/src/main/java/net/juligames/core/api/config/Interpreter.java b/API/src/main/java/net/juligames/core/api/config/Interpreter.java index 7d12739b..6448539e 100644 --- a/API/src/main/java/net/juligames/core/api/config/Interpreter.java +++ b/API/src/main/java/net/juligames/core/api/config/Interpreter.java @@ -1,6 +1,7 @@ package net.juligames.core.api.config; import de.bentzin.tools.DoNotOverride; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import java.util.function.Function; @@ -25,11 +26,13 @@ default R interpretAndThen(@NotNull String input, @NotNull Function fu } @DoNotOverride + @ApiStatus.AvailableSince("1.6") default Reverser asReverser() { return this; } @DoNotOverride + @ApiStatus.AvailableSince("1.6") default PrimitiveInterpreter asIInterpreter() { return this; } diff --git a/API/src/main/java/net/juligames/core/api/config/PrimitiveInterpreter.java b/API/src/main/java/net/juligames/core/api/config/PrimitiveInterpreter.java index f0cdf22c..6761432c 100644 --- a/API/src/main/java/net/juligames/core/api/config/PrimitiveInterpreter.java +++ b/API/src/main/java/net/juligames/core/api/config/PrimitiveInterpreter.java @@ -9,6 +9,7 @@ * 12.04.2023 */ @ApiStatus.Internal +@ApiStatus.AvailableSince("1.6") public sealed interface PrimitiveInterpreter permits Interpreter{ /** diff --git a/API/src/main/java/net/juligames/core/api/config/Reverser.java b/API/src/main/java/net/juligames/core/api/config/Reverser.java index 356f0837..89828be5 100644 --- a/API/src/main/java/net/juligames/core/api/config/Reverser.java +++ b/API/src/main/java/net/juligames/core/api/config/Reverser.java @@ -13,6 +13,7 @@ * 12.04.2023 */ @ApiStatus.Internal +@ApiStatus.AvailableSince("1.6") public sealed interface Reverser permits Interpreter, Reverser.PrivateReverser { /** diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/BackedPrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/BackedPrompt.java index 6ba1cae3..d606484b 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/BackedPrompt.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/BackedPrompt.java @@ -5,7 +5,9 @@ import de.bentzin.conversationlib.prompt.ValidatingPrompt; import de.bentzin.tools.misc.SubscribableType; import net.juligames.core.api.config.Interpreter; +import net.juligames.core.api.config.PrimitiveInterpreter; import net.juligames.core.api.misc.APIUtils; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -17,6 +19,7 @@ * @author Ture Bentzin * 10.04.2023 */ +@ApiStatus.AvailableSince("1.6") public abstract class BackedPrompt extends ValidatingPrompt { private final @NotNull PromptBacker promptBacker; @@ -56,7 +59,7 @@ public boolean canProvide(@NotNull String string) { }; } - static @NotNull PromptBacker fromInterpreter(@NotNull Interpreter vInterpreter) { + static @NotNull PromptBacker fromInterpreter(@NotNull PrimitiveInterpreter vInterpreter) { return new SimplePromptBacker() { @Override public boolean canProvide(@NotNull String string) { From 321beb6414769f32bfc578c858bdd35b2357dc88 Mon Sep 17 00:00:00 2001 From: TDR Date: Thu, 13 Apr 2023 16:14:58 +0200 Subject: [PATCH 25/60] added a security notice to the popular POM files --- API/pom.xml | 6 +++ .../core/api/config/Interpreter.java | 44 ++++++++++++++++--- AdventureAPI/pom.xml | 6 +++ Core/pom.xml | 6 +++ PaperAPI/pom.xml | 6 +++ VelocityAPI/pom.xml | 7 ++- 6 files changed, 68 insertions(+), 7 deletions(-) diff --git a/API/pom.xml b/API/pom.xml index 9e141cfe..40440753 100644 --- a/API/pom.xml +++ b/API/pom.xml @@ -1,5 +1,11 @@ + diff --git a/API/src/main/java/net/juligames/core/api/config/Interpreter.java b/API/src/main/java/net/juligames/core/api/config/Interpreter.java index 6448539e..dcbcd387 100644 --- a/API/src/main/java/net/juligames/core/api/config/Interpreter.java +++ b/API/src/main/java/net/juligames/core/api/config/Interpreter.java @@ -4,33 +4,65 @@ import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; +import java.util.concurrent.CompletableFuture; import java.util.function.Function; -/** - * @author Ture Bentzin - * 26.11.2022 - * @see BuildInInterpreters - */ - public non-sealed interface Interpreter extends Reverser, PrimitiveInterpreter { + + /** + * Converts the given input according to this implementation to a given Object of the provided Type. + * This process is known as "interpreting the input as an instance of Type T" + * + * @param input the input to be interpreted + * @return the instance of T that results the interpretation + * @throws Exception will be thrown if the input cant be interpreted according to this implementation + */ @NotNull T interpret(final String input) throws Exception; + /** + * Converts the given instance of T according to this implementation to a String with the intention that this string + * can be interpreted back to the instance of T with the correct implementation of {@link Interpreter} that + * implements this {@link Reverser}. + * It should always be possible to convert t to a string! + * This process is known as "reversing the interpretation of a string back to the string" + * + * @param t the object to be reversed + * @return the string that was reversed from the instance of T + */ @NotNull String reverse(T t); default R reverseAndThen(@NotNull T t, @NotNull Function function) { return function.apply(reverse(t)); } + @ApiStatus.AvailableSince("1.6") + @ApiStatus.Experimental + default void reverseAndThenComplete(@NotNull T t, @NotNull CompletableFuture completableFuture) { + completableFuture.complete(reverse(t)); + } + default R interpretAndThen(@NotNull String input, @NotNull Function function) throws Exception { return function.apply(interpret(input)); } + @ApiStatus.AvailableSince("1.6") + @ApiStatus.Experimental + default void interpretAndThenComplete(@NotNull String input, @NotNull CompletableFuture completableFuture) throws Exception { + completableFuture.complete(interpret(input)); + } + + /** + * This will return a cast of this to a {@link Reverser} + */ @DoNotOverride @ApiStatus.AvailableSince("1.6") default Reverser asReverser() { return this; } + /** + * This will return a cast of this to a {@link PrimitiveInterpreter} + */ @DoNotOverride @ApiStatus.AvailableSince("1.6") default PrimitiveInterpreter asIInterpreter() { diff --git a/AdventureAPI/pom.xml b/AdventureAPI/pom.xml index 75e234f4..560539b6 100644 --- a/AdventureAPI/pom.xml +++ b/AdventureAPI/pom.xml @@ -1,5 +1,11 @@ + diff --git a/Core/pom.xml b/Core/pom.xml index 53a56847..97c20e4d 100644 --- a/Core/pom.xml +++ b/Core/pom.xml @@ -1,5 +1,11 @@ + diff --git a/PaperAPI/pom.xml b/PaperAPI/pom.xml index 3da1fa01..cf6956f3 100644 --- a/PaperAPI/pom.xml +++ b/PaperAPI/pom.xml @@ -1,5 +1,11 @@ + diff --git a/VelocityAPI/pom.xml b/VelocityAPI/pom.xml index b08aaaf6..a629a1a2 100644 --- a/VelocityAPI/pom.xml +++ b/VelocityAPI/pom.xml @@ -1,6 +1,11 @@ - + From dc2d23ab5a1a9c3f73af0b8f83c563a6f0acb6ed Mon Sep 17 00:00:00 2001 From: TDR Date: Fri, 14 Apr 2023 17:24:35 +0200 Subject: [PATCH 26/60] further javadoc progress in the api --- .../core/api/config/Interpreter.java | 61 +++- .../core/api/message/LegacyMessageType.java | 42 ++- .../core/api/message/MessageApi.java | 271 ++++++++++++++++-- .../adventure/api/prompt/SpacePrompt.java | 26 ++ .../core/adventure/api/prompt/VoidPrompt.java | 33 +++ .../paper/misc/configmapping/Autofill.java | 14 + .../ObjectifiedConfiguration.java | 129 +++++++++ 7 files changed, 544 insertions(+), 32 deletions(-) create mode 100644 AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/SpacePrompt.java create mode 100644 AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/VoidPrompt.java create mode 100644 PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/Autofill.java create mode 100644 PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/ObjectifiedConfiguration.java diff --git a/API/src/main/java/net/juligames/core/api/config/Interpreter.java b/API/src/main/java/net/juligames/core/api/config/Interpreter.java index dcbcd387..f45c9075 100644 --- a/API/src/main/java/net/juligames/core/api/config/Interpreter.java +++ b/API/src/main/java/net/juligames/core/api/config/Interpreter.java @@ -7,6 +7,35 @@ import java.util.concurrent.CompletableFuture; import java.util.function.Function; +/** + * This interface defines methods for interpreting a string as an instance of a certain type and for reversing the + * interpretation back to a string. + *

+ * This is an example implementation for interpreting Integers + *

+ * {@code
+
+ * public final class IntegerInterpreter implements Interpreter {
+ *
+ *     @Override
+ *     public Integer interpret(String input) throws Exception {
+ *         return Integer.parseInt(input);
+ *     }
+ *
+ *     @Override
+ *     public String reverse(Integer integer) {
+ *         return Integer.toString(integer);
+ *     }
+ *
+ *     public Class getType() {
+ *         return Integer.class;
+ *     }
+ * }
+ * }
+ * 
+ * + * @param the type of object that this Interpreter can interpret + */ public non-sealed interface Interpreter extends Reverser, PrimitiveInterpreter { /** @@ -14,8 +43,8 @@ public non-sealed interface Interpreter extends Reverser, PrimitiveInterpr * This process is known as "interpreting the input as an instance of Type T" * * @param input the input to be interpreted - * @return the instance of T that results the interpretation - * @throws Exception will be thrown if the input cant be interpreted according to this implementation + * @return the instance of T that results from the interpretation + * @throws Exception will be thrown if the input can't be interpreted according to this implementation */ @NotNull T interpret(final String input) throws Exception; @@ -31,20 +60,40 @@ public non-sealed interface Interpreter extends Reverser, PrimitiveInterpr */ @NotNull String reverse(T t); + /** + * Applies the given function to the result of {@link #reverse(T)} and returns its result. + * + * @param t the object to be reversed + * @param function the function to apply to the result of {@link #reverse(T)} + * @param the type of the result of the function + * @return the result of applying the function to the result of {@link #reverse(T)} + */ default R reverseAndThen(@NotNull T t, @NotNull Function function) { return function.apply(reverse(t)); } + /** + * Completes the given CompletableFuture with the result of {@link #reverse(T)}. + * + * @param t the object to be reversed + * @param completableFuture the CompletableFuture to complete with the result of {@link #reverse(T)} + * @param the type of the CompletableFuture + */ @ApiStatus.AvailableSince("1.6") @ApiStatus.Experimental default void reverseAndThenComplete(@NotNull T t, @NotNull CompletableFuture completableFuture) { completableFuture.complete(reverse(t)); } - default R interpretAndThen(@NotNull String input, @NotNull Function function) throws Exception { - return function.apply(interpret(input)); - } - + /** + * Interprets the given input according to this implementation to an instance of T and completes the given + * CompletableFuture with the result of the interpretation. This process is known as "interpreting the input as an + * instance of Type T". If the interpretation fails, an Exception will be thrown. + * + * @param input the input to be interpreted + * @param completableFuture the CompletableFuture that should be completed with the result of the interpretation + * @throws Exception will be thrown if the input cant be interpreted according to this implementation + */ @ApiStatus.AvailableSince("1.6") @ApiStatus.Experimental default void interpretAndThenComplete(@NotNull String input, @NotNull CompletableFuture completableFuture) throws Exception { diff --git a/API/src/main/java/net/juligames/core/api/message/LegacyMessageType.java b/API/src/main/java/net/juligames/core/api/message/LegacyMessageType.java index 70136dd5..82530833 100644 --- a/API/src/main/java/net/juligames/core/api/message/LegacyMessageType.java +++ b/API/src/main/java/net/juligames/core/api/message/LegacyMessageType.java @@ -5,22 +5,60 @@ import org.jetbrains.annotations.NotNull; /** - * @author Ture Bentzin - * 25.02.2023 + * The {@code LegacyMessageType} interface represents the types of formatting codes used in legacy Minecraft chat messages. + * These codes are used to change the color, formatting, and other properties of text in the chat. + * + *

The {@code LegacyMessageType} interface provides two default implementations for commonly used formatting codes: + * {@link #AMPERSAND} and {@link #SECTION}. Additionally, custom formatting codes can be created using the static + * {@link #custom(char)} method. + * + *

Note that these formatting codes are only supported in legacy Minecraft versions. Modern Minecraft versions use + * JSON-formatted chat messages instead. You are still able to use them through Spigot but it is recommended to use + * Components instead + * + * @since 1.4 */ @ApiStatus.AvailableSince("1.4") public interface LegacyMessageType { + + /** + * A {@code LegacyMessageType} implementation for the '&' formatting code. + */ @NotNull LegacyMessageType AMPERSAND = () -> '&'; + + /** + * A {@code LegacyMessageType} implementation for the '§' formatting code. + */ @NotNull LegacyMessageType SECTION = () -> '§'; + /** + * Creates a custom {@code LegacyMessageType} implementation for the specified character. + * + * @param c the formatting code character + * @return a new {@code CustomLegacyMessageType} instance for the specified character + */ @Contract(pure = true) static @NotNull CustomLegacyMessageType custom(char c) { return new CustomLegacyMessageType(c); } + /** + * Gets the formatting code character for this {@code LegacyMessageType}. + * + * @return the formatting code character + */ char getChar(); + /** + * A {@code record} implementation of {@code LegacyMessageType} for custom formatting codes. + */ record CustomLegacyMessageType(char c) implements LegacyMessageType { + + /** + * Gets the formatting code character for this {@code CustomLegacyMessageType}. + * + * @return the formatting code character + */ @Override public char getChar() { return c; diff --git a/API/src/main/java/net/juligames/core/api/message/MessageApi.java b/API/src/main/java/net/juligames/core/api/message/MessageApi.java index 89ddb624..5a293d21 100644 --- a/API/src/main/java/net/juligames/core/api/message/MessageApi.java +++ b/API/src/main/java/net/juligames/core/api/message/MessageApi.java @@ -11,26 +11,41 @@ import java.util.stream.Stream; /** + * Provides an api for accessing and managing messages and message + * replacements. + * * @author Ture Bentzin - * 18.11.2022 - * @apiNote Please consider that the core your using may not support all the operations below. If a core should not - * support one of the methods there are two options what could happen. First the core could automatically execute a similar - * Method and print a warning. If this should not be possible then the Core will throw an {@link UnsupportedOperationException} with further - * information on how to approach this issue. + * @apiNote Please consider that the core your using may not support all the + * operations below. If a core should not support one of the methods + * there are two options what could happen. First the core could + * automatically execute a similar Method and print a warning. If this + * should not be possible then the Core will throw an + * {@link UnsupportedOperationException} with further information on + * how to approach this issue. + * @since 18.11.2022 */ @SuppressWarnings("unused") public interface MessageApi { + /** + * Returns an array from a varargs input. + * + * @param ts the input arguments + * @param the type of the array elements + * @return the array + */ @SafeVarargs @ApiStatus.AvailableSince("1.5") static T[] arrFromVargs(T... ts) { return ts; } - /** - * This is an alias for {@link #arrFromVargs(Object[])} + * Alias for {@link #arrFromVargs(Object[])}. * + * @param ts the input arguments + * @param the type of the array elements + * @return the array * @apiNote You should import this method static! */ @SafeVarargs @@ -39,79 +54,288 @@ static T[] repl(T... ts) { return arrFromVargs(ts); } - //DAO + /** + * Calls a message DAO extension. + * + * @param extensionCallback the callback to call + * @param the return type of the callback + * @return the callback result + * @apiNote Internal use only. + */ @ApiStatus.Internal @ApiStatus.Experimental - - @Nullable R callMessageExtension(@NotNull ExtensionCallback extensionCallback); + @Nullable R callMessageExtension(@NotNull ExtensionCallback extensionCallback); + /** + * Calls a locale DAO extension. + * + * @param extensionCallback the callback to call + * @param the return type of the callback + * @return the callback result + * @apiNote Internal use only. + * @since experimental + */ @ApiStatus.Internal @ApiStatus.Experimental - - @Nullable R callLocaleExtension(@NotNull ExtensionCallback extensionCallback); + @Nullable R callLocaleExtension(@NotNull ExtensionCallback extensionCallback); + /** + * Calls an extension callback with a ReplacementDAO instance as the second argument. + * + * @param extensionCallback the extension callback to call + * @param the type of the return value + * @return the result of the extension callback, or null if the callback returns null + * @throws RuntimeException if the extension callback throws an exception + */ @ApiStatus.Internal @ApiStatus.Experimental - - @Nullable R callReplacementExtension(@NotNull ExtensionCallback extensionCallback); + @Nullable R callReplacementExtension(@NotNull ExtensionCallback extensionCallback); + /** + * Calls an extension callback with a ReplacementTypeDAO instance as the second argument. + * + * @param extensionCallback the extension callback to call + * @param the type of the return value + * @return the result of the extension callback, or null if the callback returns null + * @throws RuntimeException if the extension callback throws an exception + */ @ApiStatus.Internal @ApiStatus.Experimental - - @Nullable R callReplacementTypeExtension(@NotNull ExtensionCallback extensionCallback); + @Nullable R callReplacementTypeExtension(@NotNull ExtensionCallback extensionCallback); + //get + + /** + * Returns the {@link Message} with the specified message key and locale. If there is no {@link Message} with the + * specified key and locale, a FallbackMessage is returned instead. + * + * @param messageKey the key of the message to retrieve. + * @param locale the locale of the message to retrieve. + * @return the {@link Message} with the specified key and locale, or a FallbackMessage if no such message exists. + */ @NotNull Message getMessage(@NotNull String messageKey, @NotNull Locale locale); + /** + * Returns the {@link Message} with the specified message key and locale, with placeholders replaced by the specified + * replacement strings. If there is no {@link Message} with the specified key and locale, a FallbackMessage is returned + * instead. + * + * @param messageKey the key of the message to retrieve. + * @param locale the locale of the message to retrieve. + * @param replacements the replacement strings to substitute into the message. + * @return the {@link Message} with the specified key and locale, or a FallbackMessage if no such message exists. + */ @NotNull Message getMessage(@NotNull String messageKey, @NotNull Locale locale, String... replacements); + /** + * Returns the {@link Message} with the specified message key and locale string. If there is no {@link Message} with the + * specified key and locale, a FallbackMessage is returned instead. + * + * @param messageKey the key of the message to retrieve. + * @param locale the locale string of the message to retrieve. + * @return the {@link Message} with the specified key and locale, or a FallbackMessage if no such message exists. + */ @NotNull Message getMessage(@NotNull String messageKey, @NotNull String locale); + /** + * Returns the {@link Message} with the specified message key and locale string, with placeholders replaced by the specified + * replacement strings. If there is no {@link Message} with the specified key and locale, a FallbackMessage is returned + * instead. + * + * @param messageKey the key of the message to retrieve. + * @param locale the locale string of the message to retrieve. + * @param replacements the replacement strings to substitute into the message. + * @return the {@link Message} with the specified key and locale, or a FallbackMessage if no such message exists. + */ @NotNull Message getMessage(@NotNull String messageKey, @NotNull String locale, String... replacements); + + /** + * Returns the {@link Message} with the specified message key and locale string. If there is no {@link Message} with the + * specified key and locale, a FallbackMessage is returned instead. + * + * @param messageKey the key of the message to retrieve. + * @param dbLocale the locale string of the message to retrieve. + * @return the {@link Message} with the specified key and locale, or a FallbackMessage if no such message exists. + */ @NotNull Message getMessage(@NotNull String messageKey, @NotNull DBLocale dbLocale); + /** + * Returns the {@link Message} with the specified message key and locale string, with placeholders replaced by the specified + * replacement strings. If there is no {@link Message} with the specified key and locale, a FallbackMessage is returned + * instead. + * + * @param messageKey the key of the message to retrieve. + * @param dbLocale the locale string of the message to retrieve. + * @param replacements the replacement strings to substitute into the message. + * @return the {@link Message} with the specified key and locale, or a FallbackMessage if no such message exists. + */ @NotNull Message getMessage(@NotNull String messageKey, @NotNull DBLocale dbLocale, String... replacements); + /** + * Returns a collection of Messages from the MessageSystem that match the specified message key. + * + * @param messageKey the message key used to retrieve the messages + * @return a collection of messages that match the specified message key + */ @NotNull Collection getMessage(@NotNull String messageKey); + /** + * Returns a collection of Messages from the MessageSystem that match the specified message key with the + * specified replacements applied to each message. + * + * @param messageKey the message key used to retrieve the messages + * @param replacements the array of replacements to apply to the messages + * @return a collection of messages that match the specified message key with the replacements applied + */ @NotNull Collection getMessage(@NotNull String messageKey, String... replacements); + + /** + * Retrieves the message from the MessageSystem using the specified key and locale. The locale is automatically selected + * based on the provided locale parameter. + * + * @param messageKey The key to retrieve the message. + * @param locale The locale to use for the message. Can be null. + * @return The message. + */ @NotNull Message getMessageSmart(@NotNull String messageKey, @Nullable Locale locale); + /** + * Retrieves the message from the MessageSystem using the specified key, locale, and replacements. The locale is + * automatically selected based on the provided locale parameter. + * + * @param messageKey The key to retrieve the message. + * @param locale The locale to use for the message. Can be null. + * @param replacements The values to replace the placeholders in the message. + * @return The message. + */ @NotNull Message getMessageSmart(@NotNull String messageKey, @Nullable Locale locale, String... replacements); + /** + * Retrieves the message from the MessageSystem using the specified key and locale. The locale is automatically selected + * based on the provided locale parameter. + * + * @param messageKey The key to retrieve the message. + * @param locale The locale to use for the message. + * @return The message. + */ @NotNull Message getMessageSmart(@NotNull String messageKey, @NotNull String locale); + /** + * Retrieves the message from the MessageSystem using the specified key, locale, and replacements. The locale is + * automatically selected based on the provided locale parameter. + * + * @param messageKey The key to retrieve the message. + * @param locale The locale to use for the message. + * @param replacements The values to replace the placeholders in the message. + * @return The message. + */ @NotNull Message getMessageSmart(@NotNull String messageKey, @NotNull String locale, String... replacements); + /** + * Retrieves the message from the MessageSystem using the specified key and locale. The locale is automatically selected + * based on the provided locale parameter. + * + * @param messageKey The key to retrieve the message. + * @param dbLocale The DBLocale to use for the message. + * @return The message. + */ @NotNull Message getMessageSmart(@NotNull String messageKey, @NotNull DBLocale dbLocale); + /** + * Retrieves the message from the MessageSystem using the specified key, locale, and replacements. The locale is + * automatically selected based on the provided locale parameter. + * + * @param messageKey The key to retrieve the message. + * @param dbLocale The DBLocale to use for the message. + * @param replacements The values to replace the placeholders in the message. + * @return The message. + */ @NotNull Message getMessageSmart(@NotNull String messageKey, @NotNull DBLocale dbLocale, String... replacements); + + /** + * Returns all messages for the specified {@link Locale}. + * + * @param locale the {@code Locale} used to filter the messages + * @return a collection of all messages for the specified {@code Locale}, or an empty collection if none were found + */ @NotNull Collection getAllFromLocale(@NotNull Locale locale); + /** + * Returns all messages for the specified {@link Locale} with replacements applied. + * + * @param locale the {@code Locale} used to filter the messages + * @param replacements an optional list of replacements to apply to the messages + * @return a collection of all messages for the specified {@code Locale}, with replacements applied, or an empty collection if none were found + */ @NotNull Collection getAllFromLocale(@NotNull Locale locale, String... replacements); + /** + * Returns all messages for the specified locale code. + * + * @param locale the locale code used to filter the messages + * @return a collection of all messages for the specified locale code, or an empty collection if none were found + */ @NotNull Collection getAllFromLocale(@NotNull String locale); + /** + * Returns all messages for the specified locale code with replacements applied. + * + * @param locale the locale code used to filter the messages + * @param replacements an optional list of replacements to apply to the messages + * @return a collection of all messages for the specified locale code, with replacements applied, or an empty collection if none were found + */ @NotNull Collection getAllFromLocale(@NotNull String locale, String... replacements); + /** + * Returns all messages for the specified database locale. + * + * @param dbLocale the database locale used to filter the messages + * @return a collection of all messages for the specified database locale, or an empty collection if none were found + */ @NotNull Collection getAllFromLocale(@NotNull DBLocale dbLocale); + /** + * Returns all messages for the specified database locale with replacements applied. + * + * @param dbLocale the database locale used to filter the messages + * @param replacements an optional list of replacements to apply to the messages + * @return a collection of all messages for the specified database locale, with replacements applied, or an empty collection if none were found + */ @NotNull Collection getAllFromLocale(@NotNull DBLocale dbLocale, String... replacements); + + /** + * Returns all messages in the message system. + * This method is experimental and may be removed or changed in a future release. + * + * @return A collection of all messages in the message system. + */ @ApiStatus.Experimental - @NotNull - Collection getAll(); + @NotNull Collection getAll(); + /** + * Returns all messages in the message system with the given replacements. + * This method is experimental and may be removed or changed in a future release. + * + * @param replacements The replacements for the messages. + * @return A collection of all messages in the message system with the given replacements. + */ @ApiStatus.Experimental - @NotNull - Collection getAll(String... replacements); + @NotNull Collection getAll(String... replacements); + /** + * Returns a stream of all the database messages in the message system. + * This method is internal and should not be used outside of the message system implementation. + * + * @return A stream of all the database messages in the message system. + */ @ApiStatus.Internal - @NotNull - Stream streamData(); + @NotNull Stream streamData(); + @NotNull Collection getReplacers(); @@ -224,8 +448,7 @@ static T[] repl(T... ts) { * @deprecated use {@link MessageApi#sendMessageSmart(Collection, Collection, String...)} instead */ @Deprecated - @NotNull - MultiMessagePostScript sendMessage(@NotNull Collection messageKeys, @NotNull Collection messageRecipients, String... replacement); + @NotNull MultiMessagePostScript sendMessage(@NotNull Collection messageKeys, @NotNull Collection messageRecipients, String... replacement); @NotNull MultiMessagePostScript sendMessage(@NotNull Collection messageKeys, @NotNull MessageRecipient messageRecipient, @NotNull String overrideLocale, String... replacement); diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/SpacePrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/SpacePrompt.java new file mode 100644 index 00000000..daccbf37 --- /dev/null +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/SpacePrompt.java @@ -0,0 +1,26 @@ +package net.juligames.core.adventure.api.prompt; + +import de.bentzin.conversationlib.ConversationContext; +import de.bentzin.conversationlib.prompt.MessagePrompt; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.ComponentLike; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +/** + * This prompt only displays a single line that defaults to " ". + * You can set "spaceprompt.text" (in {@link ConversationContext#sessionData()}) to a {@link String} or a {@link ComponentLike} + * - if you do this the default message will be replaced to the content of "spaceprompt.text" + * + * @author Ture Bentzin + * 14.04.2023 + */ +@ApiStatus.AvailableSince("1.6") +public abstract class SpacePrompt extends MessagePrompt { + + @Override + public final @NotNull ComponentLike getPromptMessage(@NotNull ConversationContext conversationContext) { + final Object object = conversationContext.getData("spaceprompt.text"); + return object instanceof ComponentLike componentLike ? componentLike : Component.text(object instanceof String plaintext ? plaintext : " "); + } +} diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/VoidPrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/VoidPrompt.java new file mode 100644 index 00000000..b59034d2 --- /dev/null +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/VoidPrompt.java @@ -0,0 +1,33 @@ +package net.juligames.core.adventure.api.prompt; + +import de.bentzin.conversationlib.ConversationContext; +import de.bentzin.conversationlib.prompt.Prompt; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.ComponentLike; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * This prompt sends an empty message + * + * @author Ture Bentzin + * 14.04.2023 + */ +public final class VoidPrompt implements Prompt { + + @Override + public @NotNull ComponentLike getPromptMessage(@NotNull ConversationContext conversationContext) { + return Component.empty(); + } + + @Override + public boolean blocksForInput(@NotNull ConversationContext context) { + return false; + } + + @Override + public @Nullable Prompt getNextPrompt(@NotNull ConversationContext conversationContext, @Nullable String input) { + return END_OF_CONVERSATION; + } + +} diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/Autofill.java b/PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/Autofill.java new file mode 100644 index 00000000..bfd2ebf0 --- /dev/null +++ b/PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/Autofill.java @@ -0,0 +1,14 @@ +package net.juligames.core.paper.misc.configmapping; + +import org.jetbrains.annotations.ApiStatus; + +/** + * @author Ture Bentzin + * 14.04.2023 + */ +@ApiStatus.AvailableSince("1.6") +public @interface Autofill { + String defaultName = ""; + + String customName() default defaultName; +} diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/ObjectifiedConfiguration.java b/PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/ObjectifiedConfiguration.java new file mode 100644 index 00000000..5b652680 --- /dev/null +++ b/PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/ObjectifiedConfiguration.java @@ -0,0 +1,129 @@ +package net.juligames.core.paper.misc.configmapping; + +import org.bukkit.configuration.ConfigurationSection; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.Optional; + +/** + * This class provides a convenient way to map configuration files to Java classes in your plugins. + * When you create a subclass of {@link ObjectifiedConfiguration}, you can add your configuration variables as fields to the class, + * and they will be automatically populated with the execution of the constructor {@link #ObjectifiedConfiguration(ConfigurationSection)}. + * You need to annotate the fields you would like to be automatically filled with @{@link Autofill}. + *

+ * The @{@link Autofill} annotation is used to mark fields that should be automatically populated with values from the configuration file. + * The {@link ObjectifiedConfiguration} class uses reflection to look up the fields in the subclass and then populates + * them with the appropriate values from the associated {@link ConfigurationSection}. + *

+ * The ObjectifiedConfiguration class provides methods to save and reload the associated configuration file. + * The {@link #save()} method saves the current values of the fields to the associated {@link ConfigurationSection}. + * The {@link #reload()} method reads the current values of the fields from the associated {@link ConfigurationSection}. + *

+ * Example implementation: + * + *

{@code
+ * package com.example.plugin;
+ *
+ * import org.bukkit.configuration.ConfigurationSection;
+ * import net.juligames.core.paper.misc.configmapping.Autofill;
+ * import net.juligames.core.paper.misc.configmapping.ObjectifiedConfiguration;
+ *
+ * public class MyConfig extends ObjectifiedConfiguration {
+ *
+ *     @Autofill
+ *     public String databaseUsername = "defaultUsername";
+ *
+ *     @Autofill
+ *     public String databasePassword = "defaultPassword";
+ *
+ *     public MyConfig(ConfigurationSection section) {
+ *         super(section);
+ *     }
+ *
+ * }
+ * }
+ * + * In this example, the {@code MyConfig} class extends {@link ObjectifiedConfiguration} and has two fields marked with the @{@link Autofill} + * annotation. These fields will be automatically populated with values from the associated configuration file. + * You can also manually {@link #save()} or {@link #reload()} the config. + * + * @author Ture Bentzin + * 14.04.2023 + */ +@SuppressWarnings("ClassCanBeRecord") +@ApiStatus.Experimental +@ApiStatus.AvailableSince("1.6") +public class ObjectifiedConfiguration { + + private final @NotNull ConfigurationSection associatedSection; + + public ObjectifiedConfiguration(@NotNull ConfigurationSection associatedSection) { + this.associatedSection = associatedSection; + reload(); + } + + public final @NotNull ConfigurationSection getAssociatedSection() { + return associatedSection; + } + + public void reload() { + Arrays.stream(this.getClass().getFields()).forEachOrdered(this::reload); + } + + public void save() { + Arrays.stream(this.getClass().getFields()).forEachOrdered(this::save); + } + + public void save(@NotNull Field field) { + if (field.getDeclaringClass().equals(this.getClass())) { + String key = getKeyForField(field); + //time to set the value + try { + getAssociatedSection().set(key, field.get(this)); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + + } + } + + private String getKeyForField(@NotNull Field field) { + return + Arrays.stream( + field.getAnnotations()) + .filter(annotation -> annotation.annotationType().equals(Autofill.class)) + .map(annotation -> (Autofill) annotation) + .findFirst() + .flatMap(annotation -> { + if (!annotation.customName().equals(Autofill.defaultName)) + return annotation.customName().describeConstable(); + return Optional.empty(); + }).orElse(field.getName()); + } + + protected final void reload(@NotNull Field field) { + if (field.getDeclaringClass().equals(this.getClass())) { + String key = getKeyForField(field); + //check for default + try { + //time to get the value from section + field.set(this, extractDefault(field) + .map(o1 -> getAssociatedSection() + .get(key, o1)) + .orElseGet(() -> getAssociatedSection() + .get(key))); + + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } + } + + protected final Optional extractDefault(@NotNull Field field) throws IllegalAccessException { + final Object o = field.get(this); + return Optional.ofNullable(o); + } +} From 8c3e9d35e94675d89ef7ed0d2560689e9be78fed Mon Sep 17 00:00:00 2001 From: TDR Date: Fri, 14 Apr 2023 18:05:52 +0200 Subject: [PATCH 27/60] finish javadoc of MessageApi --- .../core/api/message/MessageApi.java | 493 +++++++++++++++++- 1 file changed, 484 insertions(+), 9 deletions(-) diff --git a/API/src/main/java/net/juligames/core/api/message/MessageApi.java b/API/src/main/java/net/juligames/core/api/message/MessageApi.java index 5a293d21..93b5512a 100644 --- a/API/src/main/java/net/juligames/core/api/message/MessageApi.java +++ b/API/src/main/java/net/juligames/core/api/message/MessageApi.java @@ -10,6 +10,20 @@ import java.util.Locale; import java.util.stream.Stream; +/* +The MessageApi interface is a high-level API for sending messages to various recipients. +It defines methods for sending single or multiple messages, with or without message key replacement, to either a single recipient or a collection of recipients. + +The interface defines two types of message sending methods: sendMessage and broadcastMessage. +The sendMessage method is used to send a message to a single recipient, while the broadcastMessage method is used to send a message to multiple recipients. +Both methods have several overloaded versions to accommodate different scenarios, such as sending messages with or without message key replacements, specifying the default or override locales, and so on. + +The MessageApi interface also provides two methods to retrieve the default locale, defaultLocale and defaultUtilLocale. +These methods return the default locale as a string and a java.util.Locale object, respectively. + +Overall, the MessageApi interface is a powerful and flexible API for sending messages, suitable for a wide range of use cases. + */ + /** * Provides an api for accessing and managing messages and message * replacements. @@ -337,142 +351,603 @@ static T[] repl(T... ts) { @NotNull Stream streamData(); + /** + * Returns a collection of all the replacers in the message system. + * + * @return a collection of all the replacers + */ @NotNull Collection getReplacers(); + //register + /** + * Registers a message with the specified message key. + * + * @param messageKey the message key to register + * @deprecated This method is deprecated and should be avoided. Instead, use the {@link #registerMessage(String, String)} + * method to register a message with a defaultMiniMessage. + */ @Deprecated void registerMessage(@NotNull String messageKey); + /** + * Registers a message with the specified message key and default mini message. + * + * @param messageKey the message key to register + * @param defaultMiniMessage the default mini message for the message (EN_US) + */ void registerMessage(@NotNull String messageKey, @NotNull String defaultMiniMessage); /** - * If you want to register a legacyMessage please use the provided method in the AdventureAPI + * Registers a third-party message with the specified message key, third-party message, and custom message dealer. + * If you want to register a legacy message, please use the provided method in the AdventureAPI. * - * @param messageKey the ley - * @param thirdPartyMessage the input - * @param dealer the dealer + * @param messageKey the message key to register + * @param thirdPartyMessage the third-party message to register (EN_US) + * @param dealer the custom message dealer to convert the third-party message to a message that can be handled + * by the message system + * @since 1.4 */ @ApiStatus.AvailableSince("1.4") void registerThirdPartyMessage(@NotNull String messageKey, @NotNull String thirdPartyMessage, @NotNull CustomMessageDealer dealer); + + /** + * Checks if a message exists in EN_US for the given message key in the message system. + * + * @param messageKey the key of the message to check + * @return {@code true} if a message exists for the given key, otherwise {@code false} + */ boolean hasMessage(@NotNull String messageKey); + /** + * Checks if a message exists for the given message key and locale in the message system. + * + * @param messageKey the key of the message to check + * @param locale the locale of the message to check + * @return {@code true} if a message exists for the given key and locale, otherwise {@code false} + */ boolean hasMessage(@NotNull String messageKey, @NotNull String locale); + /** + * Checks if a message exists for the given message key and locale in the message system. + * + * @param messageKey the key of the message to check + * @param locale the locale of the message to check + * @return {@code true} if a message exists for the given key and locale, otherwise {@code false} + */ boolean hasMessage(@NotNull String messageKey, @NotNull Locale locale); + /** + * Checks if a message exists for the given message key and locale in the message system. + * + * @param messageKey the key of the message to check + * @param locale the locale of the message to check + * @return {@code true} if a message exists for the given key and locale, otherwise {@code false} + */ boolean hasMessage(@NotNull String messageKey, @NotNull DBLocale locale); + //send + /** + * Sends a message to the specified recipient and returns a {@link MessagePostScript} that contains details about + * the message that was sent. The best locale for the message is determined via the {@link MessageRecipient}. + * + * @param messageKey the key of the message to send. + * @param messageRecipient the recipient of the message. + * @return a {@link MessagePostScript} that contains details about the sent message. + */ @NotNull MessagePostScript sendMessage(@NotNull String messageKey, @NotNull MessageRecipient messageRecipient); + /** + * Sends the message with the specified message key to the given message recipient using the provided override locale. + * + * @param messageKey the message key + * @param messageRecipient the recipient of the message + * @param overrideLocale the locale to use instead of the best available locale for the recipient + * @return a MessagePostScript providing details about the sent message + */ @NotNull MessagePostScript sendMessage(@NotNull String messageKey, @NotNull MessageRecipient messageRecipient, @NotNull Locale overrideLocale); + /** + * Sends the message with the specified message key to the given message recipient using the provided override locale. + * + * @param messageKey the message key + * @param messageRecipient the recipient of the message + * @param overrideLocale the locale to use instead of the best available locale for the recipient as a string in the format of "language_country" + * @return a MessagePostScript providing details about the sent message + */ @NotNull MessagePostScript sendMessage(@NotNull String messageKey, @NotNull MessageRecipient messageRecipient, @NotNull String overrideLocale); + /** + * Sends the message with the specified message key to the given message recipient using the provided override locale. + * + * @param messageKey the message key + * @param messageRecipient the recipient of the message + * @param overrideLocale the locale to use instead of the best available locale for the recipient + * @return a MessagePostScript providing details about the sent message + */ @NotNull MessagePostScript sendMessage(@NotNull String messageKey, @NotNull MessageRecipient messageRecipient, @NotNull DBLocale overrideLocale); + /** + * Sends a message to all available recipients with the specified message key and default locale. + * + * @param messageKey the key of the message to be sent + * @param defaultLocale the default locale to be used for the message + * @return a {@link MultiMessagePostScript} describing the details of the messages sent + */ @NotNull MultiMessagePostScript broadcastMessage(@NotNull String messageKey, @NotNull Locale defaultLocale); + /** + * Sends a message to all available recipients with the specified message key and default locale. + * + * @param messageKey the key of the message to be sent + * @param defaultLocale the default locale to be used for the message + * @return a {@link MultiMessagePostScript} describing the details of the messages sent + */ @NotNull MultiMessagePostScript broadcastMessage(@NotNull String messageKey, @NotNull String defaultLocale); + /** + * Sends a message to all available recipients with the specified message key and default locale. + * + * @param messageKey the key of the message to be sent + * @param defaultLocale the default locale to be used for the message + * @return a {@link MultiMessagePostScript} describing the details of the messages sent + */ @NotNull MultiMessagePostScript broadcastMessage(@NotNull String messageKey, @NotNull DBLocale defaultLocale); + + /** + * Sends the message with the given {@code messageKey} to all available recipients and returns the + * {@link Collection} of {@link MessagePostScript}s containing details about each sent message. + * + * @param messageKey the key of the message to send + * @return a {@link Collection} of {@link MessagePostScript}s containing details about each sent message + */ @NotNull Collection broadcastMessage(@NotNull String messageKey); + + /** + * Sends multiple messages to the same recipient. + * + * @param messageKeys the collection of message keys to send + * @param messageRecipient the recipient of the messages + * @return the post-script describing the details of the messages sent + */ @NotNull MultiMessagePostScript sendMessage(@NotNull Collection messageKeys, @NotNull MessageRecipient messageRecipient); + /** + * Sends multiple messages to multiple recipients. + * + * @param messageKeys the collection of message keys to send + * @param messageRecipients the collection of recipients of the messages + * @return the post-script describing the details of the messages sent + */ @NotNull MultiMessagePostScript sendMessage(@NotNull Collection messageKeys, @NotNull Collection messageRecipients); + + /** + * Sends multiple messages to the same recipient with the given locale override. + * + * @param messageKeys the collection of message keys + * @param messageRecipient the message recipient + * @param overrideLocale the locale override + * @return the MultiMessagePostScript representing the sent messages + */ @NotNull MultiMessagePostScript sendMessage(@NotNull Collection messageKeys, @NotNull MessageRecipient messageRecipient, @NotNull String overrideLocale); + /** + * Sends multiple messages to the same recipient with the given locale override. + * + * @param messageKeys the collection of message keys + * @param messageRecipient the message recipient + * @param overrideLocale the locale override + * @return the MultiMessagePostScript representing the sent messages + */ @NotNull MultiMessagePostScript sendMessage(@NotNull Collection messageKeys, @NotNull MessageRecipient messageRecipient, @NotNull Locale overrideLocale); + /** + * Sends multiple messages to the same recipient with the given locale override. + * + * @param messageKeys the collection of message keys + * @param messageRecipient the message recipient + * @param overrideLocale the locale override + * @return the MultiMessagePostScript representing the sent messages + */ @NotNull MultiMessagePostScript sendMessage(@NotNull Collection messageKeys, @NotNull MessageRecipient messageRecipient, @NotNull DBLocale overrideLocale); - @NotNull MultiMessagePostScript sendMessage(@NotNull Collection messageKeys, @NotNull Collection messageRecipients, @NotNull String overrideLocale); + /** + * Sends a message composed of the given message keys to the specified message recipient, using the specified locale + * to override the default locale set in the recipient. + * + * @param messageKeys the collection of message keys to compose the message + * @param messageRecipients the collection of message recipients to send the message to + * @param overrideLocale the locale to use for message translation, overriding the recipient's default locale + * @return a MultiMessagePostScript containing details about the messages that were sent + */ @NotNull MultiMessagePostScript sendMessage(@NotNull Collection messageKeys, @NotNull Collection messageRecipients, @NotNull Locale overrideLocale); + /** + * Sends a message composed of the given message keys to the specified message recipient, using the specified DBLocale + * to override the default locale set in the recipient. + * + * @param messageKeys the collection of message keys to compose the message + * @param messageRecipients the collection of message recipients to send the message to + * @param overrideLocale the DBLocale to use for message translation, overriding the recipient's default locale + * @return a MultiMessagePostScript containing details about the messages that were sent + */ @NotNull MultiMessagePostScript sendMessage(@NotNull Collection messageKeys, @NotNull Collection messageRecipients, @NotNull DBLocale overrideLocale); + /** + * Sends a message composed of the given message keys to the specified message recipient, using the specified locale + * code (e.g. "EN_US") to override the default locale set in the recipient. + * + * @param messageKeys the collection of message keys to compose the message + * @param messageRecipients the collection of message recipients to send the message to + * @param overrideLocale the locale code to use for message translation, overriding the recipient's default locale + * @return a MultiMessagePostScript containing details about the messages that were sent + */ + @NotNull MultiMessagePostScript sendMessage(@NotNull Collection messageKeys, @NotNull Collection messageRecipients, @NotNull String overrideLocale); + + /** + * Sends the given messages to the given recipients, replacing any placeholders in the messages with the given replacements. + * The locale for each message is determined based on the locale of the recipient. + * + * @param messageKeys the keys of the messages to send + * @param messageRecipients the recipients to send the messages to + * @param replacement the replacements to use for any placeholders in the messages + * @return a collection of MultiMessagePostScript objects describing the messages that were sent + */ @NotNull Collection sendMessageSmart(@NotNull Collection messageKeys, @NotNull Collection messageRecipients, String... replacement); + /** + * Sends the message with the given message key to the specified collection of recipients. + * + * @param messageKey the message key + * @param messageRecipients the collection of message recipients + * @return a collection of {@link MessagePostScript} objects describing the details of each message sent + */ @NotNull Collection sendMessage(@NotNull String messageKey, @NotNull Collection messageRecipients); + /** + * Sends a message with the given message key to a collection of message recipients with an overridden locale. + * + * @param messageKey The message key to use. + * @param messageRecipients The collection of message recipients to send the message to. + * @param overrideLocale The locale to use instead of the recipients' default locale. + * @return A MultiMessagePostScript containing details about the sent messages. + */ @NotNull MultiMessagePostScript sendMessage(@NotNull String messageKey, @NotNull Collection messageRecipients, @NotNull String overrideLocale); + /** + * Sends a message with the given message key to a collection of message recipients with an overridden locale. + * + * @param messageKey The message key to use. + * @param messageRecipients The collection of message recipients to send the message to. + * @param overrideLocale The locale to use instead of the recipients' default locale. + * @return A MultiMessagePostScript containing details about the sent messages. + */ @NotNull MultiMessagePostScript sendMessage(@NotNull String messageKey, @NotNull Collection messageRecipients, @NotNull Locale overrideLocale); + /** + * Sends a message with the given message key to a collection of message recipients with an overridden locale. + * + * @param messageKey The message key to use. + * @param messageRecipients The collection of message recipients to send the message to. + * @param overrideLocale The locale to use instead of the recipients' default locale. + * @return A MultiMessagePostScript containing details about the sent messages. + */ @NotNull MultiMessagePostScript sendMessage(@NotNull String messageKey, @NotNull Collection messageRecipients, @NotNull DBLocale overrideLocale); + /** + * Sends a message with the given message key and replacements to the specified recipients. + * + * @param messageKey the message key for the message to be sent + * @param messageRecipients the recipients to send the message to + * @param replacements replacements to be made in the message + * @return a collection of {@code MessagePostScript} objects representing the details of the sent messages + */ @NotNull Collection sendMessage(@NotNull String messageKey, @NotNull Collection messageRecipients, String... replacements); + /** + * Sends a message with the given message key, replacements, and locale override to the specified recipients. + * + * @param messageKey the message key for the message to be sent + * @param messageRecipients the recipients to send the message to + * @param overrideLocale the locale to use for the message, overriding any default locale + * @param replacements replacements to be made in the message + * @return a {@code MultiMessagePostScript} object representing the details of the sent messages + */ @NotNull MultiMessagePostScript sendMessage(@NotNull String messageKey, @NotNull Collection messageRecipients, @NotNull String overrideLocale, String... replacements); + /** + * Sends a message with the given message key, replacements, and locale override to the specified recipients. + * + * @param messageKey the message key for the message to be sent + * @param messageRecipients the recipients to send the message to + * @param overrideLocale the locale to use for the message, overriding any default locale + * @param replacements replacements to be made in the message + * @return a {@code MultiMessagePostScript} object representing the details of the sent messages + */ @NotNull MultiMessagePostScript sendMessage(@NotNull String messageKey, @NotNull Collection messageRecipients, @NotNull Locale overrideLocale, String... replacements); - @NotNull MultiMessagePostScript sendMessage(@NotNull String messageKey, @NotNull Collection messageRecipients, @NotNull DBLocale overrideLocale, String... replacements); - + /** + * Sends a message with a specific message key to a collection of message recipients, + * with the option to override the default locale for message retrieval. + * + * @param messageKey the key for the message to be sent + * @param messageRecipients the collection of message recipients to receive the message + * @param overrideLocale the locale to use for message retrieval, overriding the default locale + * @param replacements the replacement values to be used in the message, if any + * @return the post-script for the message sending operation + */ + @NotNull + MultiMessagePostScript sendMessage(@NotNull String messageKey, @NotNull Collection messageRecipients, + @NotNull DBLocale overrideLocale, String... replacements); + /** + * Sends the specified message to multiple recipients with the specified default locale. + * + * @param messageKeys a collection of keys of the messages to be sent + * @param defaultLocale the default locale for the messages + * @return a {@link MultiMessagePostScript} object representing the result of the messages sent + */ @NotNull MultiMessagePostScript broadcastMessage(@NotNull Collection messageKeys, @NotNull Locale defaultLocale); + /** + * Sends the specified message to multiple recipients with the specified default locale. + * + * @param messageKeys a collection of keys of the messages to be sent + * @param defaultLocale the default locale for the messages + * @return a {@link MultiMessagePostScript} object representing the result of the messages sent + */ @NotNull MultiMessagePostScript broadcastMessage(@NotNull Collection messageKeys, @NotNull String defaultLocale); + /** + * Sends the specified message to multiple recipients with the specified default locale. + * + * @param messageKeys a collection of keys of the messages to be sent + * @param defaultLocale the default locale for the messages + * @return a {@link MultiMessagePostScript} object representing the result of the messages sent + */ @NotNull MultiMessagePostScript broadcastMessage(@NotNull Collection messageKeys, @NotNull DBLocale defaultLocale); + /** + * Sends the specified message to multiple recipients with the default locale. + * + * @param messageKeys a collection of keys of the messages to be sent + * @return a {@link MultiMessagePostScript} object representing the result of the messages sent + */ @NotNull MultiMessagePostScript broadcastMessage(@NotNull Collection messageKeys); - //sending with replacements + /** + * Sends a message with replacement values to a single recipient. + * + * @param messageKey The key identifying the message to send. + * @param messageRecipient The recipient to send the message to. + * @param replacement The replacement values to use in the message. + * @return A {@code MessagePostScript} object representing the sent message. + */ @NotNull MessagePostScript sendMessage(@NotNull String messageKey, @NotNull MessageRecipient messageRecipient, String... replacement); + /** + * Sends a message with replacement values to a single recipient, overriding the locale of the message. + * + * @param messageKey The key identifying the message to send. + * @param messageRecipient The recipient to send the message to. + * @param overrideLocale The locale to use for the message, overriding the default locale. + * @param replacement The replacement values to use in the message. + * @return A {@code MessagePostScript} object representing the sent message. + */ @NotNull MessagePostScript sendMessage(@NotNull String messageKey, @NotNull MessageRecipient messageRecipient, @NotNull Locale overrideLocale, String... replacement); + /** + * Sends a message with replacement values to a single recipient, overriding the locale of the message. + * + * @param messageKey The key identifying the message to send. + * @param messageRecipient The recipient to send the message to. + * @param overrideLocale The locale to use for the message, overriding the default locale. + * @param replacement The replacement values to use in the message. + * @return A {@code MessagePostScript} object representing the sent message. + */ @NotNull MessagePostScript sendMessage(@NotNull String messageKey, @NotNull MessageRecipient messageRecipient, @NotNull String overrideLocale, String... replacement); + /** + * Sends a message with replacement values to a single recipient, overriding the locale of the message. + * + * @param messageKey The key identifying the message to send. + * @param messageRecipient The recipient to send the message to. + * @param overrideLocale The locale to use for the message, overriding the default locale. + * @param replacement The replacement values to use in the message. + * @return A {@code MessagePostScript} object representing the sent message. + */ @NotNull MessagePostScript sendMessage(@NotNull String messageKey, @NotNull MessageRecipient messageRecipient, @NotNull DBLocale overrideLocale, String... replacement); + + /** + * Broadcasts a message with the given key to all message recipients, using the given default locale and replacements. + * + * @param messageKey the key of the message to be broadcasted + * @param defaultLocale the default locale to use for the broadcast + * @param replacement optional replacements for placeholders in the message + * @return a multi-message post script containing the status of each sent message + */ @NotNull MultiMessagePostScript broadcastMessage(@NotNull String messageKey, @NotNull Locale defaultLocale, String... replacement); + /** + * Broadcasts a message with the given key to all message recipients, using the given default locale and replacements. + * + * @param messageKey the key of the message to be broadcasted + * @param defaultLocale the default locale to use for the broadcast + * @param replacement optional replacements for placeholders in the message + * @return a multi-message post script containing the status of each sent message + */ @NotNull MultiMessagePostScript broadcastMessage(@NotNull String messageKey, @NotNull String defaultLocale, String... replacement); + /** + * Broadcasts a message with the given key to all message recipients, using the given default locale and replacements. + * + * @param messageKey the key of the message to be broadcasted + * @param defaultLocale the default locale to use for the broadcast + * @param replacement optional replacements for placeholders in the message + * @return a multi-message post script containing the status of each sent message + */ @NotNull MultiMessagePostScript broadcastMessage(@NotNull String messageKey, @NotNull DBLocale defaultLocale, String... replacement); + + /** + * Sends a message with replacements to all recipients, using the default locale. + * + * @param messageKey the key for the message to send + * @param replacement the replacements for placeholders in the message + * @return a collection of message post-scripts for each recipient + */ @NotNull Collection broadcastMessage(@NotNull String messageKey, String... replacement); + + /** + * Sends a collection of messages to a single message recipient with optional replacements. + * + * @param messageKeys the collection of message keys to be sent + * @param messageRecipient the message recipient to send the messages to + * @param replacement optional replacement strings to be used in the message templates + * @return the postscript representing the sending of the messages + */ @NotNull MultiMessagePostScript sendMessage(@NotNull Collection messageKeys, @NotNull MessageRecipient messageRecipient, String... replacement); /** - * @deprecated use {@link MessageApi#sendMessageSmart(Collection, Collection, String...)} instead + * @param messageKeys The keys of the messages to send. + * @param messageRecipients The recipients of the messages. + * @param replacement The replacements for message placeholders. + * @return A {@link MultiMessagePostScript} object containing the result of the message sending operation. + * @deprecated Use {@link MessageApi#sendMessageSmart(Collection, Collection, String...)} instead. */ @Deprecated @NotNull MultiMessagePostScript sendMessage(@NotNull Collection messageKeys, @NotNull Collection messageRecipients, String... replacement); + /** + * Sends a message to a single recipient with the specified locale override and replacement values. + * + * @param messageKeys The keys of the messages to send. + * @param messageRecipient The recipient of the message. + * @param overrideLocale The locale to use instead of the recipient's locale. + * @param replacement The replacements for message placeholders. + * @return A {@link MultiMessagePostScript} object containing the result of the message sending operation. + */ @NotNull MultiMessagePostScript sendMessage(@NotNull Collection messageKeys, @NotNull MessageRecipient messageRecipient, @NotNull String overrideLocale, String... replacement); + /** + * Sends a message to the given message recipient(s) with the specified message keys and replacements. + * + * @param messageKeys the collection of message keys to send + * @param messageRecipient the message recipient to send the messages to + * @param overrideLocale the locale to use when sending the message(s) + * @param replacement the array of message replacement values to use when sending the message(s) + * @return the message post-script + */ @NotNull MultiMessagePostScript sendMessage(@NotNull Collection messageKeys, @NotNull MessageRecipient messageRecipient, @NotNull Locale overrideLocale, String... replacement); + /** + * Sends a message to the given message recipient(s) with the specified message keys and replacements. + * + * @param messageKeys the collection of message keys to send + * @param messageRecipient the message recipient to send the messages to + * @param overrideLocale the DB locale to use when sending the message(s) + * @param replacement the array of message replacement values to use when sending the message(s) + * @return the message post-script + */ @NotNull MultiMessagePostScript sendMessage(@NotNull Collection messageKeys, @NotNull MessageRecipient messageRecipient, @NotNull DBLocale overrideLocale, String... replacement); + /** + * Sends a message to the given message recipient(s) with the specified message keys and replacements. + * + * @param messageKeys the collection of message keys to send + * @param messageRecipients the collection of message recipients to send the messages to + * @param overrideLocale the locale to use when sending the message(s) + * @param replacement the array of message replacement values to use when sending the message(s) + * @return the collection of message post-scripts + */ @NotNull MultiMessagePostScript sendMessage(@NotNull Collection messageKeys, @NotNull Collection messageRecipients, @NotNull String overrideLocale, String... replacement); + /** + * Sends a collection of messages with replacements to a collection of message recipients, with the specified locale override. + * + * @param messageKeys the collection of message keys to send + * @param messageRecipients the collection of message recipients to send the messages to + * @param overrideLocale the locale override to use for the messages + * @param replacement the array of replacements to use for each message + * @return a {@link MultiMessagePostScript} representing the post-script of the messages sent + */ @NotNull MultiMessagePostScript sendMessage(@NotNull Collection messageKeys, @NotNull Collection messageRecipients, @NotNull Locale overrideLocale, String... replacement); + /** + * Sends a collection of messages with replacements to a collection of message recipients, with the specified DB locale override. + * + * @param messageKeys the collection of message keys to send + * @param messageRecipients the collection of message recipients to send the messages to + * @param overrideLocale the DB locale override to use for the messages + * @param replacement the array of replacements to use for each message + * @return a {@link MultiMessagePostScript} representing the post-script of the messages sent + */ @NotNull MultiMessagePostScript sendMessage(@NotNull Collection messageKeys, @NotNull Collection messageRecipients, @NotNull DBLocale overrideLocale, String... replacement); + /** + * Sends a message broadcast to all recipients with the given message keys and replacement values. + * + * @param messageKeys the message keys to send. + * @param defaultLocale the default locale to use if a specific locale is not specified. + * @param replacement the replacement values to use in the message. + * @return a {@code MultiMessagePostScript} object representing the result of the operation. + */ @NotNull MultiMessagePostScript broadcastMessage(@NotNull Collection messageKeys, @NotNull Locale defaultLocale, String... replacement); + /** + * Sends a message broadcast to all recipients with the given message keys and replacement values. + * + * @param messageKeys the message keys to send. + * @param defaultLocale the default locale to use if a specific locale is not specified. + * @param replacement the replacement values to use in the message. + * @return a {@code MultiMessagePostScript} object representing the result of the operation. + */ @NotNull MultiMessagePostScript broadcastMessage(@NotNull Collection messageKeys, @NotNull String defaultLocale, String... replacement); + /** + * Sends a message broadcast to all recipients with the given message keys and replacement values. + * + * @param messageKeys the message keys to send. + * @param defaultLocale the default locale to use if a specific locale is not specified. + * @param replacement the replacement values to use in the message. + * @return a {@code MultiMessagePostScript} object representing the result of the operation. + */ @NotNull MultiMessagePostScript broadcastMessage(@NotNull Collection messageKeys, @NotNull DBLocale defaultLocale, String... replacement); + /** + * Sends a message broadcast to all recipients with the given message keys and replacement values. + * + * @param messageKeys the message keys to send. + * @param replacement the replacement values to use in the message. + * @return a {@code MultiMessagePostScript} object representing the result of the operation. + */ @NotNull MultiMessagePostScript broadcastMessage(@NotNull Collection messageKeys, String... replacement); + + /** + * Returns the default locale (EN_US) as a String. + * + * @return the default locale as a String + */ @NotNull String defaultLocale(); + /** + * Returns the default locale (EN_US) as a Locale object. + * + * @return the default locale as a Locale object + */ @NotNull Locale defaultUtilLocale(); + //TagManager getTagManager(); removed in favor of AdventureCore / AdventureAPI } From f33d9a7dbb0c6ac5adb5564e7daa594538d26889 Mon Sep 17 00:00:00 2001 From: TDR Date: Fri, 14 Apr 2023 18:14:52 +0200 Subject: [PATCH 28/60] add javadoc --- .../core/api/message/PatternType.java | 58 ++++++++++++++++--- .../net/juligames/core/api/misc/APIUtils.java | 53 +++++++++++++---- 2 files changed, 92 insertions(+), 19 deletions(-) diff --git a/API/src/main/java/net/juligames/core/api/message/PatternType.java b/API/src/main/java/net/juligames/core/api/message/PatternType.java index fc61d9ce..dfe8bdc2 100644 --- a/API/src/main/java/net/juligames/core/api/message/PatternType.java +++ b/API/src/main/java/net/juligames/core/api/message/PatternType.java @@ -1,53 +1,97 @@ +/** + * The PatternType enum represents the different types of patterns that can be used + * to identify placeholders in messages. The enum includes information about the + * start and end characters of the pattern, a tag identifier for the pattern, + * and whether the pattern should be resolved. + * + * @author Ture Bentzin + * @since 11.02.2023 + */ package net.juligames.core.api.message; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; -/** - * @author Ture Bentzin - * 11.02.2023 - */ public enum PatternType { + // Enum constants UNTRUSTED('{', '}', "safe", false), TRUSTED('[', ']', "unsafe", true); - + // Fields private final char start; private final char end; private final String tagIdentifier; private final boolean resolve; - PatternType(char start, char end, String tagIdentifier, boolean parse) { + // Constructor + PatternType(char start, char end, String tagIdentifier, boolean resolve) { this.start = start; this.end = end; this.tagIdentifier = tagIdentifier; - this.resolve = parse; + this.resolve = resolve; } + // Methods - why is this so EXTREME javadoced? + + /** + * Builds a pattern string using the start and end characters and an integer index. + * + * @param i the integer index to use in the pattern + * @return the pattern string + */ @Contract(pure = true) public @NotNull String buildPattern(int i) { return String.valueOf(start) + i + end; } + /** + * Builds a tag string using the tag identifier and an integer index. + * + * @param i the integer index to use in the tag + * @return the tag string + */ @Contract(pure = true) public @NotNull String buildTag(int i) { return "<" + buildTagID(i) + ">"; } + /** + * Builds a tag identifier string using the tag identifier and an integer index. + * + * @param i the integer index to use in the tag identifier + * @return the tag identifier string + */ @Contract(pure = true) public @NotNull String buildTagID(int i) { return "param_" + tagIdentifier + "_" + i; } + /** + * Converts a pattern string to a tag string. + * + * @param target the target string to convert + * @param index the integer index to use in the tag + * @return the converted tag string + */ public @NotNull String convertPatternToTag(@NotNull String target, int index) { return target.replace(buildPattern(index), buildTag(index)); } + /** + * Returns whether or not the pattern should be resolved. + * + * @return true if the pattern should be resolved, false otherwise + */ public boolean shouldParse() { return resolve; } + /** + * Returns a string representation of the PatternType enum constant. + * + * @return a string representation of the PatternType enum constant + */ @Contract(pure = true) public @NotNull String toString() { return "PatternType: " + name() + ": \"" + start + "i" + end + "\""; diff --git a/API/src/main/java/net/juligames/core/api/misc/APIUtils.java b/API/src/main/java/net/juligames/core/api/misc/APIUtils.java index 1d9453d7..2fca42d1 100644 --- a/API/src/main/java/net/juligames/core/api/misc/APIUtils.java +++ b/API/src/main/java/net/juligames/core/api/misc/APIUtils.java @@ -16,14 +16,13 @@ private APIUtils() { } - public static boolean executedWithoutException(@NotNull ThrowingRunnable runnable, Exception... exceptions) { - return executedWithoutException(runnable, List.of(exceptions)); - } - - public static boolean executedWithoutException(@NotNull ThrowingRunnable runnable) { - return executedWithoutException(runnable, Collections.emptyList()); - } - + /** + * Executes the given `ThrowingRunnable` and returns `true` if it completes without throwing an exception, or if the thrown exception is not contained in the specified collection of exceptions. + * + * @param runnable the `ThrowingRunnable` to execute + * @param exceptions a collection of exceptions that should not be counted as a failure + * @return `true` if the `ThrowingRunnable` completes without throwing an exception or if the thrown exception is not contained in the specified collection of exceptions + */ public static boolean executedWithoutException(@NotNull ThrowingRunnable runnable, Collection exceptions) { try { runnable.run(); @@ -33,14 +32,34 @@ public static boolean executedWithoutException(@NotNull ThrowingRunnable runnabl } } - public static boolean executedWithoutExceptionL(@NotNull Runnable runnable, Exception... exceptions) { - return executedWithoutExceptionL(runnable, List.of(exceptions)); + /** + * Executes the given `ThrowingRunnable` and returns `true` if it completes without throwing an exception. + * + * @param runnable the `ThrowingRunnable` to execute + * @return `true` if the `ThrowingRunnable` completes without throwing an exception + */ + public static boolean executedWithoutException(@NotNull ThrowingRunnable runnable) { + return executedWithoutException(runnable, Collections.emptyList()); } - public static boolean executedWithoutExceptionL(@NotNull Runnable runnable) { - return executedWithoutExceptionL(runnable, Collections.emptyList()); + /** + * Executes the given `ThrowingRunnable` and returns `true` if it completes without throwing an exception that is contained in the specified array of exceptions. + * + * @param runnable the `ThrowingRunnable` to execute + * @param exceptions an array of exceptions that should not be counted as a failure + * @return `true` if the `ThrowingRunnable` completes without throwing an exception or if the thrown exception is not contained in the specified array of exceptions + */ + public static boolean executedWithoutException(@NotNull ThrowingRunnable runnable, Exception... exceptions) { + return executedWithoutException(runnable, List.of(exceptions)); } + /** + * Executes the given `Runnable` and returns `true` if it completes without throwing an exception, or if the thrown exception is not contained in the specified collection of exceptions. + * + * @param runnable the `Runnable` to execute + * @param exceptions a collection of exceptions that should not be counted as a failure + * @return `true` if the `Runnable` completes without throwing an exception or if the thrown exception is not contained in the specified collection of exceptions + */ public static boolean executedWithoutExceptionL(@NotNull Runnable runnable, Collection exceptions) { try { runnable.run(); @@ -49,4 +68,14 @@ public static boolean executedWithoutExceptionL(@NotNull Runnable runnable, Coll return !exceptions.contains(e); } } + + /** + * Executes the given `Runnable` and returns `true` if it completes without throwing an exception. + * + * @param runnable the `Runnable` to execute + * @return `true` if the `Runnable` completes without throwing an exception + */ + public static boolean executedWithoutExceptionL(@NotNull Runnable runnable) { + return executedWithoutExceptionL(runnable, Collections.emptyList()); + } } From 6c4d154014b1d1e496ab9629e99cb3f245acf66e Mon Sep 17 00:00:00 2001 From: TDR Date: Fri, 14 Apr 2023 18:30:34 +0200 Subject: [PATCH 29/60] further javadocs --- .../net/juligames/core/api/misc/APIUtils.java | 2 + .../api/misc/EntryInterpretationUtil.java | 46 ++++++++++++++++++- 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/API/src/main/java/net/juligames/core/api/misc/APIUtils.java b/API/src/main/java/net/juligames/core/api/misc/APIUtils.java index 2fca42d1..0500ad7c 100644 --- a/API/src/main/java/net/juligames/core/api/misc/APIUtils.java +++ b/API/src/main/java/net/juligames/core/api/misc/APIUtils.java @@ -1,5 +1,6 @@ package net.juligames.core.api.misc; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import java.util.Collection; @@ -10,6 +11,7 @@ * @author Ture Bentzin * 10.04.2023 */ +@ApiStatus.AvailableSince("1.6") public class APIUtils { private APIUtils() { diff --git a/API/src/main/java/net/juligames/core/api/misc/EntryInterpretationUtil.java b/API/src/main/java/net/juligames/core/api/misc/EntryInterpretationUtil.java index d16c6d75..682d5fd6 100644 --- a/API/src/main/java/net/juligames/core/api/misc/EntryInterpretationUtil.java +++ b/API/src/main/java/net/juligames/core/api/misc/EntryInterpretationUtil.java @@ -1,6 +1,7 @@ package net.juligames.core.api.misc; import net.juligames.core.api.config.Interpreter; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Unmodifiable; @@ -9,27 +10,69 @@ import java.util.Map; import java.util.stream.Collectors; +@ApiStatus.AvailableSince("1.6") public class EntryInterpretationUtil { private EntryInterpretationUtil() { } + /** + * Interpret an entry in a {@link Map} using the given key and value interpreters and return an unmodifiable map entry. + * + * @param stringStringEntry the map entry to interpret + * @param kInterpreter the key interpreter + * @param vInterpreter the value interpreter + * @param the type of the key + * @param the type of the value + * @return an unmodifiable map entry with an interpreted key and value + * @throws Exception if there is an error during interpretation + */ @Contract("_, _, _ -> new") public static Map.@NotNull @Unmodifiable Entry interpretEntry(Map.@NotNull Entry stringStringEntry, @NotNull Interpreter kInterpreter, @NotNull Interpreter vInterpreter) throws Exception { return Map.entry(kInterpreter.interpret(stringStringEntry.getKey()), vInterpreter.interpret(stringStringEntry.getValue())); } + /** + * Reverse an entry in a {@link Map} using the given key and value interpreters and return an unmodifiable map entry. + * + * @param stringStringEntry the map entry to reverse + * @param kInterpreter the key interpreter + * @param vInterpreter the value interpreter + * @param the type of the key + * @param the type of the value + * @return an unmodifiable map entry with reversed key and value + */ @Contract("_, _, _ -> new") public static Map.@NotNull @Unmodifiable Entry reverseEntry(Map.@NotNull Entry stringStringEntry, @NotNull Interpreter kInterpreter, @NotNull Interpreter vInterpreter) { return Map.entry(kInterpreter.reverse(stringStringEntry.getKey()), vInterpreter.reverse(stringStringEntry.getValue())); } + /** + * Reverse a collection of entries in a {@link Map} using the given key and value interpreters and return an unmodifiable collection of map entries. + * + * @param collection the collection of map entries to reverse + * @param kInterpreter the key interpreter + * @param vInterpreter the value interpreter + * @param the type of the key + * @param the type of the value + * @return an unmodifiable collection of map entries with reversed key and value + */ public static @Unmodifiable Collection> reverseEntries(@NotNull Collection> collection, Interpreter kInterpreter, Interpreter vInterpreter) { return collection.stream().map(kvEntry -> reverseEntry(kvEntry, kInterpreter, vInterpreter)).collect(Collectors.toUnmodifiableSet()); } - + /** + * Interpret a collection of entries in a {@link Map} using the given key and value interpreters and return an unmodifiable collection of map entries. + * + * @param collection the collection of map entries to interpret + * @param kInterpreter the key interpreter + * @param vInterpreter the value interpreter + * @param the type of the key + * @param the type of the value + * @return an unmodifiable collection of map entries with interpreted key and value + * @throws RuntimeException if there is an error during interpretation + */ public static @Unmodifiable Collection> interpretEntries(@NotNull Collection> collection, Interpreter kInterpreter, Interpreter vInterpreter) { return collection.stream().map(kvEntry -> { try { @@ -39,4 +82,5 @@ private EntryInterpretationUtil() { } }).collect(Collectors.toUnmodifiableSet()); } + } From f75e5ab66798bef53665e1aa2cc1970a4e04c879 Mon Sep 17 00:00:00 2001 From: TDR Date: Sat, 15 Apr 2023 22:15:14 +0200 Subject: [PATCH 30/60] fixed issue with IDE and SUPERCORE --- SuperCore/SuperCore.iml | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 SuperCore/SuperCore.iml diff --git a/SuperCore/SuperCore.iml b/SuperCore/SuperCore.iml new file mode 100644 index 00000000..c4622759 --- /dev/null +++ b/SuperCore/SuperCore.iml @@ -0,0 +1,12 @@ + + + + + + + ADVENTURE + + + + + \ No newline at end of file From 06c2fb9ea7bea8a4e444e2f331ba560515127fc2 Mon Sep 17 00:00:00 2001 From: TDR Date: Sat, 15 Apr 2023 22:15:18 +0200 Subject: [PATCH 31/60] Update HazelConnector.java --- .../juligames/core/hcast/HazelConnector.java | 51 +++++++++++++++---- 1 file changed, 41 insertions(+), 10 deletions(-) diff --git a/Core/src/main/java/net/juligames/core/hcast/HazelConnector.java b/Core/src/main/java/net/juligames/core/hcast/HazelConnector.java index 293d3916..dc291539 100644 --- a/Core/src/main/java/net/juligames/core/hcast/HazelConnector.java +++ b/Core/src/main/java/net/juligames/core/hcast/HazelConnector.java @@ -5,11 +5,14 @@ import com.hazelcast.config.Config; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; +import org.checkerframework.checker.optional.qual.MaybePresent; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.Objects; +import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; @@ -18,29 +21,29 @@ * 16.11.2022 */ public class HazelConnector { - private final String clientName; + private final @NotNull String clientName; - private final CompletableFuture instance = new CompletableFuture<>(); + private final @NotNull CompletableFuture instance = new CompletableFuture<>(); - private HazelConnector(String memberName) { - this.clientName = memberName; + private HazelConnector(@NotNull String clientName) { + this.clientName = clientName; } @Contract("_ -> new") - public static @NotNull HazelConnector getInstance(String name) { + public static @NotNull HazelConnector getInstance(@NotNull String name) { return new HazelConnector(name); } - public static HazelConnector getInstanceAndConnect(String name) { + public static @NotNull HazelConnector getInstanceAndConnect(@NotNull String name) { return new HazelConnector(name).connect(); } @ApiStatus.Internal - public static HazelConnector getInstanceAndConnectAsMember(String name) { + public static @NotNull HazelConnector getInstanceAndConnectAsMember(@NotNull String name) { return new HazelConnector(name).connectMember(); } - public HazelConnector connect() { + public @NotNull HazelConnector connect() { ClientConfig clientConfig = HCastConfigProvider.provide(clientName); HazelcastInstance hazelcastInstance = HazelcastClient.newHazelcastClient(clientConfig); instance.complete(hazelcastInstance); @@ -48,7 +51,7 @@ public HazelConnector connect() { } @ApiStatus.Internal - public HazelConnector connectMember() { + public @NotNull HazelConnector connectMember() { Config config = HCastConfigProvider.provideMember(clientName); config.getJetConfig().setEnabled(true); HazelcastInstance hazelcastInstance = Hazelcast.getOrCreateHazelcastInstance(config); @@ -64,13 +67,41 @@ public void disconnect() { } } + /** + * This method acts like {@link #disconnect()} but cant throw an {@link Exception} and does not wait for population of + * the {@link #instance} field! + * @return an Optional that might contain an {@link Exception} that was thrown while trying to kill hazelcast + */ + @ApiStatus.Internal + @MaybePresent + public @NotNull Optional kill() { + try { + Objects.requireNonNull(instance.getNow(null), "cant kill instance! Your cluster might be bricked now...") + .shutdown(); + return Optional.empty(); + }catch (Exception e) { + e.printStackTrace(); //print but do not propagate! + return Optional.of(e); + } + } + @ApiStatus.Internal @Nullable public HazelcastInstance getForce() { return getInstance().getNow(null); } - public CompletableFuture getInstance() { + public @NotNull CompletableFuture getInstance() { return instance; } + + /** + * Get the configured {@link #clientName}. + * This represents a memberName if this {@link HazelConnector} is used for members (masters) or a real clientName if it is + * used for creating members + * @return the clientName + */ + protected @NotNull String getClientName() { + return clientName; + } } From 57c289f51930e2535e34331b3c24220b45451a88 Mon Sep 17 00:00:00 2001 From: TDR Date: Sun, 16 Apr 2023 11:24:39 +0200 Subject: [PATCH 32/60] pull down methods from CoreMessageAPI --- .../net/juligames/core/api/message/MessageApi.java | 13 +++++++++++++ .../adventure/api/AudienceMessageRecipient.java | 1 + 2 files changed, 14 insertions(+) diff --git a/API/src/main/java/net/juligames/core/api/message/MessageApi.java b/API/src/main/java/net/juligames/core/api/message/MessageApi.java index 93b5512a..30b86d98 100644 --- a/API/src/main/java/net/juligames/core/api/message/MessageApi.java +++ b/API/src/main/java/net/juligames/core/api/message/MessageApi.java @@ -934,6 +934,19 @@ MultiMessagePostScript sendMessage(@NotNull String messageKey, @NotNull Collecti @NotNull MultiMessagePostScript broadcastMessage(@NotNull Collection messageKeys, String... replacement); + /** + * @param messageKey the messageKey + * @param messageRecipient the recipient + * @return the best locale + * @deprecated use {@link MessageApi#findBestMessageForRecipient(String, MessageRecipient)} instead + */ + @Deprecated + String findBestForRecipient(String messageKey, @NotNull MessageRecipient messageRecipient); + + Message findBestMessageForRecipient(String messageKey, @NotNull MessageRecipient messageRecipient); + + Message findBestMessageForRecipient(String messageKey, @NotNull MessageRecipient messageRecipient, String... replacements); + /** * Returns the default locale (EN_US) as a String. * diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/AudienceMessageRecipient.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/AudienceMessageRecipient.java index abe93907..a9a6bf4d 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/AudienceMessageRecipient.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/AudienceMessageRecipient.java @@ -6,6 +6,7 @@ import net.juligames.core.api.message.MessageRecipient; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.identity.Identity; +import net.kyori.adventure.pointer.Pointered; import net.kyori.adventure.text.Component; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; From 56b1d151da4c3fd90c07b90bce1d1b9d56f5aa6a Mon Sep 17 00:00:00 2001 From: TDR Date: Sun, 16 Apr 2023 21:38:59 +0200 Subject: [PATCH 33/60] some tweaks --- .../net/juligames/core/api/message/MessageApi.java | 3 +++ .../core/api/misc/DurationFormatUtils.java | 2 +- .../core/api/misc/EntryInterpretationUtil.java | 13 +++++++++++-- .../GenericHashtableToStringHashtableMapper.java | 1 + .../java/net/juligames/core/util/ShuffleUtil.java | 1 - 5 files changed, 16 insertions(+), 4 deletions(-) diff --git a/API/src/main/java/net/juligames/core/api/message/MessageApi.java b/API/src/main/java/net/juligames/core/api/message/MessageApi.java index 30b86d98..b79080d0 100644 --- a/API/src/main/java/net/juligames/core/api/message/MessageApi.java +++ b/API/src/main/java/net/juligames/core/api/message/MessageApi.java @@ -941,10 +941,13 @@ MultiMessagePostScript sendMessage(@NotNull String messageKey, @NotNull Collecti * @deprecated use {@link MessageApi#findBestMessageForRecipient(String, MessageRecipient)} instead */ @Deprecated + @ApiStatus.AvailableSince("1.6") String findBestForRecipient(String messageKey, @NotNull MessageRecipient messageRecipient); + @ApiStatus.AvailableSince("1.6") Message findBestMessageForRecipient(String messageKey, @NotNull MessageRecipient messageRecipient); + @ApiStatus.AvailableSince("1.6") Message findBestMessageForRecipient(String messageKey, @NotNull MessageRecipient messageRecipient, String... replacements); /** diff --git a/API/src/main/java/net/juligames/core/api/misc/DurationFormatUtils.java b/API/src/main/java/net/juligames/core/api/misc/DurationFormatUtils.java index 63ef04bb..0c568585 100644 --- a/API/src/main/java/net/juligames/core/api/misc/DurationFormatUtils.java +++ b/API/src/main/java/net/juligames/core/api/misc/DurationFormatUtils.java @@ -256,7 +256,7 @@ public DurationFormatUtils() { API.get().getMessageApi().defaultUtilLocale()); API.get().getAPILogger().info("finished registration of default messages! (took: " + formatDurationWords + ")"); }catch (Exception e){ - API.get().getAPILogger().error("failed to register default messages: " + e); + API.get().getAPILogger().warning("failed to register default messages: " + e); ThrowableDebug.debug(e); } diff --git a/API/src/main/java/net/juligames/core/api/misc/EntryInterpretationUtil.java b/API/src/main/java/net/juligames/core/api/misc/EntryInterpretationUtil.java index 682d5fd6..96159491 100644 --- a/API/src/main/java/net/juligames/core/api/misc/EntryInterpretationUtil.java +++ b/API/src/main/java/net/juligames/core/api/misc/EntryInterpretationUtil.java @@ -8,6 +8,7 @@ import java.util.Collection; import java.util.Map; +import java.util.function.IntFunction; import java.util.stream.Collectors; @ApiStatus.AvailableSince("1.6") @@ -58,7 +59,7 @@ private EntryInterpretationUtil() { * @param the type of the value * @return an unmodifiable collection of map entries with reversed key and value */ - public static @Unmodifiable Collection> reverseEntries(@NotNull Collection> collection, Interpreter kInterpreter, Interpreter vInterpreter) { + public static @NotNull @Unmodifiable Collection> reverseEntries(@NotNull Collection> collection, @NotNull Interpreter kInterpreter, @NotNull Interpreter vInterpreter) { return collection.stream().map(kvEntry -> reverseEntry(kvEntry, kInterpreter, vInterpreter)).collect(Collectors.toUnmodifiableSet()); } @@ -73,7 +74,7 @@ private EntryInterpretationUtil() { * @return an unmodifiable collection of map entries with interpreted key and value * @throws RuntimeException if there is an error during interpretation */ - public static @Unmodifiable Collection> interpretEntries(@NotNull Collection> collection, Interpreter kInterpreter, Interpreter vInterpreter) { + public static @NotNull @Unmodifiable Collection> interpretEntries(@NotNull Collection> collection, @NotNull Interpreter kInterpreter, @NotNull Interpreter vInterpreter) { return collection.stream().map(kvEntry -> { try { return interpretEntry(kvEntry, kInterpreter, vInterpreter); @@ -83,4 +84,12 @@ private EntryInterpretationUtil() { }).collect(Collectors.toUnmodifiableSet()); } + public static @Unmodifiable @NotNull Map interpretMap(@NotNull Map map, @NotNull Interpreter kInterpreter, @NotNull Interpreter vInterpreter) { + return Map.ofEntries(interpretEntries(map.entrySet(), kInterpreter, vInterpreter).toArray((IntFunction[]>) value -> new Map.Entry[0])); + } + + public static @Unmodifiable @NotNull Map reverseMap(@NotNull Map map, @NotNull Interpreter kInterpreter, @NotNull Interpreter vInterpreter) { + return Map.ofEntries(reverseEntries(map.entrySet(), kInterpreter, vInterpreter).toArray((IntFunction[]>) value -> new Map.Entry[0])); + } + } diff --git a/API/src/main/java/net/juligames/core/api/misc/GenericHashtableToStringHashtableMapper.java b/API/src/main/java/net/juligames/core/api/misc/GenericHashtableToStringHashtableMapper.java index 614977bf..5f6e032b 100644 --- a/API/src/main/java/net/juligames/core/api/misc/GenericHashtableToStringHashtableMapper.java +++ b/API/src/main/java/net/juligames/core/api/misc/GenericHashtableToStringHashtableMapper.java @@ -21,6 +21,7 @@ public class GenericHashtableToStringHashtableMapper implements Function kInterpreter, @NotNull Interpreter vInterpreter) { this.kInterpreter = kInterpreter; this.vInterpreter = vInterpreter; + } @Contract(value = "_ -> new", pure = true) diff --git a/MiniGameAPI/src/main/java/net/juligames/core/util/ShuffleUtil.java b/MiniGameAPI/src/main/java/net/juligames/core/util/ShuffleUtil.java index d87b2194..24b7ecd4 100644 --- a/MiniGameAPI/src/main/java/net/juligames/core/util/ShuffleUtil.java +++ b/MiniGameAPI/src/main/java/net/juligames/core/util/ShuffleUtil.java @@ -25,7 +25,6 @@ public final class ShuffleUtil { ); private ShuffleUtil() { - } @SuppressWarnings("unchecked") From 091cdc5baab11a2acf7694499e63dee78b6a6daf Mon Sep 17 00:00:00 2001 From: TDR Date: Sun, 16 Apr 2023 21:39:12 +0200 Subject: [PATCH 34/60] added option to interpret maps --- .../adventure/api/MessageRepresentation.java | 26 ++++++++++++++----- 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java index 9fcb4d13..c5b20aa6 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java @@ -2,12 +2,11 @@ import net.juligames.core.adventure.AdventureTagManager; import net.juligames.core.api.API; +import net.juligames.core.api.config.BuildInInterpreters; import net.juligames.core.api.jdbi.DBLocale; -import net.juligames.core.api.jdbi.DBMessage; import net.juligames.core.api.message.Message; -import net.kyori.adventure.audience.Audience; +import net.juligames.core.api.misc.EntryInterpretationUtil; import net.kyori.adventure.identity.Identity; -import net.kyori.adventure.pointer.Pointer; import net.kyori.adventure.pointer.Pointered; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.ComponentLike; @@ -15,7 +14,12 @@ import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; +import java.io.File; +import java.net.URL; +import java.util.HashMap; import java.util.Locale; +import java.util.Map; +import java.util.stream.Stream; /** * @author Ture Bentzin @@ -26,6 +30,7 @@ public class MessageRepresentation implements ComponentLike { private final @NotNull AdventureTagManager adventureTagManager; private final @NotNull Message message; + public MessageRepresentation(@NotNull AdventureTagManager adventureTagManager, @NotNull Message message) { this.adventureTagManager = adventureTagManager; this.message = message; @@ -79,7 +84,9 @@ public MessageRepresentation(@NotNull Message message) { return new MessageRepresentation(API.get().getMessageApi().getMessageSmart(messageKey, pointered.get(Identity.LOCALE).orElse(defaultLocale()), replacements)); } - + private static @NotNull Locale defaultLocale() { + return API.get().getMessageApi().defaultUtilLocale(); + } @Override public @NotNull Component asComponent() { @@ -90,7 +97,14 @@ public Message getMessage() { return message; } - private static @NotNull Locale defaultLocale() { - return API.get().getMessageApi().defaultUtilLocale(); + private void demo() { + + Map fileURLMap = new HashMap<>(); + Map stringStringMap = EntryInterpretationUtil.reverseMap(fileURLMap, BuildInInterpreters.fileInterpreter(), BuildInInterpreters.urlInterpreter()); + Map fileURLMap1 = EntryInterpretationUtil.interpretMap(stringStringMap, BuildInInterpreters.fileInterpreter(), BuildInInterpreters.urlInterpreter()); + assert fileURLMap1.equals(fileURLMap); + + Stream> entryStream = fileURLMap.entrySet().stream().map(fileURLEntry -> EntryInterpretationUtil.reverseEntry(fileURLEntry, BuildInInterpreters.fileInterpreter(), BuildInInterpreters.urlInterpreter())); + } } From 5b3a2ccf6b0651f030ec80738f450b6ee4296eb3 Mon Sep 17 00:00:00 2001 From: TDR Date: Mon, 17 Apr 2023 20:15:39 +0200 Subject: [PATCH 35/60] Create Representation.java --- .../representations/Representation.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 API/src/main/java/net/juligames/core/api/config/representations/Representation.java diff --git a/API/src/main/java/net/juligames/core/api/config/representations/Representation.java b/API/src/main/java/net/juligames/core/api/config/representations/Representation.java new file mode 100644 index 00000000..9811dde3 --- /dev/null +++ b/API/src/main/java/net/juligames/core/api/config/representations/Representation.java @@ -0,0 +1,28 @@ +package net.juligames.core.api.config.representations; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Supplier; + +/** + * @author Ture Bentzin + * 17.04.2023 + */ +@ApiStatus.AvailableSince("1.6") +@FunctionalInterface +public interface Representation { + + @Contract(pure = true) + static @NotNull Representation of(T t) { + return () -> t; + } + + @Contract(pure = true) + static @NotNull Representation of(@NotNull Supplier supplier) { + return supplier::get; + } + + T represent(); +} From fc34a09c308beaeb4e1e6f33af88c26f4354dc4f Mon Sep 17 00:00:00 2001 From: TDR Date: Mon, 17 Apr 2023 20:15:41 +0200 Subject: [PATCH 36/60] Create Interpretation.java --- .../representations/Interpretation.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 API/src/main/java/net/juligames/core/api/config/representations/Interpretation.java diff --git a/API/src/main/java/net/juligames/core/api/config/representations/Interpretation.java b/API/src/main/java/net/juligames/core/api/config/representations/Interpretation.java new file mode 100644 index 00000000..7a58036b --- /dev/null +++ b/API/src/main/java/net/juligames/core/api/config/representations/Interpretation.java @@ -0,0 +1,30 @@ +package net.juligames.core.api.config.representations; + +import net.juligames.core.api.config.PrimitiveInterpreter; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +/** + * @author Ture Bentzin + * 17.04.2023 + */ +@ApiStatus.AvailableSince("1.6") +public abstract class Interpretation implements Representation{ + + public Interpretation(@NotNull PrimitiveInterpreter interpreter) { + this.interpreter = interpreter; + } + + public final @NotNull PrimitiveInterpreter interpreter; + + @Override + public final @NotNull T represent() { + try { + return interpreter.interpret(getRepresentation()); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public abstract String getRepresentation(); +} From 27b58ac113bb623f1cecf2c1bea4038f7495f9ec Mon Sep 17 00:00:00 2001 From: TDR Date: Mon, 17 Apr 2023 20:16:03 +0200 Subject: [PATCH 37/60] add new api features to make files ready for 1.6 release --- .../adventure/api/MessageRepresentation.java | 9 ++++- .../ObjectifiedConfiguration.java | 39 ++++++++++++++++++- 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java index c5b20aa6..51f0ebb7 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java @@ -3,6 +3,7 @@ import net.juligames.core.adventure.AdventureTagManager; import net.juligames.core.api.API; import net.juligames.core.api.config.BuildInInterpreters; +import net.juligames.core.api.config.representations.Representation; import net.juligames.core.api.jdbi.DBLocale; import net.juligames.core.api.message.Message; import net.juligames.core.api.misc.EntryInterpretationUtil; @@ -26,7 +27,7 @@ * 25.03.2023 */ @ApiStatus.AvailableSince("1.6") -public class MessageRepresentation implements ComponentLike { +public class MessageRepresentation implements ComponentLike, Representation { private final @NotNull AdventureTagManager adventureTagManager; private final @NotNull Message message; @@ -107,4 +108,10 @@ private void demo() { Stream> entryStream = fileURLMap.entrySet().stream().map(fileURLEntry -> EntryInterpretationUtil.reverseEntry(fileURLEntry, BuildInInterpreters.fileInterpreter(), BuildInInterpreters.urlInterpreter())); } + + @Override + @ApiStatus.AvailableSince("1.6") + public Component represent() { + return asComponent(); + } } diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/ObjectifiedConfiguration.java b/PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/ObjectifiedConfiguration.java index 5b652680..5b8c4765 100644 --- a/PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/ObjectifiedConfiguration.java +++ b/PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/ObjectifiedConfiguration.java @@ -1,10 +1,21 @@ package net.juligames.core.paper.misc.configmapping; +import net.juligames.core.api.config.representations.Representation; +import org.bukkit.configuration.Configuration; import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import java.io.File; +import java.io.Reader; import java.lang.reflect.Field; +import java.net.URI; +import java.net.URL; +import java.time.YearMonth; import java.util.Arrays; import java.util.Optional; @@ -53,7 +64,6 @@ * @author Ture Bentzin * 14.04.2023 */ -@SuppressWarnings("ClassCanBeRecord") @ApiStatus.Experimental @ApiStatus.AvailableSince("1.6") public class ObjectifiedConfiguration { @@ -65,6 +75,33 @@ public ObjectifiedConfiguration(@NotNull ConfigurationSection associatedSection) reload(); } + public ObjectifiedConfiguration(@NotNull File ymlFile) { + this(YamlConfiguration.loadConfiguration(ymlFile)); + } + + public ObjectifiedConfiguration(@NotNull Reader reader) { + this(YamlConfiguration.loadConfiguration(reader)); + } + + public ObjectifiedConfiguration(@NotNull String data, @Nullable String section) throws InvalidConfigurationException { + YamlConfiguration configuration = new YamlConfiguration(); + configuration.loadFromString(data); + this.associatedSection = section == null? configuration : configuration.createSection(section); + } + + public ObjectifiedConfiguration(@NotNull String path) { + this(new File(path)); + } + + public ObjectifiedConfiguration(@NotNull URI path) { + this(new File(path)); + } + + public ObjectifiedConfiguration(@NotNull Representation sectionRepresentation) { + this(sectionRepresentation.represent()); + } + + public final @NotNull ConfigurationSection getAssociatedSection() { return associatedSection; } From f13663e7878499c9d4ffef9f52b1624796b5b63e Mon Sep 17 00:00:00 2001 From: TDR Date: Mon, 17 Apr 2023 20:24:47 +0200 Subject: [PATCH 38/60] add experimental saving to ObjectifiedConfiguration --- .../ObjectifiedConfiguration.java | 45 ++++++++++++++++--- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/ObjectifiedConfiguration.java b/PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/ObjectifiedConfiguration.java index 5b8c4765..261e29e8 100644 --- a/PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/ObjectifiedConfiguration.java +++ b/PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/ObjectifiedConfiguration.java @@ -1,5 +1,6 @@ package net.juligames.core.paper.misc.configmapping; +import net.juligames.core.api.API; import net.juligames.core.api.config.representations.Representation; import org.bukkit.configuration.Configuration; import org.bukkit.configuration.ConfigurationSection; @@ -11,13 +12,13 @@ import org.jetbrains.annotations.Nullable; import java.io.File; +import java.io.IOException; import java.io.Reader; import java.lang.reflect.Field; import java.net.URI; -import java.net.URL; -import java.time.YearMonth; import java.util.Arrays; import java.util.Optional; +import java.util.function.Consumer; /** * This class provides a convenient way to map configuration files to Java classes in your plugins. @@ -56,7 +57,7 @@ * * } * } - * + *

* In this example, the {@code MyConfig} class extends {@link ObjectifiedConfiguration} and has two fields marked with the @{@link Autofill} * annotation. These fields will be automatically populated with values from the associated configuration file. * You can also manually {@link #save()} or {@link #reload()} the config. @@ -86,7 +87,7 @@ public ObjectifiedConfiguration(@NotNull Reader reader) { public ObjectifiedConfiguration(@NotNull String data, @Nullable String section) throws InvalidConfigurationException { YamlConfiguration configuration = new YamlConfiguration(); configuration.loadFromString(data); - this.associatedSection = section == null? configuration : configuration.createSection(section); + this.associatedSection = section == null ? configuration : configuration.createSection(section); } public ObjectifiedConfiguration(@NotNull String path) { @@ -114,10 +115,44 @@ public void save() { Arrays.stream(this.getClass().getFields()).forEachOrdered(this::save); } + /** + * @param file file to save to + * @throws IOException if saving fails fatally + * @apiNote This method is not available with standalone! + */ + @ApiStatus.Experimental + public void save(File file) throws IOException { + save(); + Configuration root = associatedSection.getRoot(); + if (root == null) { + API.get().getAPILogger().warning("cant save " + this.getClass().getSimpleName() + " because associatedSection does not" + + " belong to any Configuration"); + return; + } + if (root instanceof FileConfiguration fileConfiguration) { + fileConfiguration.save(file); + } else { + API.get().getAPILogger().warning("cant save " + this.getClass().getSimpleName() + " because associatedSection does not" + + " belong to a FileConfiguration! :: " + root.getClass().getSimpleName()); + } + } + + @ApiStatus.Experimental + public void save(Consumer saver) { + save(); + Configuration root = associatedSection.getRoot(); + if (root == null) { + API.get().getAPILogger().warning("cant save " + this.getClass().getSimpleName() + " because associatedSection does not" + + " belong to any Configuration"); + return; + } + saver.accept((C) root); + } + public void save(@NotNull Field field) { if (field.getDeclaringClass().equals(this.getClass())) { String key = getKeyForField(field); - //time to set the value + //time to set the value try { getAssociatedSection().set(key, field.get(this)); } catch (IllegalAccessException e) { From 0e9970f2da44a43094aefa7be41f51e989387e75 Mon Sep 17 00:00:00 2001 From: TDR Date: Fri, 21 Apr 2023 15:23:12 +0200 Subject: [PATCH 39/60] added further javadoc --- .../core/api/config/EnumInterpreter.java | 27 +++++++- .../mapbacked/DictionaryFeedInterpreter.java | 68 +++++++++++++++++-- .../core/api/message/MessagePostScript.java | 12 +++- .../core/api/message/MessageRecipient.java | 41 +++++++---- .../api/message/MiniMessageSerializer.java | 39 +++++++---- .../core/api/minigame/StartType.java | 44 ++++++++++++ .../core/adventure/JDBITagAdapter.java | 29 +++++--- .../team/procedures/InsertionProcedure.java | 7 ++ .../core/paper/PaperMessageRecipient.java | 28 ++++++-- .../inventory/InventoryConfigWriter.java | 34 +++++++++- .../ObjectifiedConfiguration.java | 46 +++++++++++++ 11 files changed, 324 insertions(+), 51 deletions(-) diff --git a/API/src/main/java/net/juligames/core/api/config/EnumInterpreter.java b/API/src/main/java/net/juligames/core/api/config/EnumInterpreter.java index cd3e9b52..5c0fe39e 100644 --- a/API/src/main/java/net/juligames/core/api/config/EnumInterpreter.java +++ b/API/src/main/java/net/juligames/core/api/config/EnumInterpreter.java @@ -13,21 +13,46 @@ public class EnumInterpreter> implements Interpreter { private final Class enumClazz; + /** + * Constructs a new {@link EnumInterpreter} instance for the specified enum class. + * + * @param enumClazz the class object for the enum type + */ public EnumInterpreter(Class enumClazz) { this.enumClazz = enumClazz; } + /** + * Interprets the input string as an enum value of type T. + * + * @param input the input string to be interpreted + * @return the interpreted enum value + * @throws IllegalArgumentException if the input string is not a valid name of an enum constant belonging to type T + */ @Override - public @NotNull T interpret(@NotNull String input) throws Exception { + public @NotNull T interpret(@NotNull String input) throws IllegalArgumentException { return T.valueOf(enumClazz, input); } + /** + * Returns the name of the specified enum value. + * + * @param t the enum value to be reversed + * @return the name of the enum value + */ @Override public @NotNull String reverse(@NotNull T t) { return t.name(); } + /** + * Returns the class object for the enum type. + * + * @return the class object for the enum type + */ public Class getEnumClazz() { return enumClazz; } } + + diff --git a/API/src/main/java/net/juligames/core/api/config/mapbacked/DictionaryFeedInterpreter.java b/API/src/main/java/net/juligames/core/api/config/mapbacked/DictionaryFeedInterpreter.java index 6142d7b4..58b352d5 100644 --- a/API/src/main/java/net/juligames/core/api/config/mapbacked/DictionaryFeedInterpreter.java +++ b/API/src/main/java/net/juligames/core/api/config/mapbacked/DictionaryFeedInterpreter.java @@ -19,53 +19,109 @@ public class DictionaryFeedInterpreter implements Interpreter> { private final @NotNull Supplier> dictionarySupplier; private final @NotNull BiFunction>, ? extends MapPart> dictionaryPartFactory; - + /** + * Constructs a new {@link DictionaryFeedInterpreter} instance with the given dictionary supplier. + * + * @param dictionarySupplier the supplier to use to provide the backing dictionary + */ public DictionaryFeedInterpreter(@NotNull Supplier> dictionarySupplier) { this.dictionarySupplier = dictionarySupplier; this.dictionaryPartFactory = DictionaryPart::new; } + /** + * Constructs a new {@link DictionaryFeedInterpreter} instance with the given dictionary supplier and map part factory. + * + * @param dictionarySupplier the supplier to use to provide the backing dictionary + * @param dictionaryPartFactory the function to use to create map parts based on the dictionary and the key + */ public DictionaryFeedInterpreter(@NotNull Supplier> dictionarySupplier, @NotNull BiFunction>, MapPart> dictionaryPartFactory) { this.dictionarySupplier = dictionarySupplier; this.dictionaryPartFactory = dictionaryPartFactory; } - + /** + * Interprets the given input string as a map part key and returns a corresponding map part. + * + * @param input the input string to interpret as a key + * @return the corresponding map part + */ @Override public @NotNull MapPart interpret(@NotNull String input) { return fabricate(input); } + /** + * Returns the factory function used to create map parts based on the dictionary and the key. + * + * @return the factory function used to create map parts + */ public BiFunction>, ? extends MapPart> getDictionaryPartFactory() { return dictionaryPartFactory; } + /** + * Creates a new map part with the given key and dictionary supplier using the factory function. + * + * @param key the key of the new map part + * @param dictionarySupplier the dictionary supplier to use for the new map part + * @return the newly created map part + */ public @NotNull MapPart fabricate(@NotNull String key, @NotNull Supplier> dictionarySupplier) { return dictionaryPartFactory.apply(key, dictionarySupplier); } + /** + * Creates a new {@code MapPart} instance with the given key and using the current dictionary supplier and factory. + * + * @param key the key for the new {@code MapPart} instance + * @return a new {@code MapPart} instance + */ protected @NotNull MapPart fabricate(@NotNull String key) { return dictionaryPartFactory.apply(key, dictionarySupplier); } + /** + * Returns the key for the given {@code MapPart} instance. + * + * @param eMapPart the {@code MapPart} instance to get the key for + * @return the key for the given {@code MapPart} instance + */ @Override public @NotNull String reverse(@NotNull MapPart eMapPart) { return eMapPart.key(); } - - private record DictionaryPart(String key, - Supplier> dictionarySupplier) implements MapPart { - + /** + * A private record that represents a map part backed by a dictionary. + * + * @param the type of values stored in the dictionary + */ + private record DictionaryPart( + String key, + Supplier> dictionarySupplier + ) implements MapPart { + + /** + * Returns the key for this map part. + * + * @return the key for this map part + */ @Override public @NotNull String key() { return key; } + /** + * Returns the value for this map part by looking up the key in the backing dictionary. + * + * @return the value for this map part + */ @Override public @NotNull E get() { return dictionarySupplier.get().get(key()); } } + } diff --git a/API/src/main/java/net/juligames/core/api/message/MessagePostScript.java b/API/src/main/java/net/juligames/core/api/message/MessagePostScript.java index 6334e297..a83421ba 100644 --- a/API/src/main/java/net/juligames/core/api/message/MessagePostScript.java +++ b/API/src/main/java/net/juligames/core/api/message/MessagePostScript.java @@ -11,22 +11,32 @@ public interface MessagePostScript { /** + * Gets the message that was sent. + * * @return the message that was sent (this may be not the exact message) */ @NotNull Message message(); /** + * Gets the time the message was sent. + * * @return the time (not exact - do not use for encryption) the message sending was complete */ @NotNull Date timeSent(); /** + * Gets the recipient of the message. + * * @return the recipient of the message */ @NotNull MessageRecipient recipient(); /** - * @return transfer this {@link MessagePostScript} to a {@link MultiMessagePostScript} + * Converts this {@link MessagePostScript} to a {@link MultiMessagePostScript}. + * + * @return the {@link MultiMessagePostScript} representation of this object */ @NotNull MultiMessagePostScript toMulti(); } + + diff --git a/API/src/main/java/net/juligames/core/api/message/MessageRecipient.java b/API/src/main/java/net/juligames/core/api/message/MessageRecipient.java index 996f6066..0f55b530 100644 --- a/API/src/main/java/net/juligames/core/api/message/MessageRecipient.java +++ b/API/src/main/java/net/juligames/core/api/message/MessageRecipient.java @@ -6,40 +6,57 @@ import org.jetbrains.annotations.Nullable; /** + * The MessageRecipient interface defines the methods necessary for an object to receive a message. + * * @author Ture Bentzin * 18.11.2022 */ public interface MessageRecipient { /** - * @return A human-readable name that defines this recipient + * Returns a human-readable name that defines this recipient. + * + * @return a human-readable name that defines this recipient */ @NotNull String getName(); /** - * Delivers the specified Message to this MessageRecipient. The message should always be human-readable! + * Delivers the specified message to this MessageRecipient. The message should always be human-readable. * * @param message the message to deliver */ void deliver(@NotNull Message message); - /** - * delivers a miniMessage string to the recipient + * Returns the locale of this MessageRecipient, or null if the locale is not specified. + * + * @return the locale of this MessageRecipient, or null if the locale is not specified */ - @ApiStatus.Internal - @Deprecated - void deliver(@NotNull String miniMessage); - - @Nullable - String supplyLocale(); + @Nullable String supplyLocale(); /** - * This will return the default locale that is distributed by the master + * Returns the default locale that is distributed by the master, or the locale of this MessageRecipient if + * specified. + * + * @return the default locale that is distributed by the master, or the locale of this MessageRecipient if + * specified */ default @Nullable String supplyLocaleOrDefault() { - if (supplyLocale() != null) return supplyLocale(); + if (supplyLocale() != null) { + return supplyLocale(); + } return API.get().getHazelDataApi().getMasterInformation().get("default_locale"); } + /** + * @deprecated Use {@link #deliver(Message)} instead. + * + *

Delivers a miniMessage string to the recipient.

+ * + * @param miniMessage the miniMessage string to deliver + */ + @Deprecated + @ApiStatus.Internal + void deliver(@NotNull String miniMessage); + } diff --git a/API/src/main/java/net/juligames/core/api/message/MiniMessageSerializer.java b/API/src/main/java/net/juligames/core/api/message/MiniMessageSerializer.java index 6387762c..1d30bd6a 100644 --- a/API/src/main/java/net/juligames/core/api/message/MiniMessageSerializer.java +++ b/API/src/main/java/net/juligames/core/api/message/MiniMessageSerializer.java @@ -3,51 +3,66 @@ import org.jetbrains.annotations.NotNull; /** + * This interface provides methods for serializing a MiniMessage to plain text or legacy format. + * It also provides methods for translating legacy format messages to MiniMessage format. * @author Ture Bentzin * 25.12.2022 */ public interface MiniMessageSerializer { /** - * This will resolve the given message to a plain String. This will strip all colors and decorations! + * This method resolves the given message to a plain text string, stripping all colors and decorations. * - * @param message the message - * @return plain text + * @param message the MiniMessage to resolve + * @return a plain text string representation of the MiniMessage */ @NotNull String resolvePlain(@NotNull Message message); /** - * This will resolve the given message to a "legacy format String". This will remove all advanced decorations! + * This method resolves the given message to a legacy format string, removing all advanced decorations. * - * @param message the message - * @return legacy message + * @param message the MiniMessage to resolve + * @return a legacy format string representation of the MiniMessage */ @Deprecated @NotNull String resolveLegacy(@NotNull Message message); /** - * This will resolve the given message to a plain String. This will strip all colors and decorations! + * This method resolves the given miniMessage to a plain text string, stripping all colors and decorations. * - * @param miniMessage the message - * @return plain text + * @param miniMessage the miniMessage to resolve + * @return a plain text string representation of the miniMessage */ @Deprecated @NotNull String resolvePlain(@NotNull String miniMessage); /** - * This will resolve the given message to a "legacy format String". This will remove all advanced decorations! + * This method resolves the given miniMessage to a legacy format string, removing all advanced decorations. * - * @param miniMessage the message - * @return legacy message + * @param miniMessage the miniMessage to resolve + * @return a legacy format string representation of the miniMessage */ @Deprecated @NotNull String resolveLegacy(@NotNull String miniMessage); + /** + * This method translates a legacy format string to MiniMessage format. + * + * @param ampersand the legacy format string to translate + * @return a MiniMessage format string representation of the legacy format string + */ @NotNull String translateLegacyToMiniMessage(@NotNull String ampersand); + /** + * This method translates a legacy format section string to MiniMessage format. + * + * @param section the legacy format section string to translate + * @return a MiniMessage format string representation of the legacy format section string + */ @NotNull String translateLegacySectionToMiniMessage(@NotNull String section); } +} diff --git a/API/src/main/java/net/juligames/core/api/minigame/StartType.java b/API/src/main/java/net/juligames/core/api/minigame/StartType.java index 60c621cd..e61c93f7 100644 --- a/API/src/main/java/net/juligames/core/api/minigame/StartType.java +++ b/API/src/main/java/net/juligames/core/api/minigame/StartType.java @@ -11,19 +11,63 @@ @ApiStatus.AvailableSince("1.5") public interface StartType { + /** + * The direct starting option. + */ StartType DIRECT = new SimpleStartType("DIRECT"); + + /** + * The delayed starting option. + */ StartType DELAYED = new SimpleStartType("DELAYED"); + /** + * Compares two StartType objects for similarity. + * + * @param s1 the first StartType object + * @param s2 the second StartType object + * @return true if the objects are similar, false otherwise + */ static boolean compare(@NotNull StartType s1, StartType s2) { return s1.isSimilar(s2); } + /** + * Returns the name of this StartType object. + * + * @return the name of this StartType object + */ String getName(); + /** + * Checks whether this StartType object is similar to another StartType object. + * + *

+ * Two StartType objects are considered similar if they have the same name. + *

+ * + * @param startType the StartType object to compare to + * @return true if the objects are similar, false otherwise + * + *

Example usage:

+ *
{@code
+     * StartType s1 = StartType.DIRECT;
+     * StartType s2 = new SimpleStartType("DIRECT");
+     * boolean areSimilar = s1.isSimilar(s2); // true
+     *
+     * StartType s3 = new ImaginaryStartType("IMAGINARY");
+     * StartType s4 = new SimpleStartType("IMAGINARY");
+     * boolean areSimilar2 = s3.isSimilar(s4); // true
+     * }
+ */ default boolean isSimilar(@NotNull StartType startType) { return this.getName().equals(startType.getName()); } + + /** + * A simple implementation of the StartType interface. + */ record SimpleStartType(String name) implements StartType { @Override public String getName() { diff --git a/AdventureCore/src/main/java/net/juligames/core/adventure/JDBITagAdapter.java b/AdventureCore/src/main/java/net/juligames/core/adventure/JDBITagAdapter.java index ccbb0e16..7f45e2f9 100644 --- a/AdventureCore/src/main/java/net/juligames/core/adventure/JDBITagAdapter.java +++ b/AdventureCore/src/main/java/net/juligames/core/adventure/JDBITagAdapter.java @@ -21,10 +21,18 @@ * 19.11.2022 */ public class JDBITagAdapter { - - + + /** + * The logger for this class. + */ public static final Logger logger = API.get().getAPILogger().adopt("adapter"); + /** + * Converts a {@link DBReplacement} to a {@link Tag}. + * + * @param replacement the DBReplacement to convert + * @return the resulting Tag + */ @SuppressWarnings("PatternValidation") public static Tag fromJDBI(@NotNull DBReplacement replacement) { String s = replacement.getReplacementType(); @@ -63,21 +71,22 @@ public static Tag fromJDBI(@NotNull DBReplacement replacement) { /** * WARNING: This uses the fallback resolver + * + * @param replacement the DBReplacement to resolve + * @return the resulting Component */ private static @NotNull Component resolveValue(@NotNull DBReplacement replacement) { return AdventureAPI.get().getAdventureTagManager().fallbackResolve(replacement.getValue()); //TODO currently this is hardcode and i intend to leave it that way to insure that fallback resolving never fails } + /** + * Represents the type of a replacement. + * + * @see CoreSQLManager + */ @SuppressWarnings("JavadocReference") public enum ReplacementType { - TEXT_CLOSING, - TEXT, - COLOR_HEX, - COLOR_HEX_CSS, - NAMED_COLOR, - FONT, - INSERT, - PROCESS; + TEXT_CLOSING, TEXT, COLOR_HEX, COLOR_HEX_CSS, NAMED_COLOR, FONT, INSERT, PROCESS; /** * @see net.juligames.core.jdbi.CoreSQLManager diff --git a/MiniGameAPI/src/main/java/net/juligames/core/minigame/api/team/procedures/InsertionProcedure.java b/MiniGameAPI/src/main/java/net/juligames/core/minigame/api/team/procedures/InsertionProcedure.java index 58b9dd1d..eecfb4cb 100644 --- a/MiniGameAPI/src/main/java/net/juligames/core/minigame/api/team/procedures/InsertionProcedure.java +++ b/MiniGameAPI/src/main/java/net/juligames/core/minigame/api/team/procedures/InsertionProcedure.java @@ -7,6 +7,13 @@ import java.util.function.BiFunction; /** + * A sealed interface that defines the insertion procedure for adding players to teams. + * The method {@code apply()} should return {@code true} if the player was successfully inserted into a team, + * and {@code false} if the insertion failed for any reason. + *

+ * You can use {@link ConsumerInsertionProcedure} to make a custom implementation (at the time) - this system is subjet + * to change but i will try to not break compatibility + * * @author Ture Bentzin * 18.12.2022 */ diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/PaperMessageRecipient.java b/PaperAPI/src/main/java/net/juligames/core/paper/PaperMessageRecipient.java index 352d472c..a349e2c7 100644 --- a/PaperAPI/src/main/java/net/juligames/core/paper/PaperMessageRecipient.java +++ b/PaperAPI/src/main/java/net/juligames/core/paper/PaperMessageRecipient.java @@ -10,6 +10,8 @@ import org.jetbrains.annotations.Nullable; /** + * Represents a message recipient on a Paper server, which is capable of receiving messages + * through the Bukkit {@link CommandSender} interface. * @author Ture Bentzin * 19.11.2022 */ @@ -17,40 +19,52 @@ public class PaperMessageRecipient implements MessageRecipient { private final CommandSender commandSender; + /** + * Constructs a new {@code PaperMessageRecipient} with the specified {@link CommandSender}. + * @param commandSender the Bukkit {@link CommandSender} for this recipient + */ public PaperMessageRecipient(CommandSender commandSender) { this.commandSender = commandSender; } /** - * @return A human-readable name that defines this recipient + * Returns a human-readable name that defines this recipient. + * @return the name of this recipient, which is equivalent to the name of the Bukkit {@link CommandSender} */ @Override public @NotNull String getName() { return commandSender.getName(); } + /** + * Delivers a message to this recipient using the Adventure API. + * @param message the {@link Message} to be delivered + */ @Override public void deliver(@NotNull Message message) { commandSender.sendMessage(AdventureAPI.get().getAdventureTagManager().resolve(message)); } /** - * delivers a miniMessage string to the recipient - * - * @param miniMessage the miniMessage to deliver to the commandSender + * Delivers a miniMessage string to this recipient using the Adventure API. + * @param miniMessage the miniMessage to be delivered to the Bukkit {@link CommandSender} */ @Override public void deliver(@NotNull String miniMessage) { - //Component resolve = Core.getInstance().getMessageApi().getTagManager().resolve(miniMessage); Component resolve = AdventureAPI.get().getAdventureTagManager().resolve(miniMessage); commandSender.sendMessage(resolve); } + /** + * Returns the locale of the player associated with this recipient, if applicable. + * @return the locale string of the player, or {@code null} if the recipient is not a player + */ @Override public @Nullable String supplyLocale() { if (commandSender instanceof Player player) { return player.locale().toString(); - } else + } else { return null; + } } -} +} \ No newline at end of file diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/inventory/InventoryConfigWriter.java b/PaperAPI/src/main/java/net/juligames/core/paper/inventory/InventoryConfigWriter.java index b3028ffb..c1cbaea5 100644 --- a/PaperAPI/src/main/java/net/juligames/core/paper/inventory/InventoryConfigWriter.java +++ b/PaperAPI/src/main/java/net/juligames/core/paper/inventory/InventoryConfigWriter.java @@ -11,19 +11,43 @@ import java.util.Collection; /** - * @author Ture Bentzin - * 23.01.2023 + * This class represents a writer for Bukkit inventories that can be serialized into configurations. + * It implements the ConfigWriter interface and provides methods for populating and writing an inventory to a configuration. + *

+ * The class uses an Interpreter to convert ItemStacks to their serialized form, and vice versa. + *

+ * + * @author Ture Bentzin 23.01.2023 */ public record InventoryConfigWriter(Inventory inventory) implements ConfigWriter { + /** + * The interpreter used to convert ItemStacks to their serialized form. + */ @SuppressWarnings("ProtectedMemberInFinalClass") protected static final @NotNull Interpreter itemStackInterpreter = new ItemStackInterpreter(); + /** + * Populates an inventory with items from the given configuration. + * + * @param configuration the configuration to read items from + * @param keyspace the keyspace in the configuration to read items from + * @param inventory the inventory to populate + */ public static void populateInventory(@NotNull Configuration configuration, @NotNull String keyspace, @NotNull Inventory inventory) { Collection collection = configuration.getCollection(keyspace, itemStackInterpreter); inventory.setContents(collection.toArray(new ItemStack[0])); } + /** + * Populates an inventory with items from the given configuration and returns the inventory. + *

+ * + * @param configuration the configuration to read items from + * @param keyspace the keyspace in the configuration to read items from + * @param inventory the inventory to populate + * @return the populated inventory + */ @ApiStatus.Experimental public static synchronized @NotNull Inventory populateAndReturnInventory(@NotNull Configuration configuration, @NotNull String keyspace, @NotNull Inventory inventory) { @@ -31,6 +55,12 @@ public static void populateInventory(@NotNull Configuration configuration, @NotN return inventory; } + /** + * Writes the inventory to the given configuration. + * + * @param configuration the configuration to write the inventory to + * @param keyspace the keyspace in the configuration to write the inventory to + */ @Override public void write(@NotNull Configuration configuration, @NotNull String keyspace) { configuration.setIterable(keyspace, inventory, itemStackInterpreter); diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/ObjectifiedConfiguration.java b/PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/ObjectifiedConfiguration.java index 261e29e8..b5548233 100644 --- a/PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/ObjectifiedConfiguration.java +++ b/PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/ObjectifiedConfiguration.java @@ -71,38 +71,84 @@ public class ObjectifiedConfiguration { private final @NotNull ConfigurationSection associatedSection; + /** + * Constructs an ObjectifiedConfiguration object with an associated ConfigurationSection. + * Calls the {@link #reload()} method to populate fields with values from the ConfigurationSection. + * + * @param associatedSection the ConfigurationSection to associate with this ObjectifiedConfiguration + */ public ObjectifiedConfiguration(@NotNull ConfigurationSection associatedSection) { this.associatedSection = associatedSection; reload(); } + /** + * Constructs an ObjectifiedConfiguration object with an associated File. + * Calls the {@link #reload()} method to populate fields with values from the FileConfiguration. + * + * @param ymlFile the File to associate with this ObjectifiedConfiguration + */ public ObjectifiedConfiguration(@NotNull File ymlFile) { this(YamlConfiguration.loadConfiguration(ymlFile)); } + /** + * Constructs an ObjectifiedConfiguration object with an associated Reader. + * Calls the {@link #reload()} method to populate fields with values from the FileConfiguration. + * + * @param reader the Reader to associate with this ObjectifiedConfiguration + */ public ObjectifiedConfiguration(@NotNull Reader reader) { this(YamlConfiguration.loadConfiguration(reader)); } + /** + * Constructs an ObjectifiedConfiguration object with an associated String data and section name. + * If the section name is null, creates a ConfigurationSection using the loaded data. + * Calls the {@link #reload()} method to populate fields with values from the ConfigurationSection. + * + * @param data the data to associate with this ObjectifiedConfiguration + * @param section the section name to associate with this ObjectifiedConfiguration, can be null + * @throws InvalidConfigurationException if the loaded data is invalid + */ public ObjectifiedConfiguration(@NotNull String data, @Nullable String section) throws InvalidConfigurationException { YamlConfiguration configuration = new YamlConfiguration(); configuration.loadFromString(data); this.associatedSection = section == null ? configuration : configuration.createSection(section); } + /** + * Constructs an ObjectifiedConfiguration object with an associated path String. + * Calls the {@link #ObjectifiedConfiguration(File)} constructor to associate the File with this ObjectifiedConfiguration. + * + * @param path the path of the File to associate with this ObjectifiedConfiguration + */ public ObjectifiedConfiguration(@NotNull String path) { this(new File(path)); } + /** + * Constructs an ObjectifiedConfiguration object with an associated URI. + * Calls the {@link #ObjectifiedConfiguration(File)} constructor to associate the File with this ObjectifiedConfiguration. + * + * @param path the URI of the File to associate with this ObjectifiedConfiguration + */ public ObjectifiedConfiguration(@NotNull URI path) { this(new File(path)); } + /** + * Constructs an ObjectifiedConfiguration object with an associated ConfigurationSection obtained from a representation. + * Calls the {@link #reload()} method to populate fields with values from the ConfigurationSection. + * + * @param sectionRepresentation the representation of the ConfigurationSection to associate with this ObjectifiedConfiguration + */ public ObjectifiedConfiguration(@NotNull Representation sectionRepresentation) { this(sectionRepresentation.represent()); } + public final @NotNull ConfigurationSection getAssociatedSection() { return associatedSection; } From 662149b226b7fd26e68e503db485065e2e84d5d4 Mon Sep 17 00:00:00 2001 From: TDR Date: Thu, 18 May 2023 13:29:46 +0200 Subject: [PATCH 40/60] tweaks to the Prompts --- .../PromptInterpreterUtils.java | 25 +++++++++++++++++++ .../core/adventure/JDBITagAdapter.java | 2 +- .../core/paper/prompt/MaterialPrompt.java | 2 ++ 3 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/interpretation/PromptInterpreterUtils.java diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/interpretation/PromptInterpreterUtils.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/interpretation/PromptInterpreterUtils.java new file mode 100644 index 00000000..e6b02efa --- /dev/null +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/interpretation/PromptInterpreterUtils.java @@ -0,0 +1,25 @@ +package net.juligames.core.adventure.api.prompt.interpretation; + +import de.bentzin.conversationlib.prompt.Prompt; +import de.bentzin.conversationlib.prompt.ValidatingPrompt; +import net.juligames.core.api.config.Interpreter; +import org.jetbrains.annotations.NotNull; + +/** + * @author Ture Bentzin + * 18.05.2023 + */ +public class PromptInterpreterUtils { + + private PromptInterpreterUtils() { + } + + private abstract static class PromptInterpreter implements Interpreter { + + private @NotNull ValidatingPrompt prompt; + + public PromptInterpreter(ValidatingPrompt) { + + } + } +} diff --git a/AdventureCore/src/main/java/net/juligames/core/adventure/JDBITagAdapter.java b/AdventureCore/src/main/java/net/juligames/core/adventure/JDBITagAdapter.java index 7f45e2f9..2bb22714 100644 --- a/AdventureCore/src/main/java/net/juligames/core/adventure/JDBITagAdapter.java +++ b/AdventureCore/src/main/java/net/juligames/core/adventure/JDBITagAdapter.java @@ -21,7 +21,7 @@ * 19.11.2022 */ public class JDBITagAdapter { - + /** * The logger for this class. */ diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/prompt/MaterialPrompt.java b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/MaterialPrompt.java index ccec998b..83d684bf 100644 --- a/PaperAPI/src/main/java/net/juligames/core/paper/prompt/MaterialPrompt.java +++ b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/MaterialPrompt.java @@ -4,6 +4,7 @@ import de.bentzin.conversationlib.prompt.Prompt; import de.bentzin.conversationlib.prompt.ValidatingPrompt; import org.bukkit.Material; +import org.bukkit.map.MapPalette; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -23,6 +24,7 @@ protected boolean isInputValid(@NotNull ConversationContext context, @NotNull St @Override protected @Nullable Prompt acceptValidatedInput(@NotNull ConversationContext context, @NotNull String input) { + MapPalette.matchColor() return acceptMaterialInput(context, Objects.requireNonNull(Material.getMaterial(input))); } From 073845759a7766fec4c78e88561da3fdad7091c3 Mon Sep 17 00:00:00 2001 From: TDR Date: Thu, 18 May 2023 13:29:57 +0200 Subject: [PATCH 41/60] Delete PromptInterpreterUtils.java --- .../PromptInterpreterUtils.java | 25 ------------------- 1 file changed, 25 deletions(-) delete mode 100644 AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/interpretation/PromptInterpreterUtils.java diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/interpretation/PromptInterpreterUtils.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/interpretation/PromptInterpreterUtils.java deleted file mode 100644 index e6b02efa..00000000 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/interpretation/PromptInterpreterUtils.java +++ /dev/null @@ -1,25 +0,0 @@ -package net.juligames.core.adventure.api.prompt.interpretation; - -import de.bentzin.conversationlib.prompt.Prompt; -import de.bentzin.conversationlib.prompt.ValidatingPrompt; -import net.juligames.core.api.config.Interpreter; -import org.jetbrains.annotations.NotNull; - -/** - * @author Ture Bentzin - * 18.05.2023 - */ -public class PromptInterpreterUtils { - - private PromptInterpreterUtils() { - } - - private abstract static class PromptInterpreter implements Interpreter { - - private @NotNull ValidatingPrompt prompt; - - public PromptInterpreter(ValidatingPrompt) { - - } - } -} From 01d4c1ce677e0b5dd444792d6e36304f604f3a63 Mon Sep 17 00:00:00 2001 From: TDR Date: Thu, 18 May 2023 13:47:47 +0200 Subject: [PATCH 42/60] Create IndexBackedInterpreterProvider.java --- .../IndexBackedInterpreterProvider.java | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 AdventureAPI/src/main/java/net/juligames/core/adventure/api/interpreter/IndexBackedInterpreterProvider.java diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/interpreter/IndexBackedInterpreterProvider.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/interpreter/IndexBackedInterpreterProvider.java new file mode 100644 index 00000000..ddcb0c0f --- /dev/null +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/interpreter/IndexBackedInterpreterProvider.java @@ -0,0 +1,95 @@ +package net.juligames.core.adventure.api.interpreter; + +import net.juligames.core.api.config.Interpreter; +import net.kyori.adventure.util.Index; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Supplier; + +/** + * @author Ture Bentzin + * 18.05.2023 + */ +public class IndexBackedInterpreterProvider> implements Supplier> { + + private final Interpreter normalInterpreter; + private final Interpreter invertedInterpreter; + private final Index source; + private final boolean inverted; + + + /** + * Defaults to false for inverted. This only affects the {@link #get()} method and only matters for automatic access! + * @param kInterpreter interpreter for the key + * @param vInterpreter interpreter for the value + * @param source the datasource to pull from + */ + public IndexBackedInterpreterProvider(Interpreter kInterpreter, Interpreter vInterpreter, Index source) { + this(kInterpreter, vInterpreter, source, false); + } + + public IndexBackedInterpreterProvider(Interpreter kInterpreter, Interpreter vInterpreter, Index source, boolean inverted) { + + this.source = source; + this.inverted = inverted; + + { + this.normalInterpreter = new Interpreter<>() { + @Override + public @NotNull V interpret(String input) throws Exception { + return getSource().valueOrThrow(kInterpreter.interpret(input)); + } + + @Override + public @NotNull String reverse(V v) { + return kInterpreter.reverse(getSource().keyOrThrow(v)); + } + }; + } + + { + this.invertedInterpreter = new Interpreter<>() { + @Override + public @NotNull K interpret(String input) throws Exception { + return getSource().keyOrThrow(vInterpreter.interpret(input)); + } + + @Override + public @NotNull String reverse(K k) { + return vInterpreter.reverse(getSource().valueOrThrow(k)); + } + }; + } + + + } + + public Index getSource() { + return source; + } + + /** + * + * @return the {@link Interpreter} to use! + */ + @Override + public Interpreter get() { + return !inverted ? normalInterpreter : invertedInterpreter; + } + + public Interpreter getInvertedInterpreter() { + return invertedInterpreter; + } + + public Interpreter getNormalInterpreter() { + return normalInterpreter; + } + + /** + * Indicates if the {@link #get()} method will return a {@link Interpreter} otherwise an {@link Interpreter} will be returned + * @return if the {@link IndexBackedInterpreterProvider} acts inverted or not! + */ + public boolean isInverted() { + return inverted; + } +} From 210677eda645c88fab218fece23a7f1c4156a402 Mon Sep 17 00:00:00 2001 From: TDR Date: Thu, 18 May 2023 14:02:04 +0200 Subject: [PATCH 43/60] Create IndexBackedInterpreterProviderBuilder.java --- ...IndexBackedInterpreterProviderBuilder.java | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 AdventureAPI/src/main/java/net/juligames/core/adventure/api/interpreter/IndexBackedInterpreterProviderBuilder.java diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/interpreter/IndexBackedInterpreterProviderBuilder.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/interpreter/IndexBackedInterpreterProviderBuilder.java new file mode 100644 index 00000000..7becca85 --- /dev/null +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/interpreter/IndexBackedInterpreterProviderBuilder.java @@ -0,0 +1,91 @@ +package net.juligames.core.adventure.api.interpreter; + +import net.juligames.core.api.config.Interpreter; +import net.kyori.adventure.util.Index; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +/** + * The `IndexBackedInterpreterProviderBuilder` class provides a builder pattern for creating instances of `IndexBackedInterpreterProvider`. + * + * @param The type of the keys in the index. + * @param The type of the values in the index. + * @param The type of the index that implements the `Index` interface. + * @author Ture Bentzin + * 18.05.2023 + */ +@ApiStatus.AvailableSince("1.6") +@ApiStatus.Experimental +public class IndexBackedInterpreterProviderBuilder> { + private Interpreter kInterpreter; + private Interpreter vInterpreter; + private Index source; + private boolean inverted = false; + + /** + * Sets the interpreter for the key type `K`. + * + * @param kInterpreter The interpreter for the key type. + * @return The builder instance. + */ + public @NotNull IndexBackedInterpreterProviderBuilder setKInterpreter(Interpreter kInterpreter) { + this.kInterpreter = kInterpreter; + return this; + } + + /** + * Sets the interpreter for the value type `V`. + * + * @param vInterpreter The interpreter for the value type. + * @return The builder instance. + */ + public @NotNull IndexBackedInterpreterProviderBuilder setVInterpreter(Interpreter vInterpreter) { + this.vInterpreter = vInterpreter; + return this; + } + + /** + * Sets the data source to pull from, implementing the `Index` interface. + * + * @param source The data source. + * @return The builder instance. + */ + public @NotNull IndexBackedInterpreterProviderBuilder setSource(Index source) { + this.source = source; + return this; + } + + /** + * Sets the inversion flag, indicating whether the interpretation is inverted or not. + * + * @param inverted The inversion flag. + * @return The builder instance. + */ + public @NotNull IndexBackedInterpreterProviderBuilder setInverted(boolean inverted) { + this.inverted = inverted; + return this; + } + + /** + * Creates a new instance of `IndexBackedInterpreterProvider` based on the provided configuration. + * + * @return The created `IndexBackedInterpreterProvider`. + * @throws IllegalStateException If the builder does not meet the minimum criteria to create an `IndexBackedInterpreterProvider`. + */ + public @NotNull IndexBackedInterpreterProvider createIndexBackedInterpreterProvider() throws IllegalStateException { + if (kInterpreter == null || vInterpreter == null || source == null) { + throw new IllegalStateException("Builder does not meet the minimum criteria to create an IndexBackedInterpreterProvider!"); + } + return new IndexBackedInterpreterProvider<>(kInterpreter, vInterpreter, source, inverted); + } + + /** + * Builds and supplies the appropriate `Interpreter` based on the builder configuration. + * + * @return The built `Interpreter`. + * @throws IllegalStateException If the builder does not meet the minimum criteria to create an `IndexBackedInterpreterProvider` or the `get()` method of the provider throws an exception. + */ + public @NotNull Interpreter buildAndSupply() throws IllegalStateException { + return createIndexBackedInterpreterProvider().get(); + } +} From af0b1d0da496e4fab3317ffe22fbade136dc66d8 Mon Sep 17 00:00:00 2001 From: TDR Date: Thu, 18 May 2023 14:02:15 +0200 Subject: [PATCH 44/60] javadoced IndexbackedInterpreterProvider --- .../IndexBackedInterpreterProvider.java | 139 +++++++++++++----- 1 file changed, 104 insertions(+), 35 deletions(-) diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/interpreter/IndexBackedInterpreterProvider.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/interpreter/IndexBackedInterpreterProvider.java index ddcb0c0f..16ba8dbb 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/interpreter/IndexBackedInterpreterProvider.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/interpreter/IndexBackedInterpreterProvider.java @@ -2,94 +2,163 @@ import net.juligames.core.api.config.Interpreter; import net.kyori.adventure.util.Index; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; +import java.util.NoSuchElementException; import java.util.function.Supplier; /** + * The `IndexBackedInterpreterProvider` class is an implementation of the `Supplier` interface that provides an interpreter for a given index-based data source. + * It allows interpreting values based on keys and vice versa, using two different interpreters for key and value types. + * The interpretation can be done in the normal direction or in an inverted direction, depending on the `inverted` flag. + * + * @param The type of the keys in the index. + * @param The type of the values in the index. + * @param The type of the index that implements the `Index` interface. * @author Ture Bentzin * 18.05.2023 + * @apiNote You can use {@link IndexBackedInterpreterProviderBuilder} to build your instance */ -public class IndexBackedInterpreterProvider> implements Supplier> { +@ApiStatus.AvailableSince("1.6") +public final class IndexBackedInterpreterProvider> implements Supplier> { private final Interpreter normalInterpreter; private final Interpreter invertedInterpreter; private final Index source; private final boolean inverted; - /** - * Defaults to false for inverted. This only affects the {@link #get()} method and only matters for automatic access! - * @param kInterpreter interpreter for the key - * @param vInterpreter interpreter for the value - * @param source the datasource to pull from + * Creates a new `IndexBackedInterpreterProvider` with the provided key and value interpreters and data source. + * The interpretation is set to be in the normal direction (non-inverted). + * + * @param kInterpreter The interpreter for the key type `K`. + * @param vInterpreter The interpreter for the value type `V`. + * @param source The data source to pull from, implementing the `Index` interface. */ public IndexBackedInterpreterProvider(Interpreter kInterpreter, Interpreter vInterpreter, Index source) { this(kInterpreter, vInterpreter, source, false); } + /** + * Creates a new `IndexBackedInterpreterProvider` with the provided key and value interpreters, data source, and inversion flag. + * + * @param kInterpreter The interpreter for the key type `K`. + * @param vInterpreter The interpreter for the value type `V`. + * @param source The data source to pull from, implementing the `Index` interface. + * @param inverted Flag indicating whether the interpretation is inverted or not. + */ public IndexBackedInterpreterProvider(Interpreter kInterpreter, Interpreter vInterpreter, Index source, boolean inverted) { - this.source = source; this.inverted = inverted; - { - this.normalInterpreter = new Interpreter<>() { - @Override - public @NotNull V interpret(String input) throws Exception { - return getSource().valueOrThrow(kInterpreter.interpret(input)); - } - - @Override - public @NotNull String reverse(V v) { + // Create the normal interpreter + this.normalInterpreter = new Interpreter<>() { + /** + * Interprets the given input as a value and retrieves it from the source. + * + * @param input The input to interpret. + * @return The interpreted value. + * @throws Exception if an error occurs during interpretation or value retrieval. + */ + @Override + public @NotNull V interpret(String input) throws Exception { + return getSource().valueOrThrow(kInterpreter.interpret(input)); + } + + /** + * Reverses the interpretation by converting the value back to its corresponding key. + * + * @param v The value to reverse. + * @return The reversed key as a string. + * @throws NoSuchElementException If the key corresponding to the value is not found in the index. + */ + @Override + public @NotNull String reverse(V v) throws NoSuchElementException { + try { return kInterpreter.reverse(getSource().keyOrThrow(v)); + } catch (NoSuchElementException e) { + throw new NoSuchElementException("Key not found for the provided value."); } - }; - } - - { - this.invertedInterpreter = new Interpreter<>() { - @Override - public @NotNull K interpret(String input) throws Exception { - return getSource().keyOrThrow(vInterpreter.interpret(input)); - } - - @Override - public @NotNull String reverse(K k) { + } + }; + + // Create the inverted interpreter + this.invertedInterpreter = new Interpreter<>() { + /** + * Interprets the given input as a key and retrieves the corresponding value from the source. + * + * @param input The input to interpret. + * @return The interpreted key. + * @throws Exception if an error occurs during interpretation or key retrieval. + */ + @Override + public @NotNull K interpret(String input) throws Exception { + return getSource().keyOrThrow(vInterpreter.interpret(input)); + } + + /** + * Reverses the interpretation by converting the key back to its corresponding value. + * + * @param k The key to reverse. + * @return The reversed value as a string. + * @throws NoSuchElementException If the value corresponding to the key is not found in the index. + */ + @Override + public @NotNull String reverse(K k) throws NoSuchElementException { + try { return vInterpreter.reverse(getSource().valueOrThrow(k)); + } catch (NoSuchElementException e) { + throw new NoSuchElementException("Value not found for the provided key."); } - }; - } - + } + }; } + /** + * Retrieves the data source associated with this interpreter provider. + * + * @return The index-based data source. + */ public Index getSource() { return source; } /** + * Returns the interpreter to use based on the inversion flag. * - * @return the {@link Interpreter} to use! + * @return The interpreter instance. */ @Override public Interpreter get() { return !inverted ? normalInterpreter : invertedInterpreter; } + /** + * Retrieves the inverted interpreter. + * + * @return The interpreter for inverted interpretation. + */ public Interpreter getInvertedInterpreter() { return invertedInterpreter; } + /** + * Retrieves the normal (non-inverted) interpreter. + * + * @return The interpreter for normal interpretation. + */ public Interpreter getNormalInterpreter() { return normalInterpreter; } /** - * Indicates if the {@link #get()} method will return a {@link Interpreter} otherwise an {@link Interpreter} will be returned - * @return if the {@link IndexBackedInterpreterProvider} acts inverted or not! + * Indicates whether the interpretation of the `get()` method is inverted or not. + * + * @return `true` if the interpretation is inverted, `false` otherwise. */ public boolean isInverted() { return inverted; } -} +} \ No newline at end of file From 4aa281b88df037914cdf45353f56881c23903075 Mon Sep 17 00:00:00 2001 From: TDR Date: Thu, 18 May 2023 14:40:59 +0200 Subject: [PATCH 45/60] bump 1.6 --- API/pom.xml | 2 +- .../representations/Representation.java | 26 ++++++++++++++++--- AdventureAPI/pom.xml | 4 +-- .../core/adventure/api/AdventureAPI.java | 2 +- AdventureCore/pom.xml | 4 +-- .../core/adventure/AdventureCore.java | 2 +- Core/pom.xml | 4 +-- .../main/java/net/juligames/core/Core.java | 4 +-- HazelAPI/pom.xml | 4 +-- Master/dependency-reduced-pom.xml | 2 +- Master/pom.xml | 4 +-- MiniGameAPI/pom.xml | 4 +-- PaperAPI/pom.xml | 4 +-- PaperCore/dependency-reduced-pom.xml | 2 +- PaperCore/pom.xml | 8 +++--- SuperCore/pom.xml | 10 +++---- VelocityAPI/pom.xml | 4 +-- VelocityCore/dependency-reduced-pom.xml | 2 +- VelocityCore/pom.xml | 8 +++--- .../juligames/core/velocity/VelocityCore.java | 2 +- pom.xml | 2 +- 21 files changed, 62 insertions(+), 42 deletions(-) diff --git a/API/pom.xml b/API/pom.xml index 40440753..9fd80cd9 100644 --- a/API/pom.xml +++ b/API/pom.xml @@ -12,7 +12,7 @@ JuliGamesCore net.juligames.core - 1.6-SNAPSHOT + 1.6 4.0.0 diff --git a/API/src/main/java/net/juligames/core/api/config/representations/Representation.java b/API/src/main/java/net/juligames/core/api/config/representations/Representation.java index 9811dde3..270f7a16 100644 --- a/API/src/main/java/net/juligames/core/api/config/representations/Representation.java +++ b/API/src/main/java/net/juligames/core/api/config/representations/Representation.java @@ -1,12 +1,14 @@ package net.juligames.core.api.config.representations; import org.jetbrains.annotations.ApiStatus; -import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import java.util.function.Supplier; /** + * The `Representation` interface defines a representation of a value of type `T`. + * + * @param The type of the value to represent. * @author Ture Bentzin * 17.04.2023 */ @@ -14,15 +16,33 @@ @FunctionalInterface public interface Representation { - @Contract(pure = true) + /** + * Creates a representation of the provided value. + * + * @param t The value to represent. + * @param The type of the value. + * @return The representation of the value. + */ static @NotNull Representation of(T t) { return () -> t; } - @Contract(pure = true) + /** + * Creates a representation based on the provided supplier. + * + * @param supplier The supplier that provides the value. + * @param The type of the value. + * @return The representation based on the supplier. + */ static @NotNull Representation of(@NotNull Supplier supplier) { return supplier::get; } + /** + * Retrieves the represented value. + * + * @return The represented value. + */ T represent(); } + diff --git a/AdventureAPI/pom.xml b/AdventureAPI/pom.xml index 560539b6..1331fef7 100644 --- a/AdventureAPI/pom.xml +++ b/AdventureAPI/pom.xml @@ -12,7 +12,7 @@ JuliGamesCore net.juligames.core - 1.6-SNAPSHOT + 1.6 4.0.0 @@ -30,7 +30,7 @@ net.juligames.core API - 1.6-SNAPSHOT + 1.6 diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/AdventureAPI.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/AdventureAPI.java index ec9f07dd..16f188dd 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/AdventureAPI.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/AdventureAPI.java @@ -18,7 +18,7 @@ * Please make sure the modules (AdventureAPI & AdventureCore) are the same version to avoid issues while execution! */ public interface AdventureAPI { - @NotNull String API_VERSION = "1.6-SNAPSHOT"; + @NotNull String API_VERSION = "1.6"; static @NotNull AdventureAPI get() { AdventureAPI api = AdventureAPICore.getAPI(); diff --git a/AdventureCore/pom.xml b/AdventureCore/pom.xml index 8cdcd15d..44e5204f 100644 --- a/AdventureCore/pom.xml +++ b/AdventureCore/pom.xml @@ -6,7 +6,7 @@ JuliGamesCore net.juligames.core - 1.6-SNAPSHOT + 1.6 4.0.0 @@ -22,7 +22,7 @@ net.juligames.core AdventureAPI - 1.6-SNAPSHOT + 1.6 diff --git a/AdventureCore/src/main/java/net/juligames/core/adventure/AdventureCore.java b/AdventureCore/src/main/java/net/juligames/core/adventure/AdventureCore.java index adc28832..01d2b02b 100644 --- a/AdventureCore/src/main/java/net/juligames/core/adventure/AdventureCore.java +++ b/AdventureCore/src/main/java/net/juligames/core/adventure/AdventureCore.java @@ -21,7 +21,7 @@ * support it. Because of this the AdventureAPI will only function as intended when bundled with the API you are using! */ public class AdventureCore implements AdventureAPI { - final String CORE_VERSION = "1.6-SNAPSHOT"; + final String CORE_VERSION = "1.6"; private CoreAdventureTagManager adventureTagManager; private Logger logger; diff --git a/Core/pom.xml b/Core/pom.xml index 97c20e4d..25057e66 100644 --- a/Core/pom.xml +++ b/Core/pom.xml @@ -12,7 +12,7 @@ JuliGamesCore net.juligames.core - 1.6-SNAPSHOT + 1.6 4.0.0 @@ -30,7 +30,7 @@ net.juligames.core HazelAPI - 1.6-SNAPSHOT + 1.6 org.jdbi diff --git a/Core/src/main/java/net/juligames/core/Core.java b/Core/src/main/java/net/juligames/core/Core.java index 4bc82b80..194bab11 100644 --- a/Core/src/main/java/net/juligames/core/Core.java +++ b/Core/src/main/java/net/juligames/core/Core.java @@ -48,9 +48,9 @@ public final class Core implements API { * This can be set depending on the build of the Core */ public static final String CORE_BRAND = "Core"; - public static final String CORE_VERSION_NUMBER = "1.6-SNAPSHOT"; + public static final String CORE_VERSION_NUMBER = "1.6"; public static final String CORE_SPECIFICATION = "Gustav"; - private static final String BUILD_VERSION = "1.6-SNAPSHOT"; //POM VERSION + private static final String BUILD_VERSION = "1.6"; //POM VERSION private static Core core; private final Registerator> hazelcastPostPreparationWorkers = new Registerator<>("hazelcastPostPreparationWorkers"); diff --git a/HazelAPI/pom.xml b/HazelAPI/pom.xml index b8843393..6124cdb7 100644 --- a/HazelAPI/pom.xml +++ b/HazelAPI/pom.xml @@ -6,7 +6,7 @@ JuliGamesCore net.juligames.core - 1.6-SNAPSHOT + 1.6 4.0.0 @@ -28,7 +28,7 @@ net.juligames.core API - 1.6-SNAPSHOT + 1.6 compile diff --git a/Master/dependency-reduced-pom.xml b/Master/dependency-reduced-pom.xml index e002a95d..ba2c20fc 100644 --- a/Master/dependency-reduced-pom.xml +++ b/Master/dependency-reduced-pom.xml @@ -3,7 +3,7 @@ JuliGamesCore net.juligames.core - 1.6-SNAPSHOT + 1.6 4.0.0 Master diff --git a/Master/pom.xml b/Master/pom.xml index 049c8fb0..7b01e112 100644 --- a/Master/pom.xml +++ b/Master/pom.xml @@ -6,7 +6,7 @@ JuliGamesCore net.juligames.core - 1.6-SNAPSHOT + 1.6 4.0.0 @@ -22,7 +22,7 @@ net.juligames.core Core - 1.6-SNAPSHOT + 1.6 org.jetbrains diff --git a/MiniGameAPI/pom.xml b/MiniGameAPI/pom.xml index ec8386c7..83a2169d 100644 --- a/MiniGameAPI/pom.xml +++ b/MiniGameAPI/pom.xml @@ -6,7 +6,7 @@ JuliGamesCore net.juligames.core - 1.6-SNAPSHOT + 1.6 4.0.0 @@ -22,7 +22,7 @@ net.juligames.core PaperAPI - 1.6-SNAPSHOT + 1.6 provided diff --git a/PaperAPI/pom.xml b/PaperAPI/pom.xml index cf6956f3..e3ce7f2c 100644 --- a/PaperAPI/pom.xml +++ b/PaperAPI/pom.xml @@ -12,7 +12,7 @@ JuliGamesCore net.juligames.core - 1.6-SNAPSHOT + 1.6 4.0.0 @@ -34,7 +34,7 @@ net.juligames.core AdventureAPI - 1.6-SNAPSHOT + 1.6 compile diff --git a/PaperCore/dependency-reduced-pom.xml b/PaperCore/dependency-reduced-pom.xml index 94138164..5a4833ac 100644 --- a/PaperCore/dependency-reduced-pom.xml +++ b/PaperCore/dependency-reduced-pom.xml @@ -3,7 +3,7 @@ JuliGamesCore net.juligames.core - 1.6-SNAPSHOT + 1.6 4.0.0 PaperCore diff --git a/PaperCore/pom.xml b/PaperCore/pom.xml index 17466f35..c55b8158 100644 --- a/PaperCore/pom.xml +++ b/PaperCore/pom.xml @@ -6,7 +6,7 @@ JuliGamesCore net.juligames.core - 1.6-SNAPSHOT + 1.6 4.0.0 @@ -16,19 +16,19 @@ net.juligames.core PaperAPI - 1.6-SNAPSHOT + 1.6 compile net.juligames.core Core - 1.6-SNAPSHOT + 1.6 compile net.juligames.core AdventureCore - 1.6-SNAPSHOT + 1.6 compile diff --git a/SuperCore/pom.xml b/SuperCore/pom.xml index 01e4b5b1..0610287d 100644 --- a/SuperCore/pom.xml +++ b/SuperCore/pom.xml @@ -6,7 +6,7 @@ net.juligames.core JuliGamesCore - 1.6-SNAPSHOT + 1.6 SuperCore @@ -22,22 +22,22 @@ net.juligames.core Master - 1.6-SNAPSHOT + 1.6 net.juligames.core PaperCore - 1.6-SNAPSHOT + 1.6 net.juligames.core VelocityCore - 1.6-SNAPSHOT + 1.6 net.juligames.core MiniGameAPI - 1.6-SNAPSHOT + 1.6 diff --git a/VelocityAPI/pom.xml b/VelocityAPI/pom.xml index a629a1a2..e459a66b 100644 --- a/VelocityAPI/pom.xml +++ b/VelocityAPI/pom.xml @@ -12,7 +12,7 @@ JuliGamesCore net.juligames.core - 1.6-SNAPSHOT + 1.6 4.0.0 @@ -35,7 +35,7 @@ net.juligames.core AdventureAPI - 1.6-SNAPSHOT + 1.6 compile diff --git a/VelocityCore/dependency-reduced-pom.xml b/VelocityCore/dependency-reduced-pom.xml index e9183dcb..b4552eb7 100644 --- a/VelocityCore/dependency-reduced-pom.xml +++ b/VelocityCore/dependency-reduced-pom.xml @@ -3,7 +3,7 @@ JuliGamesCore net.juligames.core - 1.6-SNAPSHOT + 1.6 4.0.0 VelocityCore diff --git a/VelocityCore/pom.xml b/VelocityCore/pom.xml index 4b6a161f..27d70dfa 100644 --- a/VelocityCore/pom.xml +++ b/VelocityCore/pom.xml @@ -6,7 +6,7 @@ JuliGamesCore net.juligames.core - 1.6-SNAPSHOT + 1.6 4.0.0 @@ -22,7 +22,7 @@ net.juligames.core VelocityAPI - 1.6-SNAPSHOT + 1.6 compile @@ -34,13 +34,13 @@ net.juligames.core Core - 1.6-SNAPSHOT + 1.6 compile net.juligames.core AdventureCore - 1.6-SNAPSHOT + 1.6 compile diff --git a/VelocityCore/src/main/java/net/juligames/core/velocity/VelocityCore.java b/VelocityCore/src/main/java/net/juligames/core/velocity/VelocityCore.java index ee26b788..d6e4f0c0 100644 --- a/VelocityCore/src/main/java/net/juligames/core/velocity/VelocityCore.java +++ b/VelocityCore/src/main/java/net/juligames/core/velocity/VelocityCore.java @@ -23,7 +23,7 @@ * 03.12.2022 */ -@Plugin(id = "velocitycore", name = "JuliGames Velocity Core", version = "1.6-SNAPSHOT", +@Plugin(id = "velocitycore", name = "JuliGames Velocity Core", version = "1.6", url = "https://github.com/JuliGames/JuliGamesCore", description = "Velocity Client for the core - necessary to provide the API here", authors = {"Ture Bentzin"}) public final class VelocityCore { diff --git a/pom.xml b/pom.xml index 0f61b20f..ae2278c8 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ net.juligames.core JuliGamesCore pom - 1.6-SNAPSHOT + 1.6 PaperCore Core From a6f9bb4f9daa2f37aa7179b69857a2cb0155463d Mon Sep 17 00:00:00 2001 From: TDR Date: Fri, 19 May 2023 16:49:40 +0200 Subject: [PATCH 46/60] little fixes and TransitivePrompt --- .../api/message/MiniMessageSerializer.java | 1 - .../api/prompt/msc/TransitivePrompt.java | 110 ++++++++++++++++++ .../core/paper/prompt/MaterialPrompt.java | 1 - 3 files changed, 110 insertions(+), 2 deletions(-) create mode 100644 AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/msc/TransitivePrompt.java diff --git a/API/src/main/java/net/juligames/core/api/message/MiniMessageSerializer.java b/API/src/main/java/net/juligames/core/api/message/MiniMessageSerializer.java index 1d30bd6a..c34fd1ea 100644 --- a/API/src/main/java/net/juligames/core/api/message/MiniMessageSerializer.java +++ b/API/src/main/java/net/juligames/core/api/message/MiniMessageSerializer.java @@ -65,4 +65,3 @@ public interface MiniMessageSerializer { */ @NotNull String translateLegacySectionToMiniMessage(@NotNull String section); } -} diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/msc/TransitivePrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/msc/TransitivePrompt.java new file mode 100644 index 00000000..18442403 --- /dev/null +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/msc/TransitivePrompt.java @@ -0,0 +1,110 @@ +package net.juligames.core.adventure.api.prompt.msc; + +import de.bentzin.conversationlib.ConversationContext; +import de.bentzin.conversationlib.prompt.Prompt; +import de.bentzin.conversationlib.prompt.ValidatingPrompt; +import de.bentzin.tools.logging.Logger; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.ComponentLike; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.TestOnly; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.function.BiFunction; +import java.util.function.Function; + +/** + * @author Ture Bentzin + * 19.05.2023 + */ +public abstract class TransitivePrompt extends ValidatingPrompt { + + private final @NotNull Function typeSupplier; + private final @NotNull BiFunction transitiveFunction; + + public TransitivePrompt(@NotNull Function typeSupplier, @NotNull BiFunction transitiveFunction) { + this.typeSupplier = typeSupplier; + this.transitiveFunction = transitiveFunction; + } + + public static TransitivePrompt functional( + @NotNull Function messageFunction, + @NotNull Function typeSupplier, + @NotNull BiFunction transitiveFunction, + @Nullable BiFunction acceptTransitiveInputFunction + ) { + return new TransitivePrompt(typeSupplier, transitiveFunction) { + @Override + protected @Nullable Prompt acceptTransitiveInput(@NotNull ConversationContext context, @NotNull R relation) { + if (acceptTransitiveInputFunction == null) return null; + return acceptTransitiveInputFunction.apply(context, relation); + } + + @Override + public @NotNull ComponentLike getPromptMessage(@NotNull ConversationContext conversationContext) { + return messageFunction.apply(conversationContext); + } + }; + } + + @Override + protected boolean isInputValid(@NotNull ConversationContext context, @NotNull String input) { + try { + final T t = supplyType(context); + transitiveFunction.apply(t, input); + } catch (Exception e) { + return false; + } + return true; + } + + @Override + protected @Nullable Prompt acceptValidatedInput(@NotNull ConversationContext context, @NotNull String input) { + final T t = supplyType(context); + R applied = transitiveFunction.apply(t, input); + return acceptTransitiveInput(context, applied); + } + + protected abstract @Nullable Prompt acceptTransitiveInput(@NotNull ConversationContext context, @NotNull R relation); + + public @NotNull BiFunction getTransitiveFunction() { + return transitiveFunction; + } + + public @NotNull T supplyType(ConversationContext context) { + return typeSupplier.apply(context); + } + + + //DO NOT PUSH TO VERSION CONTROL + @TestOnly + private static class Test { + + + public static void main(String[] args) { + final Prompt trans = TransitivePrompt., Method>functional( + context -> Component.text("this text was removed..."), + context -> context.getData("class"), + (aClass, s) -> { + try { + return aClass.getMethod(s, (Class[]) null); + } catch (NoSuchMethodException e) { + throw new RuntimeException(e); + } + }, + (context, method) -> { + try { + method.invoke(context.getData("object"), (Object[]) null); + return END_OF_CONVERSATION; + } catch (IllegalAccessException | InvocationTargetException e) { + ((Logger) context.getData("logger")).error("this text was removed too." + e.getMessage()); + throw new RuntimeException(e); + } + } + ); + + } + } +} diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/prompt/MaterialPrompt.java b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/MaterialPrompt.java index 83d684bf..0f7097db 100644 --- a/PaperAPI/src/main/java/net/juligames/core/paper/prompt/MaterialPrompt.java +++ b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/MaterialPrompt.java @@ -24,7 +24,6 @@ protected boolean isInputValid(@NotNull ConversationContext context, @NotNull St @Override protected @Nullable Prompt acceptValidatedInput(@NotNull ConversationContext context, @NotNull String input) { - MapPalette.matchColor() return acceptMaterialInput(context, Objects.requireNonNull(Material.getMaterial(input))); } From 977f3364563c22dbb44ba6c9cf849c65128b6146 Mon Sep 17 00:00:00 2001 From: TDR Date: Fri, 19 May 2023 16:50:01 +0200 Subject: [PATCH 47/60] Update TransitivePrompt.java --- .../api/prompt/msc/TransitivePrompt.java | 38 +------------------ 1 file changed, 2 insertions(+), 36 deletions(-) diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/msc/TransitivePrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/msc/TransitivePrompt.java index 18442403..6ecf599c 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/msc/TransitivePrompt.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/msc/TransitivePrompt.java @@ -3,15 +3,11 @@ import de.bentzin.conversationlib.ConversationContext; import de.bentzin.conversationlib.prompt.Prompt; import de.bentzin.conversationlib.prompt.ValidatingPrompt; -import de.bentzin.tools.logging.Logger; -import net.kyori.adventure.text.Component; import net.kyori.adventure.text.ComponentLike; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.annotations.TestOnly; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; import java.util.function.BiFunction; import java.util.function.Function; @@ -19,6 +15,7 @@ * @author Ture Bentzin * 19.05.2023 */ +@ApiStatus.AvailableSince("1.6") public abstract class TransitivePrompt extends ValidatingPrompt { private final @NotNull Function typeSupplier; @@ -76,35 +73,4 @@ protected boolean isInputValid(@NotNull ConversationContext context, @NotNull St public @NotNull T supplyType(ConversationContext context) { return typeSupplier.apply(context); } - - - //DO NOT PUSH TO VERSION CONTROL - @TestOnly - private static class Test { - - - public static void main(String[] args) { - final Prompt trans = TransitivePrompt., Method>functional( - context -> Component.text("this text was removed..."), - context -> context.getData("class"), - (aClass, s) -> { - try { - return aClass.getMethod(s, (Class[]) null); - } catch (NoSuchMethodException e) { - throw new RuntimeException(e); - } - }, - (context, method) -> { - try { - method.invoke(context.getData("object"), (Object[]) null); - return END_OF_CONVERSATION; - } catch (IllegalAccessException | InvocationTargetException e) { - ((Logger) context.getData("logger")).error("this text was removed too." + e.getMessage()); - throw new RuntimeException(e); - } - } - ); - - } - } } From 2ff72f8804da8a8f2f108793210dabf95f5ad267 Mon Sep 17 00:00:00 2001 From: TDR Date: Fri, 19 May 2023 17:19:23 +0200 Subject: [PATCH 48/60] add new methods to the HazelDataAPI --- .../net/juligames/core/api/misc/APIUtils.java | 32 ++++++++++-- .../juligames/core/api/misc/Predicates.java | 52 +++++++++++++++++++ .../juligames/core/data/HazelDataCore.java | 20 +++++++ .../core/api/hazel/NativeHazelDataAPI.java | 16 ++++++ 4 files changed, 115 insertions(+), 5 deletions(-) create mode 100644 API/src/main/java/net/juligames/core/api/misc/Predicates.java diff --git a/API/src/main/java/net/juligames/core/api/misc/APIUtils.java b/API/src/main/java/net/juligames/core/api/misc/APIUtils.java index 0500ad7c..daa42be4 100644 --- a/API/src/main/java/net/juligames/core/api/misc/APIUtils.java +++ b/API/src/main/java/net/juligames/core/api/misc/APIUtils.java @@ -3,9 +3,9 @@ import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; -import java.util.Collection; -import java.util.Collections; -import java.util.List; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Stream; /** * @author Ture Bentzin @@ -25,7 +25,7 @@ private APIUtils() { * @param exceptions a collection of exceptions that should not be counted as a failure * @return `true` if the `ThrowingRunnable` completes without throwing an exception or if the thrown exception is not contained in the specified collection of exceptions */ - public static boolean executedWithoutException(@NotNull ThrowingRunnable runnable, Collection exceptions) { + public static boolean executedWithoutException(@NotNull ThrowingRunnable runnable, @NotNull Collection exceptions) { try { runnable.run(); return true; @@ -62,7 +62,7 @@ public static boolean executedWithoutException(@NotNull ThrowingRunnable runnabl * @param exceptions a collection of exceptions that should not be counted as a failure * @return `true` if the `Runnable` completes without throwing an exception or if the thrown exception is not contained in the specified collection of exceptions */ - public static boolean executedWithoutExceptionL(@NotNull Runnable runnable, Collection exceptions) { + public static boolean executedWithoutExceptionL(@NotNull Runnable runnable, @NotNull Collection exceptions) { try { runnable.run(); return true; @@ -80,4 +80,26 @@ public static boolean executedWithoutExceptionL(@NotNull Runnable runnable, Coll public static boolean executedWithoutExceptionL(@NotNull Runnable runnable) { return executedWithoutExceptionL(runnable, Collections.emptyList()); } + + /** + * Maps the elements of the input stream using the provided mapper function, while dropping any elements that cause an exception during mapping. + * + * @param the type of the input stream elements + * @param the type of the resulting stream elements + * @param stream the input stream to be mapped + * @param mapper the mapping function to apply to each element of the input stream + * @return a new stream containing the mapped elements, with any elements causing an exception during mapping dropped + */ + public static @NotNull Stream mapOrDrop(@NotNull Stream stream, @NotNull Function mapper) { + List list = new ArrayList<>(); + stream.forEachOrdered(t -> { + try { + list.add(mapper.apply(t)); + } catch (Exception ignored) { + // drop + } + }); + return list.stream(); + } + } diff --git a/API/src/main/java/net/juligames/core/api/misc/Predicates.java b/API/src/main/java/net/juligames/core/api/misc/Predicates.java new file mode 100644 index 00000000..3b77c89b --- /dev/null +++ b/API/src/main/java/net/juligames/core/api/misc/Predicates.java @@ -0,0 +1,52 @@ +package net.juligames.core.api.misc; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Consumer; +import java.util.function.Predicate; + +/** + * This class provides predicates + * @implNote might use {@link APIUtils#executedWithoutExceptionL(Runnable)} later + * @author Ture Bentzin + * 19.05.2023 + */ +public class Predicates { + + private Predicates() { + + } + + @Contract(pure = true) + @ApiStatus.AvailableSince("1.6") + public static @NotNull Predicate instanceOf(Class clazz) { + return t -> t.getClass().isInstance(clazz); + } + + @Contract(pure = true) + @ApiStatus.AvailableSince("1.6") + public static @NotNull Predicate nestedIn(Class clazz) { + return t -> t.getClass().getNestHost().equals(clazz); + } + + @Contract(pure = true) + @ApiStatus.AvailableSince("1.6") + public static @NotNull Predicate executes(Consumer operation) { + return t -> { + try { + operation.accept(t); + } catch (Exception e) { + return false; + } + return true; + }; + } + + @Contract(pure = true) + @ApiStatus.AvailableSince("1.6") + public static @NotNull Predicate fails(Consumer operation) { + return Predicate.not(executes(operation)); + } +} diff --git a/Core/src/main/java/net/juligames/core/data/HazelDataCore.java b/Core/src/main/java/net/juligames/core/data/HazelDataCore.java index d5039621..0eadaa92 100644 --- a/Core/src/main/java/net/juligames/core/data/HazelDataCore.java +++ b/Core/src/main/java/net/juligames/core/data/HazelDataCore.java @@ -10,9 +10,11 @@ import net.juligames.core.Core; import net.juligames.core.api.data.HazelDataApi; import net.juligames.core.api.hazel.NativeHazelDataAPI; +import net.juligames.core.api.misc.APIUtils; import org.jetbrains.annotations.NotNull; import java.util.Collection; +import java.util.Optional; /** * @author Ture Bentzin @@ -57,5 +59,23 @@ public final class HazelDataCore implements HazelDataApi, NativeHazelDataAPI { return getHazelcastInstance().getDistributedObjects(); } + /** + * Retrieves an instance of the specified type that extends DistributedObject, with the given name. + * + * @param hazel the name of the distributed object to retrieve + * @param the type of the distributed object to retrieve + * @return an Optional containing the instance of the distributed object, if found; otherwise, an empty Optional + * @throws NullPointerException if the hazel parameter is null + */ + @Override + public @NotNull Optional get(@NotNull String hazel) { + //noinspection unchecked + return APIUtils.mapOrDrop(getAll() + .stream() + .filter(distributedObject -> + distributedObject.getName().equals(hazel)), + distributedObject -> (T) distributedObject).findAny(); + } + } diff --git a/HazelAPI/src/main/java/net/juligames/core/api/hazel/NativeHazelDataAPI.java b/HazelAPI/src/main/java/net/juligames/core/api/hazel/NativeHazelDataAPI.java index 2854a9ad..065d33a4 100644 --- a/HazelAPI/src/main/java/net/juligames/core/api/hazel/NativeHazelDataAPI.java +++ b/HazelAPI/src/main/java/net/juligames/core/api/hazel/NativeHazelDataAPI.java @@ -7,8 +7,10 @@ import com.hazelcast.map.IMap; import com.hazelcast.topic.ITopic; import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; import java.util.Collection; +import java.util.Optional; /** * @author Ture Bentzin @@ -66,4 +68,18 @@ public interface NativeHazelDataAPI { @ApiStatus.Experimental @ApiStatus.AvailableSince("1.5") Collection getAll(); + + /** + * Retrieves an instance of the specified type that extends DistributedObject, with the given name. + * This method can be used to automatically determine the type of hazel! + * The implementation might be changed over a version. + * This one should not be used outside user interface applications + * @apiNote The implementation currently uses {@link #getAll()} and {@link java.util.function.Predicate}s to + * determine what will be returned. + * @param hazel hazel + * @return the optional that may contain a {@link DistributedObject} + * @param the implementation of {@link DistributedObject} + */ + @ApiStatus.AvailableSince("1.6") + Optional get(@NotNull String hazel); } From 0d801a8def320d3c056e9405f2f75e7fc362d3d2 Mon Sep 17 00:00:00 2001 From: TDR Date: Fri, 19 May 2023 17:19:58 +0200 Subject: [PATCH 49/60] javadoc IterableSplitter --- .../core/config/IterableSplitter.java | 99 +++++++++++++++++-- 1 file changed, 90 insertions(+), 9 deletions(-) diff --git a/Core/src/main/java/net/juligames/core/config/IterableSplitter.java b/Core/src/main/java/net/juligames/core/config/IterableSplitter.java index 6eff05ac..796699fe 100644 --- a/Core/src/main/java/net/juligames/core/config/IterableSplitter.java +++ b/Core/src/main/java/net/juligames/core/config/IterableSplitter.java @@ -10,15 +10,31 @@ import java.util.stream.Collectors; /** + * The IterableSplitter class provides utility methods for splitting and processing iterables. + * It allows splitting an iterable into strings, writing the split strings to a configuration, + * and reading split strings from a configuration and interpreting them as objects of a given type. + * This class is final and cannot be subclassed. + * * @author Ture Bentzin * 10.01.2023 */ public final class IterableSplitter { + /** + * Private constructor to prevent instantiation of the IterableSplitter class. + */ private IterableSplitter() { } - + /** + * Splits the elements of the given iterable into strings using the provided interpreter and returns a list of the split strings. + * + * @param the type of the elements in the iterable + * @param iterable the iterable to be split + * @param interpreter the interpreter to convert elements to strings + * @return a list of strings representing the split elements + * @throws NullPointerException if the iterable or interpreter parameter is null + */ @Contract(pure = true) public static @NotNull List simpleSplit(@NotNull Iterable iterable, Interpreter interpreter) { final ArrayList data = new ArrayList<>(); @@ -29,46 +45,111 @@ private IterableSplitter() { return data; } + /** + * Splits the elements of the given iterable into strings using the provided interpreter + * and returns a SplitCollectionConfigWriter that can be used to write the split strings to a configuration. + * + * @param the type of the elements in the iterable + * @param iterable the iterable to be split + * @param interpreter the interpreter to convert elements to strings + * @return a SplitCollectionConfigWriter for writing the split strings to a configuration + * @throws NullPointerException if the iterable or interpreter parameter is null + */ @Contract(pure = true) public static @NotNull SplitCollectionConfigWriter splitToWriter(Iterable iterable, Interpreter interpreter) { return new SplitCollectionConfigWriter(simpleSplit(iterable, interpreter)); } + /** + * Splits the elements of the given iterable into strings using the provided interpreter + * and writes the split strings to the given configuration under the specified key space. + * + * @param the type of the elements in the iterable + * @param iterable the iterable to be split + * @param interpreter the interpreter to convert elements to strings + * @param configuration the configuration to write the split strings to + * @param keySpace the key space under which the split strings will be written + * @throws NullPointerException if any of the iterable, interpreter, configuration, or keySpace parameters is null + */ public static void splitAndWrite(Iterable iterable, Interpreter interpreter, Configuration configuration, String keySpace) { splitToWriter(iterable, interpreter).write(configuration, keySpace); } + /** + * Reads a collection of objects of the specified type from the given strings using the provided interpreter. + * Any strings that cannot be interpreted as objects will be ignored. + * + * @param the type of the objects to read + * @param strings the strings to read the objects from + * @param interpreter the interpreter to convert strings to objects + * @return a collection of objects interpreted from the strings + * @throws NullPointerException if the strings or interpreter parameter is null + */ public static @NotNull Collection tryReadStrings(@NotNull Iterable strings, Interpreter interpreter) { final Collection ts = new ArrayList<>(); - for (String value : strings) + for (String value : strings) { try { ts.add(interpreter.interpret(value)); } catch (Exception ignored) { + // Ignore strings that cannot be interpreted as objects } + } return ts; } + /** + * Reads a collection of objects of the specified type from the values in the given configuration + * that are associated with keys starting with the specified key space. + * + * @param the type of the objects to read + * @param configuration the configuration to read the values from + * @param keySpace the key space indicating the keys to read the values from + * @param interpreter the interpreter to convert strings to objects + * @return a collection of objects interpreted from the configuration values + * @throws NullPointerException if any of the configuration, keySpace, or interpreter parameters is null + */ public static @NotNull Collection tryReadSplitCollection(@NotNull Configuration configuration, String keySpace, Interpreter interpreter) { - return tryReadStrings(configuration.entrySet().stream().filter(entry -> - entry.getKey().startsWith(keySpace)).map(Map.Entry::getValue) - .collect(Collectors.toUnmodifiableSet()), interpreter); + return tryReadStrings( + configuration.entrySet() + .stream() + .filter(entry -> entry.getKey().startsWith(keySpace)) + .map(Map.Entry::getValue) + .collect(Collectors.toUnmodifiableSet()), + interpreter); } + /** + * The SplitCollectionConfigWriter class provides a way to write split strings to a configuration. + * It implements the ConfigWriter interface and is used by the splitToWriter method in the IterableSplitter class. + */ public static final class SplitCollectionConfigWriter implements ConfigWriter { - final List data; + private final List data; + /** + * Constructs a SplitCollectionConfigWriter with the given list of split strings. + * + * @param simpleSplit the list of split strings to be written to a configuration + * @throws NullPointerException if the simpleSplit parameter is null + */ public SplitCollectionConfigWriter(List simpleSplit) { data = Collections.unmodifiableList(simpleSplit); } + /** + * Writes the split strings to the specified configuration under the given key space. + * + * @param configuration the configuration to write the split strings to + * @param keySpace the key space under which the split strings will be written + * @throws NullPointerException if the configuration or keySpace parameter is null + */ @Override - public void write(@NotNull Configuration configuration, @NotNull String keyspace) { + public void write(@NotNull Configuration configuration, @NotNull String keySpace) { for (int i = 0; i < data.size(); i++) { final String simple = data.get(i); - final String key = keyspace + "_" + i; + final String key = keySpace + "_" + i; configuration.setString(key, simple); } } } -} +} \ No newline at end of file From 513c00d9f8df3979c17c93bd3181ffb3247bd134 Mon Sep 17 00:00:00 2001 From: TDR Date: Fri, 19 May 2023 17:24:04 +0200 Subject: [PATCH 50/60] javadoc GenericHashtableToStringHashtableMapper --- ...nericHashtableToStringHashtableMapper.java | 30 +++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/API/src/main/java/net/juligames/core/api/misc/GenericHashtableToStringHashtableMapper.java b/API/src/main/java/net/juligames/core/api/misc/GenericHashtableToStringHashtableMapper.java index 5f6e032b..d29f992e 100644 --- a/API/src/main/java/net/juligames/core/api/misc/GenericHashtableToStringHashtableMapper.java +++ b/API/src/main/java/net/juligames/core/api/misc/GenericHashtableToStringHashtableMapper.java @@ -9,6 +9,10 @@ import java.util.function.Function; /** + * The GenericHashtableToStringHashtableMapper class is a function that maps a Hashtable with generic key-value types + * to a Hashtable with String keys and String values. + * It uses provided interpreters to convert the keys and values of the input Hashtable to their String representations. + * * @author Ture Bentzin * 03.03.2023 */ @@ -18,17 +22,39 @@ public class GenericHashtableToStringHashtableMapper implements Function kInterpreter; private final @NotNull Interpreter vInterpreter; + /** + * Constructs a GenericHashtableToStringHashtableMapper with the given key and value interpreters. + * + * @param kInterpreter the interpreter for converting keys to String + * @param vInterpreter the interpreter for converting values to String + * @throws NullPointerException if the kInterpreter or vInterpreter parameter is null + */ public GenericHashtableToStringHashtableMapper(@NotNull Interpreter kInterpreter, @NotNull Interpreter vInterpreter) { this.kInterpreter = kInterpreter; this.vInterpreter = vInterpreter; - } + /** + * Creates a new GenericHashtableToStringHashtableMapper with a parallel interpreter for keys and values of the same type. + * + * @param the type of the keys and values + * @param tInterpreter the interpreter for converting keys and values to String + * @return a GenericHashtableToStringHashtableMapper with parallel key and value interpreters + * @throws NullPointerException if the tInterpreter parameter is null + */ @Contract(value = "_ -> new", pure = true) public static @NotNull GenericHashtableToStringHashtableMapper createParallel(final Interpreter tInterpreter) { return new GenericHashtableToStringHashtableMapper<>(tInterpreter, tInterpreter); } + /** + * Applies the mapping function to the given input Hashtable, converting its keys and values to String + * and creating a new Hashtable with String keys and String values. + * + * @param objectObjectHashtable the input Hashtable to be mapped + * @return a new Hashtable with String keys and String values + * @throws NullPointerException if the objectObjectHashtable parameter is null + */ @Override public @NotNull Hashtable apply(@NotNull Hashtable objectObjectHashtable) { final Hashtable stringStringHashtable = new Hashtable<>(); @@ -36,4 +62,4 @@ public GenericHashtableToStringHashtableMapper(@NotNull Interpreter kInterpre stringStringHashtable.put(kInterpreter.reverse(key), vInterpreter.reverse(value))); return stringStringHashtable; } -} +} \ No newline at end of file From 3640522b1930fbbf0bf1280f77b5f79fa347e320 Mon Sep 17 00:00:00 2001 From: TDR Date: Sun, 21 May 2023 13:29:26 +0200 Subject: [PATCH 51/60] fix two headers --- .../net/juligames/core/api/config/Interpreter.java | 3 +++ .../net/juligames/core/api/message/MessageApi.java | 12 +++++++----- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/API/src/main/java/net/juligames/core/api/config/Interpreter.java b/API/src/main/java/net/juligames/core/api/config/Interpreter.java index f45c9075..bc8196b0 100644 --- a/API/src/main/java/net/juligames/core/api/config/Interpreter.java +++ b/API/src/main/java/net/juligames/core/api/config/Interpreter.java @@ -35,6 +35,9 @@ * * * @param the type of object that this Interpreter can interpret + * @author Ture Bentzin + * 26.11.2022 + * @see BuildInInterpreters */ public non-sealed interface Interpreter extends Reverser, PrimitiveInterpreter { diff --git a/API/src/main/java/net/juligames/core/api/message/MessageApi.java b/API/src/main/java/net/juligames/core/api/message/MessageApi.java index b79080d0..b0583364 100644 --- a/API/src/main/java/net/juligames/core/api/message/MessageApi.java +++ b/API/src/main/java/net/juligames/core/api/message/MessageApi.java @@ -29,14 +29,16 @@ * replacements. * * @author Ture Bentzin + * 18.11.2022 * @apiNote Please consider that the core your using may not support all the - * operations below. If a core should not support one of the methods - * there are two options what could happen. First the core could - * automatically execute a similar Method and print a warning. If this - * should not be possible then the Core will throw an + * operations below. + * If a core should not support one of the methods, there are two options for what could happen. + * First, the core could + * automatically execute a similar Method and print a warning. + * If this + * should not be possible, then the Core will throw an * {@link UnsupportedOperationException} with further information on * how to approach this issue. - * @since 18.11.2022 */ @SuppressWarnings("unused") public interface MessageApi { From 80f1b9cbb603471c7fa87d652187861fb8c6d8f0 Mon Sep 17 00:00:00 2001 From: TDR Date: Fri, 26 May 2023 19:16:55 +0200 Subject: [PATCH 52/60] some additions --- .../main/java/net/juligames/core/api/API.java | 13 +++- .../core/api/config/EnumInterpreter.java | 27 ++++++++ .../config/property/PropertyInterpreter.java | 21 ++++++ .../net/juligames/core/api/misc/APIUtils.java | 67 +++++++++++++++++-- .../main/java/net/juligames/core/Core.java | 28 ++++++++ 5 files changed, 149 insertions(+), 7 deletions(-) diff --git a/API/src/main/java/net/juligames/core/api/API.java b/API/src/main/java/net/juligames/core/api/API.java index bbdef188..686035d2 100644 --- a/API/src/main/java/net/juligames/core/api/API.java +++ b/API/src/main/java/net/juligames/core/api/API.java @@ -1,6 +1,7 @@ package net.juligames.core.api; import de.bentzin.tools.logging.Logger; +import de.bentzin.tools.logging.Logging; import de.bentzin.tools.misc.SubscribableType; import net.juligames.core.api.cacheing.CacheApi; import net.juligames.core.api.cluster.ClusterApi; @@ -22,13 +23,14 @@ import java.util.Optional; import java.util.function.Predicate; import java.util.function.Supplier; +import java.util.logging.LogManager; /** * @author Ture Bentzin * 16.11.2022 * @implNote Main class to be used to get the different parts of the api */ -public interface API { +public interface API extends Logging { /** * This is the primary way for getting your API Instance. With this Instance you have access to all build in features in the core @@ -148,6 +150,15 @@ public interface API { @NotNull Collection supplyOnlineRecipients(); + /** + * When using a {@link LogManager} you should use {@link API#getJavaLogManager()} to get hold of it + * @return an {@link LogManager} instance that is or acts like {@link LogManager#getLogManager()} + * @apiNote This is not associated with the {@link de.bentzin.tools.logging} package and environment + */ + @ApiStatus.Experimental + @ApiStatus.AvailableSince("1.6") + @NotNull LogManager getJavaLogManager(); + /* * * @return if the core is connected and ready for operation diff --git a/API/src/main/java/net/juligames/core/api/config/EnumInterpreter.java b/API/src/main/java/net/juligames/core/api/config/EnumInterpreter.java index 5c0fe39e..809a46b2 100644 --- a/API/src/main/java/net/juligames/core/api/config/EnumInterpreter.java +++ b/API/src/main/java/net/juligames/core/api/config/EnumInterpreter.java @@ -4,8 +4,35 @@ import org.jetbrains.annotations.NotNull; /** + * Here is an exmaple on how to use the {@link EnumInterpreter} with the fictional enum "Color" + *

+ * {@code
+ * public enum Color {
+ *     RED,
+ *     GREEN,
+ *     BLUE
+ * }
+ *
+ * public class Main {
+ *     public static void main(String[] args) {
+ *         EnumInterpreter colorInterpreter = new EnumInterpreter<>(Color.class);
+ *
+ *         // Reverse an enum value to a string
+ *         Color color = Color.RED;
+ *         String reversed = colorInterpreter.reverse(color);
+ *         System.out.println("Reversed: " + reversed); // Output: Reversed: RED
+ *
+ *         // Interpret a string as an enum value
+ *         String input = "GREEN";
+ *         Color interpreted = colorInterpreter.interpret(input);
+ *         System.out.println("Interpreted: " + interpreted); // Output: Interpreted: GREEN
+ *     }
+ * }
+ * }
+ * 
* @author Ture Bentzin * 15.03.2023 + */ @ApiStatus.AvailableSince("1.5") @ApiStatus.Experimental diff --git a/API/src/main/java/net/juligames/core/api/config/property/PropertyInterpreter.java b/API/src/main/java/net/juligames/core/api/config/property/PropertyInterpreter.java index ba267a2d..e6e13262 100644 --- a/API/src/main/java/net/juligames/core/api/config/property/PropertyInterpreter.java +++ b/API/src/main/java/net/juligames/core/api/config/property/PropertyInterpreter.java @@ -11,6 +11,27 @@ * The {@link PropertyInterpreter} allows to store a reference to a property that is set. The value that is read will * be used as the "key" for getting the property. If you {@link #reverse(Object)} then {@link String#valueOf(Object)} * will be used + *

+ * This is an example on how to use the {@link PropertyInterpreter} specifically the {@link PropertyInterpreter#stringPropertyInterpreter()} + *

+ *
+ *     {@code
+ *         // Create a PropertyInterpreter for String properties
+ *         PropertyInterpreter stringPropertyInterpreter
+ *              = PropertyInterpreter.stringPropertyInterpreter();
+ *
+ *         // Get the value of a String property
+ *         String propertyValue = stringPropertyInterpreter.interpret("my.property");
+ *         System.out.println("Property value: " + propertyValue);
+ *
+ *         // Reverse a String value to a property
+ *         String reversedValue = "Hello, World!";
+ *         String propertyKey = stringPropertyInterpreter.reverse(reversedValue);
+ *         System.out.println("Property key: " + propertyKey);
+ *
+ *
+ *     }
+ * 
* * @author Ture Bentzin * 07.03.2023 diff --git a/API/src/main/java/net/juligames/core/api/misc/APIUtils.java b/API/src/main/java/net/juligames/core/api/misc/APIUtils.java index daa42be4..06bcc2ad 100644 --- a/API/src/main/java/net/juligames/core/api/misc/APIUtils.java +++ b/API/src/main/java/net/juligames/core/api/misc/APIUtils.java @@ -1,10 +1,17 @@ package net.juligames.core.api.misc; +import de.bentzin.tools.Independent; +import de.bentzin.tools.logging.JavaLogger; import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; import java.util.function.Function; +import java.util.logging.Logger; import java.util.stream.Stream; /** @@ -18,6 +25,23 @@ private APIUtils() { } + /** + * Formats a StackFrame object to obtain caller information. + * + * @param frame The StackFrame object representing the caller. + * @return A formatted string containing caller information. + */ + @Independent + public static @NotNull String formatCaller(StackWalker.@NotNull StackFrame frame) { + return frame.getMethodName() + + "@" + + frame.getClassName() + + ":" + frame.getLineNumber() + + (frame.getClassName().equals(frame.getFileName()) + ? " " + : " located in " + frame.getFileName() + "[" + frame.getByteCodeIndex() + "]"); + } + /** * Executes the given `ThrowingRunnable` and returns `true` if it completes without throwing an exception, or if the thrown exception is not contained in the specified collection of exceptions. * @@ -25,6 +49,7 @@ private APIUtils() { * @param exceptions a collection of exceptions that should not be counted as a failure * @return `true` if the `ThrowingRunnable` completes without throwing an exception or if the thrown exception is not contained in the specified collection of exceptions */ + @Independent public static boolean executedWithoutException(@NotNull ThrowingRunnable runnable, @NotNull Collection exceptions) { try { runnable.run(); @@ -40,6 +65,7 @@ public static boolean executedWithoutException(@NotNull ThrowingRunnable runnabl * @param runnable the `ThrowingRunnable` to execute * @return `true` if the `ThrowingRunnable` completes without throwing an exception */ + @Independent public static boolean executedWithoutException(@NotNull ThrowingRunnable runnable) { return executedWithoutException(runnable, Collections.emptyList()); } @@ -51,6 +77,7 @@ public static boolean executedWithoutException(@NotNull ThrowingRunnable runnabl * @param exceptions an array of exceptions that should not be counted as a failure * @return `true` if the `ThrowingRunnable` completes without throwing an exception or if the thrown exception is not contained in the specified array of exceptions */ + @Independent public static boolean executedWithoutException(@NotNull ThrowingRunnable runnable, Exception... exceptions) { return executedWithoutException(runnable, List.of(exceptions)); } @@ -62,6 +89,7 @@ public static boolean executedWithoutException(@NotNull ThrowingRunnable runnabl * @param exceptions a collection of exceptions that should not be counted as a failure * @return `true` if the `Runnable` completes without throwing an exception or if the thrown exception is not contained in the specified collection of exceptions */ + @Independent public static boolean executedWithoutExceptionL(@NotNull Runnable runnable, @NotNull Collection exceptions) { try { runnable.run(); @@ -77,6 +105,7 @@ public static boolean executedWithoutExceptionL(@NotNull Runnable runnable, @Not * @param runnable the `Runnable` to execute * @return `true` if the `Runnable` completes without throwing an exception */ + @Independent public static boolean executedWithoutExceptionL(@NotNull Runnable runnable) { return executedWithoutExceptionL(runnable, Collections.emptyList()); } @@ -84,12 +113,13 @@ public static boolean executedWithoutExceptionL(@NotNull Runnable runnable) { /** * Maps the elements of the input stream using the provided mapper function, while dropping any elements that cause an exception during mapping. * - * @param the type of the input stream elements - * @param the type of the resulting stream elements - * @param stream the input stream to be mapped - * @param mapper the mapping function to apply to each element of the input stream - * @return a new stream containing the mapped elements, with any elements causing an exception during mapping dropped + * @param the type of the input stream elements + * @param the type of the resulting stream elements + * @param stream the input stream to be mapped + * @param mapper the mapping function to apply to each element of the input stream + * @return a new stream containing the mapped elements, with any elements causing an exception during mapping dropped */ + @Independent public static @NotNull Stream mapOrDrop(@NotNull Stream stream, @NotNull Function mapper) { List list = new ArrayList<>(); stream.forEachOrdered(t -> { @@ -102,4 +132,29 @@ public static boolean executedWithoutExceptionL(@NotNull Runnable runnable) { return list.stream(); } + /** + * Creates a JavaLogger instance from a {@link Logger}. + * + * @param logger The {@link Logger} instance. + * @return A {@link JavaLogger} instance. + */ + @Contract("_ -> new") + @Independent + public static @NotNull JavaLogger fromUtil(Logger logger) { + return new JavaLogger(logger.getName(), logger); + } + + /** + * Creates a JavaLogger instance from a logger name. + * + * @param name The name of the logger. + * @return A {@link JavaLogger} instance. + */ + @Contract("_ -> new") + @Independent + public static @NotNull JavaLogger fromName(String name) { + return fromUtil(Logger.getLogger(name)); + } + + } diff --git a/Core/src/main/java/net/juligames/core/Core.java b/Core/src/main/java/net/juligames/core/Core.java index 194bab11..b3915633 100644 --- a/Core/src/main/java/net/juligames/core/Core.java +++ b/Core/src/main/java/net/juligames/core/Core.java @@ -14,6 +14,7 @@ import net.juligames.core.api.err.dev.TODOException; import net.juligames.core.api.message.MessageRecipient; import net.juligames.core.api.minigame.BasicMiniGame; +import net.juligames.core.api.misc.APIUtils; import net.juligames.core.caching.CoreCacheApi; import net.juligames.core.caching.MessageCaching; import net.juligames.core.cluster.CoreClusterApi; @@ -37,6 +38,8 @@ import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; +import java.util.logging.LogManager; +import java.util.stream.Stream; /** * @author Ture Bentzin @@ -79,6 +82,14 @@ public Core() { * @param core_name the core name */ public Core(String core_name) { + APIUtils.fromName("JG-Foreman") + .debug(getShortCoreName() + " started by " + APIUtils.formatCaller( + StackWalker + .getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE) + .walk(Stream::findFirst) + .orElseThrow(() -> new IllegalCallerException("Core cant identify caller of constructor?!"))) + ); + start(core_name); } @@ -166,6 +177,12 @@ public void start(String core_name, @NotNull Logger logger, boolean member) { if (!Boolean.getBoolean("acknowledgeUnsafeMasterCheck")) { coreLogger.info("checking compatibility with master.."); final String masterVersion = getHazelDataApi().getMasterInformation().get("master_version"); + if(masterVersion == null) { + coreLogger.error("Flawed data! Please check if hazelcast is working correctly and if your master" + + " is operating normal! If you see this message on your Master, you should get in touch with me at " + + "mailto://bentzin@tdrstudios.de! Thank you for using JuliGamesCore. It is likely that your JuliGamesCore Cluster " + + "starts but you should expect severe issues after reading this message!"); + } if (!getVersion().equals(masterVersion)) { coreLogger.warning("********************************************************"); @@ -410,6 +427,11 @@ public void setOnlineRecipientProvider(@NotNull Supplier> getHazelcastPostPreparationWorkers() { return hazelcastPostPreparationWorkers; } @@ -421,4 +443,10 @@ protected void finalize() { //Currently only for testing around with GarbageColl getCoreLogger().debug("This API implementation is no longer available!"); } } + + @Contract(pure = true) + @Override + public @NotNull Logger getLogger() { + return getAPILogger(); + } } From eb81421855f9d37f2dc997831e73257bd5557102 Mon Sep 17 00:00:00 2001 From: TDR Date: Fri, 26 May 2023 20:14:42 +0200 Subject: [PATCH 53/60] master improvements --- .run/CoreMaster.run.xml | 17 +++++ .../juligames/core/api/data/HazelDataApi.java | 8 +++ .../net/juligames/core/api/misc/APIUtils.java | 24 +++++-- .../main/java/net/juligames/core/Core.java | 2 + .../core/config/CoreConfiguration.java | 2 +- .../juligames/core/data/HazelDataCore.java | 5 ++ .../net/juligames/core/master/CoreMaster.java | 23 +++--- .../core/master/cmd/PrintMapCommand.java | 71 ++++++++++++++----- .../data/MasterHazelInformationProvider.java | 5 +- .../core/master/logging/MasterLogger.java | 6 ++ 10 files changed, 130 insertions(+), 33 deletions(-) create mode 100644 .run/CoreMaster.run.xml diff --git a/.run/CoreMaster.run.xml b/.run/CoreMaster.run.xml new file mode 100644 index 00000000..d9b6b1c4 --- /dev/null +++ b/.run/CoreMaster.run.xml @@ -0,0 +1,17 @@ + + + + \ No newline at end of file diff --git a/API/src/main/java/net/juligames/core/api/data/HazelDataApi.java b/API/src/main/java/net/juligames/core/api/data/HazelDataApi.java index a75ff20f..130b5d1a 100644 --- a/API/src/main/java/net/juligames/core/api/data/HazelDataApi.java +++ b/API/src/main/java/net/juligames/core/api/data/HazelDataApi.java @@ -1,6 +1,7 @@ package net.juligames.core.api.data; import de.bentzin.tools.Hardcode; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -55,5 +56,12 @@ default Map getMasterInformation() { return getMap("master_information"); } + /** + * This method trys to guess if {@link #getMasterInformation()} will provide a populated map. + * It provides no information about the last update + */ + @ApiStatus.AvailableSince("1.6") + boolean isMasterInformationAvailable(); + } diff --git a/API/src/main/java/net/juligames/core/api/misc/APIUtils.java b/API/src/main/java/net/juligames/core/api/misc/APIUtils.java index 06bcc2ad..7ce385b1 100644 --- a/API/src/main/java/net/juligames/core/api/misc/APIUtils.java +++ b/API/src/main/java/net/juligames/core/api/misc/APIUtils.java @@ -6,11 +6,9 @@ import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; +import java.util.*; import java.util.function.Function; +import java.util.function.Supplier; import java.util.logging.Logger; import java.util.stream.Stream; @@ -132,6 +130,24 @@ public static boolean executedWithoutExceptionL(@NotNull Runnable runnable) { return list.stream(); } + @ApiStatus.Experimental + public static void executeAndSwallow(ThrowingRunnable throwingRunnable) { + try { + throwingRunnable.run(); + } catch (Exception ignored) { + } + } + + @SafeVarargs + public static Optional executeAndReturnFirstSuccess(Supplier @NotNull ... suppliers) { + for (Supplier supplier : suppliers) { + try { + return Optional.of(supplier.get()); + }catch (Exception ignore) {} + } + return Optional.empty(); + } + /** * Creates a JavaLogger instance from a {@link Logger}. * diff --git a/Core/src/main/java/net/juligames/core/Core.java b/Core/src/main/java/net/juligames/core/Core.java index b3915633..2cf0d0fc 100644 --- a/Core/src/main/java/net/juligames/core/Core.java +++ b/Core/src/main/java/net/juligames/core/Core.java @@ -173,6 +173,7 @@ public void start(String core_name, @NotNull Logger logger, boolean member) { .addMessageListener(coreNotificationApi); + if(getHazelDataApi().isMasterInformationAvailable()) { if (!Boolean.getBoolean("acknowledgeUnsafeMasterCheck")) { coreLogger.info("checking compatibility with master.."); @@ -196,6 +197,7 @@ public void start(String core_name, @NotNull Logger logger, boolean member) { } } } + else logger.debug("master information is not available! If you see this on the Master it is expected behavior"); logger.info("hooking to shutdown..."); getJavaRuntime().addShutdownHook(new Thread(() -> { diff --git a/Core/src/main/java/net/juligames/core/config/CoreConfiguration.java b/Core/src/main/java/net/juligames/core/config/CoreConfiguration.java index 7c3a032c..69f3649b 100644 --- a/Core/src/main/java/net/juligames/core/config/CoreConfiguration.java +++ b/Core/src/main/java/net/juligames/core/config/CoreConfiguration.java @@ -60,7 +60,7 @@ public CoreConfiguration(String name) { for (Map.Entry entry : entries) { if (override) { String old = map.put(entry.getKey().toString(), entry.getValue().toString()); //oh man... oh man - Core.getInstance().getCoreLogger().debug("OVERRIDE: set " + entry.getKey() + "from " + old + " to " + entry.getValue()); + Core.getInstance().getCoreLogger().debug("OVERRIDE: set " + entry.getKey() + " from " + old + " to " + entry.getValue()); } else if (!map.containsKey(entry.getKey().toString())) { String old = map.put(entry.getKey().toString(), entry.getValue().toString()); //oh man... oh man Core.getInstance().getCoreLogger().debug("set " + entry.getKey() + "from " + old + " to " + entry.getValue()); diff --git a/Core/src/main/java/net/juligames/core/data/HazelDataCore.java b/Core/src/main/java/net/juligames/core/data/HazelDataCore.java index 0eadaa92..577a6071 100644 --- a/Core/src/main/java/net/juligames/core/data/HazelDataCore.java +++ b/Core/src/main/java/net/juligames/core/data/HazelDataCore.java @@ -49,6 +49,11 @@ public final class HazelDataCore implements HazelDataApi, NativeHazelDataAPI { return getHazelcastInstance().getList(hazel); } + @Override + public boolean isMasterInformationAvailable() { + return getMasterInformation().containsKey("available"); + } + @Override public @NotNull ITopic getTopic(@NotNull String hazel) { return getHazelcastInstance().getTopic(hazel); diff --git a/Master/src/main/java/net/juligames/core/master/CoreMaster.java b/Master/src/main/java/net/juligames/core/master/CoreMaster.java index 12967be6..cc925fde 100644 --- a/Master/src/main/java/net/juligames/core/master/CoreMaster.java +++ b/Master/src/main/java/net/juligames/core/master/CoreMaster.java @@ -35,23 +35,26 @@ private CoreMaster() { public static void main(String[] args) { + //Setup + MasterLogger.setupJavaLogging(); + logger = new MasterLogger("Master", java.util.logging.Logger.getLogger(Core.getShortRelease())); //entry point for Master masterCommandRunner = new MasterCommandRunner(logger); masterConfigManager = new MasterConfigManager(); - logger.info("welcome to " + Core.getFullCoreName() + " Master by Ture Bentzin "); + logger.info("Welcome to " + Core.getFullCoreName() + " Master by Ture Bentzin "); - logger.info("preparing directory..."); + logger.info("Preparing directory..."); masterConfigManager.createDatabaseConfiguration(); - logger.info("booting hazelcast (MEMBER CORE):"); + logger.info("Booting hazelcast (MEMBER CORE):"); Core core = new Core(); try { core.getHazelcastPostPreparationWorkers().register(hazelcastInstance -> { - logger.info("loading config"); + logger.info("Loading config"); masterConfigManager.load(); }); } catch (Registerator.DuplicateEntryException ignored) { @@ -67,11 +70,11 @@ public static void main(String[] args) { logger.error("FAILED TO SETUP HAZELCAST - Master will probably start anyway but the master should be restarted as soon as possible"); } - logger.info("hazelcast boot was completed - advice: hazelcast could potentially fail to boot for a variety of reasons, so if you should see" + + logger.info("Hazelcast boot was completed - advice: hazelcast could potentially fail to boot for a variety of reasons, so if you should see" + "an error above then you might want to restart the master. In the case that the Clients are put on hold by the core you should also" + "consider restarting."); - logger.debug("sql: start"); + logger.debug("SQL: start"); SQLManager = Core.getInstance().getSQLManager(); SQLManager.createTables(); //MASTER CREATES TABLES (NOT THE CORE!!!) @@ -83,7 +86,7 @@ public static void main(String[] args) { //Data masterHazelInformationProvider = new MasterHazelInformationProvider(hazelcast); - logger.warning("not all code execution on master is stable because the master DOES NOT PROVIDE a fully usable core!!!"); + logger.warning("Not all code execution on master is stable because the master DOES NOT PROVIDE a fully usable core!!!"); try { registerCommands(); } catch (Registerator.DuplicateEntryException e) { @@ -92,15 +95,15 @@ public static void main(String[] args) { } //CommandSystem - logger.info("registering CommandHandler..."); + logger.info("Registering CommandHandler..."); core.getCommandApi().setCommandHandler(new CommandHandler()); - logger.info("master is now ready to receive commands from hazelcast"); + logger.info("Master is now ready to receive commands from hazelcast"); //HOOK Core.getInstance().getJavaRuntime().addShutdownHook(new Thread(() -> { try { - logger.info("master is going down!!"); + logger.info("Master is going down!!"); } catch (Exception ignored) { System.out.println("Seems like everything is cursed right now. Please report this!"); } diff --git a/Master/src/main/java/net/juligames/core/master/cmd/PrintMapCommand.java b/Master/src/main/java/net/juligames/core/master/cmd/PrintMapCommand.java index 56fd2dcd..8a7b7e99 100644 --- a/Master/src/main/java/net/juligames/core/master/cmd/PrintMapCommand.java +++ b/Master/src/main/java/net/juligames/core/master/cmd/PrintMapCommand.java @@ -2,11 +2,18 @@ import com.hazelcast.core.DistributedObject; import com.hazelcast.map.IMap; +import de.bentzin.tools.logging.Logger; import net.juligames.core.Core; import net.juligames.core.api.TODO; +import net.juligames.core.api.misc.APIUtils; import org.jetbrains.annotations.NotNull; import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Predicate; + +import static net.juligames.core.api.misc.APIUtils.executeAndReturnFirstSuccess; +import static net.juligames.core.api.misc.APIUtils.executeAndSwallow; /** * @author Ture Bentzin @@ -23,27 +30,59 @@ public PrintMapCommand() { public void executeCommand(@NotNull String commandString) { String[] s = commandString.replaceFirst(" ", "").split(" "); String ident = s[0]; - Optional optionalDistributedObject = - Core.getInstance().getOrThrow().getDistributedObjects().stream() - .filter(distributedObject -> distributedObject.getName().equals(ident)) - .findFirst(); - if (optionalDistributedObject.isEmpty()) { - throw new IllegalArgumentException("cant find: " + ident); - } - IMap map = Core.getInstance().getOrThrow().getMap(ident); - Core.getInstance().getCoreLogger().info("printing result of printMap: " + ident); - final boolean[] first = {true}; - Core.getInstance().getCoreLogger().warning("The here referenced classes may be inaccurate"); + final IMap map = findMap(ident); + Logger coreLogger = Core.getInstance().getCoreLogger(); + coreLogger.info("printing result of printMap: " + map.getName()); + + AtomicReference> keyClass = new AtomicReference<>(); + AtomicReference> valueClass = new AtomicReference<>(); map.forEach((o, o2) -> { - if (first[0]) { - first[0] = false; - Core.getInstance().getCoreLogger().info("keyClass: " + o.getClass().getSimpleName()); - Core.getInstance().getCoreLogger().info("valueClass: " + o2.getClass().getSimpleName()); + if (o == null || o2 == null) { + coreLogger.warning("FLAWED: " + o + " :! " + o2); + return; } - Core.getInstance().getCoreLogger().info(o.toString() + " : " + o2.toString()); + if (keyClass.get() != o.getClass() || valueClass.get() != o2.getClass()) { + coreLogger.info(o.getClass().getSimpleName() + " | " + o2.getClass().getSimpleName()); + keyClass.set(o.getClass()); + valueClass.set(o2.getClass()); + } + + coreLogger.info(o + " : " + o2); }); } + + + @SuppressWarnings("unchecked") + protected IMap findMap(String query) { + return (IMap) executeAndReturnFirstSuccess( + //Equal names + () -> findMapHard(query,distributedObject -> distributedObject.getName().equals(query)), + //Semi Equal names + () -> findMapHard(query,distributedObject -> distributedObject.getName().equalsIgnoreCase(query)), + //Starts with + () -> findMapHard(query, distributedObject -> distributedObject.getName().startsWith(query)), + //Starts with (semi) + () -> findMapHard(query, distributedObject -> distributedObject.getName().toLowerCase().startsWith(query.toLowerCase())), + //Contains + () -> findMapHard(query, distributedObject -> distributedObject.getName().contains(query)), + //Contains (semi) + () -> findMapHard(query, distributedObject -> distributedObject.getName().toLowerCase().contains(query.toLowerCase())) + + ).orElseThrow(() -> new IllegalArgumentException("cant find a map for query: \"" + query + "\"")); + } + + @SuppressWarnings("unchecked") + private @NotNull IMap findMapHard(String name, Predicate predicate) { + Optional optionalDistributedObject = + Core.getInstance().getOrThrow().getDistributedObjects().stream() + .filter(predicate) + .findFirst(); + if (optionalDistributedObject.isEmpty()) { + throw new IllegalArgumentException("cant find: " + name); + } + return (IMap)optionalDistributedObject.get(); + } } diff --git a/Master/src/main/java/net/juligames/core/master/data/MasterHazelInformationProvider.java b/Master/src/main/java/net/juligames/core/master/data/MasterHazelInformationProvider.java index c4bcfb89..55a40a50 100644 --- a/Master/src/main/java/net/juligames/core/master/data/MasterHazelInformationProvider.java +++ b/Master/src/main/java/net/juligames/core/master/data/MasterHazelInformationProvider.java @@ -38,15 +38,16 @@ protected void genMap() { public void update() { //Locale DBLocale defaultEnglish = CoreSQLManager.defaultEnglish(); + informationMap().put("available", ""); informationMap().put("default_locale", defaultEnglish.getLocale()); informationMap().put("default_locale_description", defaultEnglish.getDescription()); informationMap().put("master_uuid", hazelcast.getLocalEndpoint().getUuid().toString()); informationMap().put("master_name", hazelcast.getName()); informationMap().put("master_boot", String.valueOf(CoreMaster.getBootMillis().orElseThrow())); informationMap().put("master_version", API.get().getVersion()); - informationMap().put("last_update", System.currentTimeMillis() + ""); + informationMap().put("last_update", String.valueOf(System.currentTimeMillis())); //Experimental - informationMap().put("master_commands", CoreMaster.getMasterCommandRunner().getIndex() + ""); + informationMap().put("master_commands", CoreMaster.getMasterCommandRunner().getIndex().toString()); informationMap().put("hazelcast_version", VersionFinder.getVersion()); informationMap().put("master_os", VersionFinder.OS.name()); informationMap().put("java_version", VersionFinder.JAVA_VERSION); diff --git a/Master/src/main/java/net/juligames/core/master/logging/MasterLogger.java b/Master/src/main/java/net/juligames/core/master/logging/MasterLogger.java index 53ee208f..943c39dc 100644 --- a/Master/src/main/java/net/juligames/core/master/logging/MasterLogger.java +++ b/Master/src/main/java/net/juligames/core/master/logging/MasterLogger.java @@ -2,6 +2,7 @@ import de.bentzin.tools.logging.JavaLogger; import de.bentzin.tools.logging.Logger; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import java.time.LocalDateTime; @@ -13,6 +14,11 @@ */ public final class MasterLogger extends JavaLogger { + @ApiStatus.AvailableSince("1.6") + public static void setupJavaLogging() { + System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tF %1$tT] [%4$-7s] %5$s %n"); + } + public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(" HH:mm:ss"); public MasterLogger(String name, @NotNull Logger parent, java.util.logging.@NotNull Logger logger) { From bff09bdf01ad43c9d9bf6f0db11d7cbbf1c0979e Mon Sep 17 00:00:00 2001 From: TDR Date: Sun, 18 Jun 2023 17:31:42 +0200 Subject: [PATCH 54/60] Delete ConversationTest.java --- .../src/main/java/test/ConversationTest.java | 17 ----------------- 1 file changed, 17 deletions(-) delete mode 100644 VelocityCore/src/main/java/test/ConversationTest.java diff --git a/VelocityCore/src/main/java/test/ConversationTest.java b/VelocityCore/src/main/java/test/ConversationTest.java deleted file mode 100644 index 5ce248ee..00000000 --- a/VelocityCore/src/main/java/test/ConversationTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package test; - -import de.bentzin.conversationlib.manager.ConversationManager; -import net.kyori.adventure.audience.Audience; - -/** - * @author Ture Bentzin - * 25.03.2023 - */ -public class ConversationTest { - public static void demo() { - - ConversationManager conversationManager = new ConversationManager(); - Audience player = Audience.empty(); - - } -} From 9e649c0c673e698db1bf472eb2976674b6739f79 Mon Sep 17 00:00:00 2001 From: Ture Bentzin <38729194+TureBentzin@users.noreply.github.com> Date: Sun, 18 Jun 2023 17:32:54 +0200 Subject: [PATCH 55/60] aligning stringification Co-authored-by: Bommels05 <69975756+Bommels05@users.noreply.github.com> --- .../core/master/data/MasterHazelInformationProvider.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Master/src/main/java/net/juligames/core/master/data/MasterHazelInformationProvider.java b/Master/src/main/java/net/juligames/core/master/data/MasterHazelInformationProvider.java index 55a40a50..c6933126 100644 --- a/Master/src/main/java/net/juligames/core/master/data/MasterHazelInformationProvider.java +++ b/Master/src/main/java/net/juligames/core/master/data/MasterHazelInformationProvider.java @@ -47,7 +47,7 @@ public void update() { informationMap().put("master_version", API.get().getVersion()); informationMap().put("last_update", String.valueOf(System.currentTimeMillis())); //Experimental - informationMap().put("master_commands", CoreMaster.getMasterCommandRunner().getIndex().toString()); + informationMap().put("master_commands", String.valueOf(CoreMaster.getMasterCommandRunner().getIndex())); informationMap().put("hazelcast_version", VersionFinder.getVersion()); informationMap().put("master_os", VersionFinder.OS.name()); informationMap().put("java_version", VersionFinder.JAVA_VERSION); From 50eb8877504c0eb60c7de61ac9c6da4ed7bc517f Mon Sep 17 00:00:00 2001 From: TDR Date: Sun, 18 Jun 2023 17:33:01 +0200 Subject: [PATCH 56/60] rename PartialPlayerPrompt.java --- .../{PartiallPlayerPrompt.java => PartialPlayerPrompt.java} | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) rename VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/{PartiallPlayerPrompt.java => PartialPlayerPrompt.java} (81%) diff --git a/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PartiallPlayerPrompt.java b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PartialPlayerPrompt.java similarity index 81% rename from VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PartiallPlayerPrompt.java rename to VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PartialPlayerPrompt.java index 5bf5b594..a3798224 100644 --- a/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PartiallPlayerPrompt.java +++ b/VelocityAPI/src/main/java/net/juligames/core/velocity/prompt/PartialPlayerPrompt.java @@ -15,11 +15,11 @@ * 25.03.2023 */ @ApiStatus.AvailableSince("1.6") -public abstract class PartiallPlayerPrompt extends FixedSetPrompt> implements ProxyServerPrompt, PluginManagerPrompt { +public abstract class PartialPlayerPrompt extends FixedSetPrompt> implements ProxyServerPrompt, PluginManagerPrompt { private final ProxyServer proxyServer; - public PartiallPlayerPrompt(@NotNull ProxyServer proxyServer) { + public PartialPlayerPrompt(@NotNull ProxyServer proxyServer) { super(s -> Collections.singleton(proxyServer.matchPlayer(s).stream().findFirst().orElse(null)), proxyServer.getAllPlayers()); this.proxyServer = proxyServer; From d83da438863aecb0a4daeecb097a57f21f9595a4 Mon Sep 17 00:00:00 2001 From: TDR Date: Sun, 18 Jun 2023 17:38:43 +0200 Subject: [PATCH 57/60] Update MessageRepresentation.java --- .../adventure/api/MessageRepresentation.java | 22 ++----------------- 1 file changed, 2 insertions(+), 20 deletions(-) diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java index 51f0ebb7..f449c5f4 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/MessageRepresentation.java @@ -2,11 +2,9 @@ import net.juligames.core.adventure.AdventureTagManager; import net.juligames.core.api.API; -import net.juligames.core.api.config.BuildInInterpreters; import net.juligames.core.api.config.representations.Representation; import net.juligames.core.api.jdbi.DBLocale; import net.juligames.core.api.message.Message; -import net.juligames.core.api.misc.EntryInterpretationUtil; import net.kyori.adventure.identity.Identity; import net.kyori.adventure.pointer.Pointered; import net.kyori.adventure.text.Component; @@ -15,12 +13,7 @@ import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; -import java.io.File; -import java.net.URL; -import java.util.HashMap; import java.util.Locale; -import java.util.Map; -import java.util.stream.Stream; /** * @author Ture Bentzin @@ -75,13 +68,13 @@ public MessageRepresentation(@NotNull Message message) { //Personal @Contract("_, _ -> new") - public static @NotNull MessageRepresentation represent(String messageKey, Pointered pointered) { + public static @NotNull MessageRepresentation represent(String messageKey, @NotNull Pointered pointered) { return new MessageRepresentation(API.get().getMessageApi().getMessageSmart(messageKey, pointered.get(Identity.LOCALE).orElse(defaultLocale()))); } @Contract("_, _, _ -> new") - public static @NotNull MessageRepresentation represent(String messageKey, Pointered pointered, String... replacements) { + public static @NotNull MessageRepresentation represent(String messageKey, @NotNull Pointered pointered, String... replacements) { return new MessageRepresentation(API.get().getMessageApi().getMessageSmart(messageKey, pointered.get(Identity.LOCALE).orElse(defaultLocale()), replacements)); } @@ -98,17 +91,6 @@ public Message getMessage() { return message; } - private void demo() { - - Map fileURLMap = new HashMap<>(); - Map stringStringMap = EntryInterpretationUtil.reverseMap(fileURLMap, BuildInInterpreters.fileInterpreter(), BuildInInterpreters.urlInterpreter()); - Map fileURLMap1 = EntryInterpretationUtil.interpretMap(stringStringMap, BuildInInterpreters.fileInterpreter(), BuildInInterpreters.urlInterpreter()); - assert fileURLMap1.equals(fileURLMap); - - Stream> entryStream = fileURLMap.entrySet().stream().map(fileURLEntry -> EntryInterpretationUtil.reverseEntry(fileURLEntry, BuildInInterpreters.fileInterpreter(), BuildInInterpreters.urlInterpreter())); - - } - @Override @ApiStatus.AvailableSince("1.6") public Component represent() { From 87a0920cc89c4d4b8219d9f6134a601dd3f38f8b Mon Sep 17 00:00:00 2001 From: Ture Bentzin <38729194+TureBentzin@users.noreply.github.com> Date: Sun, 18 Jun 2023 17:39:04 +0200 Subject: [PATCH 58/60] fix annotation Co-authored-by: Bommels05 <69975756+Bommels05@users.noreply.github.com> --- .../net/juligames/core/api/misc/EntryInterpretationUtil.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/API/src/main/java/net/juligames/core/api/misc/EntryInterpretationUtil.java b/API/src/main/java/net/juligames/core/api/misc/EntryInterpretationUtil.java index 96159491..e588d3d9 100644 --- a/API/src/main/java/net/juligames/core/api/misc/EntryInterpretationUtil.java +++ b/API/src/main/java/net/juligames/core/api/misc/EntryInterpretationUtil.java @@ -11,7 +11,7 @@ import java.util.function.IntFunction; import java.util.stream.Collectors; -@ApiStatus.AvailableSince("1.6") +@ApiStatus.AvailableSince("1.5") public class EntryInterpretationUtil { private EntryInterpretationUtil() { From 6407a4776723139f47114a62b0bcddd9f628e0bd Mon Sep 17 00:00:00 2001 From: Ture Bentzin <38729194+TureBentzin@users.noreply.github.com> Date: Sun, 18 Jun 2023 17:39:43 +0200 Subject: [PATCH 59/60] remove "Experimental" ApiStatus from method Co-authored-by: Bommels05 <69975756+Bommels05@users.noreply.github.com> --- API/src/main/java/net/juligames/core/api/misc/APIUtils.java | 1 - 1 file changed, 1 deletion(-) diff --git a/API/src/main/java/net/juligames/core/api/misc/APIUtils.java b/API/src/main/java/net/juligames/core/api/misc/APIUtils.java index 7ce385b1..79e6441f 100644 --- a/API/src/main/java/net/juligames/core/api/misc/APIUtils.java +++ b/API/src/main/java/net/juligames/core/api/misc/APIUtils.java @@ -130,7 +130,6 @@ public static boolean executedWithoutExceptionL(@NotNull Runnable runnable) { return list.stream(); } - @ApiStatus.Experimental public static void executeAndSwallow(ThrowingRunnable throwingRunnable) { try { throwingRunnable.run(); From 140993d48e4ca1993c08e292c8cdfd944a873190 Mon Sep 17 00:00:00 2001 From: TDR Date: Sun, 18 Jun 2023 17:43:05 +0200 Subject: [PATCH 60/60] final face lift of 1.6 --- .run/CoreMaster.run.xml | 32 +++--- .../main/java/net/juligames/core/api/API.java | 1 + .../core/api/config/EnumInterpreter.java | 2 +- .../core/api/config/Interpreter.java | 4 +- .../core/api/config/PrimitiveInterpreter.java | 4 +- .../juligames/core/api/config/Reverser.java | 13 ++- .../mapbacked/DictionaryFeedInterpreter.java | 4 +- .../config/mapbacked/MapFeedInterpreter.java | 4 +- .../config/property/PropertyInterpreter.java | 2 +- .../representations/Interpretation.java | 6 +- .../api/external/AdventureWebuiEditorAPI.java | 5 +- .../core/api/message/MessageRecipient.java | 5 +- .../api/message/MiniMessageSerializer.java | 1 + .../core/api/message/PatternType.java | 2 +- .../net/juligames/core/api/misc/APIUtils.java | 3 +- .../core/api/misc/DurationFormatUtils.java | 40 +++---- .../api/misc/EntryInterpretationUtil.java | 4 +- .../juligames/core/api/misc/Predicates.java | 3 +- .../core/api/misc/ThrowableDebug.java | 1 - .../core/api/misc/ThrowingRunnable.java | 1 + .../core/adventure/AdventureTagManager.java | 1 + .../api/AudienceMessageRecipient.java | 1 - .../adventure/api/prompt/BackedPrompt.java | 1 - .../adventure/api/prompt/MapBackedPrompt.java | 2 +- .../adventure/CoreAdventureTagManager.java | 1 - .../main/java/net/juligames/core/Core.java | 11 +- .../juligames/core/hcast/HazelConnector.java | 4 +- .../core/api/hazel/NativeHazelDataAPI.java | 7 +- Master/dependency-reduced-pom.xml | 85 +++++++------- .../core/master/cmd/PrintMapCommand.java | 8 +- .../core/master/logging/MasterLogger.java | 10 +- .../core/paper/PaperConversationManager.java | 14 +-- .../core/paper/PaperMessageRecipient.java | 6 + .../inventory/InventoryConfigWriter.java | 10 +- .../ObjectifiedConfiguration.java | 1 - .../core/paper/prompt/MaterialPrompt.java | 1 - PaperCore/dependency-reduced-pom.xml | 105 +++++++++--------- .../juligames/core/paper/PaperCorePlugin.java | 1 - .../conversation/ConversationListener.java | 3 +- SuperCore/pom.xml | 4 +- VelocityCore/dependency-reduced-pom.xml | 105 +++++++++--------- 41 files changed, 267 insertions(+), 251 deletions(-) diff --git a/.run/CoreMaster.run.xml b/.run/CoreMaster.run.xml index d9b6b1c4..e7c386b6 100644 --- a/.run/CoreMaster.run.xml +++ b/.run/CoreMaster.run.xml @@ -1,17 +1,19 @@ - - + + \ No newline at end of file diff --git a/API/src/main/java/net/juligames/core/api/API.java b/API/src/main/java/net/juligames/core/api/API.java index 686035d2..d21192cf 100644 --- a/API/src/main/java/net/juligames/core/api/API.java +++ b/API/src/main/java/net/juligames/core/api/API.java @@ -152,6 +152,7 @@ public interface API extends Logging { /** * When using a {@link LogManager} you should use {@link API#getJavaLogManager()} to get hold of it + * * @return an {@link LogManager} instance that is or acts like {@link LogManager#getLogManager()} * @apiNote This is not associated with the {@link de.bentzin.tools.logging} package and environment */ diff --git a/API/src/main/java/net/juligames/core/api/config/EnumInterpreter.java b/API/src/main/java/net/juligames/core/api/config/EnumInterpreter.java index 809a46b2..b7b279e1 100644 --- a/API/src/main/java/net/juligames/core/api/config/EnumInterpreter.java +++ b/API/src/main/java/net/juligames/core/api/config/EnumInterpreter.java @@ -30,9 +30,9 @@ * } * } * + * * @author Ture Bentzin * 15.03.2023 - */ @ApiStatus.AvailableSince("1.5") @ApiStatus.Experimental diff --git a/API/src/main/java/net/juligames/core/api/config/Interpreter.java b/API/src/main/java/net/juligames/core/api/config/Interpreter.java index bc8196b0..7f06ceb0 100644 --- a/API/src/main/java/net/juligames/core/api/config/Interpreter.java +++ b/API/src/main/java/net/juligames/core/api/config/Interpreter.java @@ -14,7 +14,7 @@ * This is an example implementation for interpreting Integers *
  * {@code
-
+ *
  * public final class IntegerInterpreter implements Interpreter {
  *
  *     @Override
@@ -93,7 +93,7 @@ default  void reverseAndThenComplete(@NotNull T t, @NotNull CompletableFuture
      * CompletableFuture with the result of the interpretation. This process is known as "interpreting the input as an
      * instance of Type T". If the interpretation fails, an Exception will be thrown.
      *
-     * @param input              the input to be interpreted
+     * @param input             the input to be interpreted
      * @param completableFuture the CompletableFuture that should be completed with the result of the interpretation
      * @throws Exception will be thrown if the input cant be interpreted according to this implementation
      */
diff --git a/API/src/main/java/net/juligames/core/api/config/PrimitiveInterpreter.java b/API/src/main/java/net/juligames/core/api/config/PrimitiveInterpreter.java
index 6761432c..2fdecf0c 100644
--- a/API/src/main/java/net/juligames/core/api/config/PrimitiveInterpreter.java
+++ b/API/src/main/java/net/juligames/core/api/config/PrimitiveInterpreter.java
@@ -5,16 +5,18 @@
 
 /**
  * This might be used later outside of this package
+ *
  * @author Ture Bentzin
  * 12.04.2023
  */
 @ApiStatus.Internal
 @ApiStatus.AvailableSince("1.6")
-public sealed interface PrimitiveInterpreter permits Interpreter{
+public sealed interface PrimitiveInterpreter permits Interpreter {
 
     /**
      * Converts the given input according to this implementation to a given Object of the provided Type.
      * This process is known as "interpreting the input as an instance of Type T"
+     *
      * @param input the input to be interpreted
      * @return the instance of T that results the interpretation
      * @throws Exception will be thrown if the input cant be interpreted according to this implementation
diff --git a/API/src/main/java/net/juligames/core/api/config/Reverser.java b/API/src/main/java/net/juligames/core/api/config/Reverser.java
index 89828be5..a718505a 100644
--- a/API/src/main/java/net/juligames/core/api/config/Reverser.java
+++ b/API/src/main/java/net/juligames/core/api/config/Reverser.java
@@ -18,9 +18,10 @@ public sealed interface Reverser permits Interpreter, Reverser.PrivateReverse
 
     /**
      * The function#apply should never return null
+     *
      * @param function the function
+     * @param       Type
      * @return a reverser based on the function
-     * @param  Type
      */
     @Contract(pure = true)
     static  @NotNull Reverser ofFunctional(@NotNull Function function) {
@@ -30,9 +31,10 @@ public sealed interface Reverser permits Interpreter, Reverser.PrivateReverse
     /**
      * This will return a new {@link Reverser} that will execute the {@link #reverse(Object)} method from the given
      * tReverser. This only benefits of you want to prevent casting this {@link Reverser} to a {@link Interpreter}!
+     *
      * @param tReverser the reverser
+     * @param        T
      * @return a new reverser
-     * @param  T
      */
     @ApiStatus.Experimental
     @Contract(pure = true)
@@ -44,8 +46,9 @@ public sealed interface Reverser permits Interpreter, Reverser.PrivateReverse
      * This {@link Reverser} will reverse the given object ONLY based on its toString!
      * Should only be used with EXTREME caution!
      * This does not respect {@link CustomInterpretable}
-     * @return a new reverser
+     *
      * @param  T
+     * @return a new reverser
      */
     @ApiStatus.Experimental
     @Contract(pure = true)
@@ -57,8 +60,9 @@ public sealed interface Reverser permits Interpreter, Reverser.PrivateReverse
      * This {@link Reverser} will reverse the given object ONLY based on its {@link String#valueOf(Object)}!
      * Should only be used with EXTREME caution!
      * This does not respect {@link CustomInterpretable}
-     * @return a new reverser
+     *
      * @param  T
+     * @return a new reverser
      */
     @ApiStatus.Experimental
     @Contract(pure = true)
@@ -81,6 +85,7 @@ public sealed interface Reverser permits Interpreter, Reverser.PrivateReverse
 
     /**
      * Meant ONLY for use with {@link #ofFunctional(Function)}
+     *
      * @param  the type
      */
     @ApiStatus.Internal
diff --git a/API/src/main/java/net/juligames/core/api/config/mapbacked/DictionaryFeedInterpreter.java b/API/src/main/java/net/juligames/core/api/config/mapbacked/DictionaryFeedInterpreter.java
index 58b352d5..7bef683e 100644
--- a/API/src/main/java/net/juligames/core/api/config/mapbacked/DictionaryFeedInterpreter.java
+++ b/API/src/main/java/net/juligames/core/api/config/mapbacked/DictionaryFeedInterpreter.java
@@ -32,7 +32,7 @@ public DictionaryFeedInterpreter(@NotNull Supplier> dictio
     /**
      * Constructs a new {@link DictionaryFeedInterpreter} instance with the given dictionary supplier and map part factory.
      *
-     * @param dictionarySupplier the supplier to use to provide the backing dictionary
+     * @param dictionarySupplier    the supplier to use to provide the backing dictionary
      * @param dictionaryPartFactory the function to use to create map parts based on the dictionary and the key
      */
     public DictionaryFeedInterpreter(@NotNull Supplier> dictionarySupplier,
@@ -64,7 +64,7 @@ public DictionaryFeedInterpreter(@NotNull Supplier> dictio
     /**
      * Creates a new map part with the given key and dictionary supplier using the factory function.
      *
-     * @param key the key of the new map part
+     * @param key                the key of the new map part
      * @param dictionarySupplier the dictionary supplier to use for the new map part
      * @return the newly created map part
      */
diff --git a/API/src/main/java/net/juligames/core/api/config/mapbacked/MapFeedInterpreter.java b/API/src/main/java/net/juligames/core/api/config/mapbacked/MapFeedInterpreter.java
index 71851f69..93a41305 100644
--- a/API/src/main/java/net/juligames/core/api/config/mapbacked/MapFeedInterpreter.java
+++ b/API/src/main/java/net/juligames/core/api/config/mapbacked/MapFeedInterpreter.java
@@ -49,11 +49,11 @@ public MapFeedInterpreter(@NotNull Supplier> mapSupplier,
     }
 
     public @NotNull MapPart fabricate(@NotNull String key, @NotNull Supplier> mapSupplier) {
-        return mapPartFactory.apply(key,mapSupplier);
+        return mapPartFactory.apply(key, mapSupplier);
     }
 
     protected @NotNull MapPart fabricate(@NotNull String key) {
-        return mapPartFactory.apply(key,mapSupplier);
+        return mapPartFactory.apply(key, mapSupplier);
     }
 
     private record MapPartImpl(String key, Supplier> mapSupplier) implements MapPart {
diff --git a/API/src/main/java/net/juligames/core/api/config/property/PropertyInterpreter.java b/API/src/main/java/net/juligames/core/api/config/property/PropertyInterpreter.java
index e6e13262..d76f9f2f 100644
--- a/API/src/main/java/net/juligames/core/api/config/property/PropertyInterpreter.java
+++ b/API/src/main/java/net/juligames/core/api/config/property/PropertyInterpreter.java
@@ -12,7 +12,7 @@
  * be used as the "key" for getting the property. If you {@link #reverse(Object)} then {@link String#valueOf(Object)}
  * will be used
  * 

- * This is an example on how to use the {@link PropertyInterpreter} specifically the {@link PropertyInterpreter#stringPropertyInterpreter()} + * This is an example on how to use the {@link PropertyInterpreter} specifically the {@link PropertyInterpreter#stringPropertyInterpreter()} *

*
  *     {@code
diff --git a/API/src/main/java/net/juligames/core/api/config/representations/Interpretation.java b/API/src/main/java/net/juligames/core/api/config/representations/Interpretation.java
index 7a58036b..5a84a7f7 100644
--- a/API/src/main/java/net/juligames/core/api/config/representations/Interpretation.java
+++ b/API/src/main/java/net/juligames/core/api/config/representations/Interpretation.java
@@ -9,14 +9,14 @@
  * 17.04.2023
  */
 @ApiStatus.AvailableSince("1.6")
-public abstract class Interpretation implements Representation{
+public abstract class Interpretation implements Representation {
+
+    public final @NotNull PrimitiveInterpreter interpreter;
 
     public Interpretation(@NotNull PrimitiveInterpreter interpreter) {
         this.interpreter = interpreter;
     }
 
-    public final @NotNull PrimitiveInterpreter interpreter;
-
     @Override
     public final @NotNull T represent() {
         try {
diff --git a/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java b/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java
index 5895b2da..084a32f6 100644
--- a/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java
+++ b/API/src/main/java/net/juligames/core/api/external/AdventureWebuiEditorAPI.java
@@ -79,6 +79,7 @@ public final class AdventureWebuiEditorAPI {
     public AdventureWebuiEditorAPI(final @NotNull URI root) {
         this(root, HttpClient.newHttpClient());
     }
+
     /**
      * Creates a new instance of the editor API with the default JuliGames api
      */
@@ -200,7 +201,7 @@ public AdventureWebuiEditorAPI(final @NotNull HttpClient client) {
 
     /**
      * @param command command with {token}
-     * @param app app
+     * @param app     app
      * @return the link
      */
     @Contract(pure = true)
@@ -215,7 +216,7 @@ public AdventureWebuiEditorAPI(final @NotNull HttpClient client) {
     /**
      * @param message the initial message
      * @param command command with {token}
-     * @param app app
+     * @param app     app
      * @return the link
      */
     @Contract(pure = true)
diff --git a/API/src/main/java/net/juligames/core/api/message/MessageRecipient.java b/API/src/main/java/net/juligames/core/api/message/MessageRecipient.java
index 0f55b530..3fafc43f 100644
--- a/API/src/main/java/net/juligames/core/api/message/MessageRecipient.java
+++ b/API/src/main/java/net/juligames/core/api/message/MessageRecipient.java
@@ -39,7 +39,7 @@ public interface MessageRecipient {
      * specified.
      *
      * @return the default locale that is distributed by the master, or the locale of this MessageRecipient if
-     *         specified
+     * specified
      */
     default @Nullable String supplyLocaleOrDefault() {
         if (supplyLocale() != null) {
@@ -49,11 +49,10 @@ public interface MessageRecipient {
     }
 
     /**
+     * @param miniMessage the miniMessage string to deliver
      * @deprecated Use {@link #deliver(Message)} instead.
      *
      * 

Delivers a miniMessage string to the recipient.

- * - * @param miniMessage the miniMessage string to deliver */ @Deprecated @ApiStatus.Internal diff --git a/API/src/main/java/net/juligames/core/api/message/MiniMessageSerializer.java b/API/src/main/java/net/juligames/core/api/message/MiniMessageSerializer.java index c34fd1ea..1fa43613 100644 --- a/API/src/main/java/net/juligames/core/api/message/MiniMessageSerializer.java +++ b/API/src/main/java/net/juligames/core/api/message/MiniMessageSerializer.java @@ -5,6 +5,7 @@ /** * This interface provides methods for serializing a MiniMessage to plain text or legacy format. * It also provides methods for translating legacy format messages to MiniMessage format. + * * @author Ture Bentzin * 25.12.2022 */ diff --git a/API/src/main/java/net/juligames/core/api/message/PatternType.java b/API/src/main/java/net/juligames/core/api/message/PatternType.java index dfe8bdc2..6c2f2af2 100644 --- a/API/src/main/java/net/juligames/core/api/message/PatternType.java +++ b/API/src/main/java/net/juligames/core/api/message/PatternType.java @@ -71,7 +71,7 @@ public enum PatternType { * Converts a pattern string to a tag string. * * @param target the target string to convert - * @param index the integer index to use in the tag + * @param index the integer index to use in the tag * @return the converted tag string */ public @NotNull String convertPatternToTag(@NotNull String target, int index) { diff --git a/API/src/main/java/net/juligames/core/api/misc/APIUtils.java b/API/src/main/java/net/juligames/core/api/misc/APIUtils.java index 79e6441f..9af23098 100644 --- a/API/src/main/java/net/juligames/core/api/misc/APIUtils.java +++ b/API/src/main/java/net/juligames/core/api/misc/APIUtils.java @@ -142,7 +142,8 @@ public static Optional executeAndReturnFirstSuccess(Supplier @NotNull for (Supplier supplier : suppliers) { try { return Optional.of(supplier.get()); - }catch (Exception ignore) {} + } catch (Exception ignore) { + } } return Optional.empty(); } diff --git a/API/src/main/java/net/juligames/core/api/misc/DurationFormatUtils.java b/API/src/main/java/net/juligames/core/api/misc/DurationFormatUtils.java index 0c568585..df83d4f9 100644 --- a/API/src/main/java/net/juligames/core/api/misc/DurationFormatUtils.java +++ b/API/src/main/java/net/juligames/core/api/misc/DurationFormatUtils.java @@ -77,6 +77,26 @@ public class DurationFormatUtils { static final @NotNull Object S = "S"; public static @NotNull String INTERNAL_MESSAGE_PREFIX = "internal.api.misc.format."; + static { + API.get().getAPILogger().info(DurationFormatUtils.class.getName() + " was loaded! Trying to register default messages:"); + long s1 = System.currentTimeMillis(); + try { + registerMessages(); + //BIT + final long between = s1 - System.currentTimeMillis(); + Duration duration = Duration.ofMillis(between); + String formatDurationWords = formatDurationWords(duration, false, false, null, + API.get().getMessageApi().defaultUtilLocale()); + API.get().getAPILogger().info("finished registration of default messages! (took: " + formatDurationWords + ")"); + } catch (Exception e) { + API.get().getAPILogger().warning("failed to register default messages: " + e); + ThrowableDebug.debug(e); + } + + } + + //----------------------------------------------------------------------- + /** *

DurationFormatUtils instances should NOT be constructed in standard programming.

* @@ -87,8 +107,6 @@ public DurationFormatUtils() { super(); } - //----------------------------------------------------------------------- - /** *

Formats the time gap as a string.

* @@ -244,24 +262,6 @@ public DurationFormatUtils() { suppressTrailingZeroElements, getLocalisationFromMessageSystem(locale, s)); } - static { - API.get().getAPILogger().info(DurationFormatUtils.class.getName() + " was loaded! Trying to register default messages:"); - long s1 = System.currentTimeMillis(); - try { - registerMessages(); - //BIT - final long between = s1 - System.currentTimeMillis(); - Duration duration = Duration.ofMillis(between); - String formatDurationWords = formatDurationWords(duration, false, false, null, - API.get().getMessageApi().defaultUtilLocale()); - API.get().getAPILogger().info("finished registration of default messages! (took: " + formatDurationWords + ")"); - }catch (Exception e){ - API.get().getAPILogger().warning("failed to register default messages: " + e); - ThrowableDebug.debug(e); - } - - } - public static void registerMessages() { registerDefaultMessage("days"); registerDefaultMessage("hours"); diff --git a/API/src/main/java/net/juligames/core/api/misc/EntryInterpretationUtil.java b/API/src/main/java/net/juligames/core/api/misc/EntryInterpretationUtil.java index e588d3d9..f5bf9c77 100644 --- a/API/src/main/java/net/juligames/core/api/misc/EntryInterpretationUtil.java +++ b/API/src/main/java/net/juligames/core/api/misc/EntryInterpretationUtil.java @@ -84,11 +84,11 @@ private EntryInterpretationUtil() { }).collect(Collectors.toUnmodifiableSet()); } - public static @Unmodifiable @NotNull Map interpretMap(@NotNull Map map, @NotNull Interpreter kInterpreter, @NotNull Interpreter vInterpreter) { + public static @Unmodifiable @NotNull Map interpretMap(@NotNull Map map, @NotNull Interpreter kInterpreter, @NotNull Interpreter vInterpreter) { return Map.ofEntries(interpretEntries(map.entrySet(), kInterpreter, vInterpreter).toArray((IntFunction[]>) value -> new Map.Entry[0])); } - public static @Unmodifiable @NotNull Map reverseMap(@NotNull Map map, @NotNull Interpreter kInterpreter, @NotNull Interpreter vInterpreter) { + public static @Unmodifiable @NotNull Map reverseMap(@NotNull Map map, @NotNull Interpreter kInterpreter, @NotNull Interpreter vInterpreter) { return Map.ofEntries(reverseEntries(map.entrySet(), kInterpreter, vInterpreter).toArray((IntFunction[]>) value -> new Map.Entry[0])); } diff --git a/API/src/main/java/net/juligames/core/api/misc/Predicates.java b/API/src/main/java/net/juligames/core/api/misc/Predicates.java index 3b77c89b..0f5fa0f0 100644 --- a/API/src/main/java/net/juligames/core/api/misc/Predicates.java +++ b/API/src/main/java/net/juligames/core/api/misc/Predicates.java @@ -9,9 +9,10 @@ /** * This class provides predicates - * @implNote might use {@link APIUtils#executedWithoutExceptionL(Runnable)} later + * * @author Ture Bentzin * 19.05.2023 + * @implNote might use {@link APIUtils#executedWithoutExceptionL(Runnable)} later */ public class Predicates { diff --git a/API/src/main/java/net/juligames/core/api/misc/ThrowableDebug.java b/API/src/main/java/net/juligames/core/api/misc/ThrowableDebug.java index e00d4c16..834d5e5c 100644 --- a/API/src/main/java/net/juligames/core/api/misc/ThrowableDebug.java +++ b/API/src/main/java/net/juligames/core/api/misc/ThrowableDebug.java @@ -1,7 +1,6 @@ package net.juligames.core.api.misc; import net.juligames.core.api.API; -import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import java.io.PrintWriter; diff --git a/API/src/main/java/net/juligames/core/api/misc/ThrowingRunnable.java b/API/src/main/java/net/juligames/core/api/misc/ThrowingRunnable.java index f6dba906..20966f71 100644 --- a/API/src/main/java/net/juligames/core/api/misc/ThrowingRunnable.java +++ b/API/src/main/java/net/juligames/core/api/misc/ThrowingRunnable.java @@ -5,6 +5,7 @@ /** * Like a normal {@link Runnable} but it accepts Exceptions + * * @author Ture Bentzin * 10.04.2023 */ diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/AdventureTagManager.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/AdventureTagManager.java index 703b2d8d..4b14ba28 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/AdventureTagManager.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/AdventureTagManager.java @@ -49,6 +49,7 @@ public interface AdventureTagManager extends MiniMessageSerializer { /** * This method creates a new {@link TagResolver} that combines {@link #getResolver()} and append + * * @param append additional resolvers * @return a new {@link TagResolver} */ diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/AudienceMessageRecipient.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/AudienceMessageRecipient.java index a9a6bf4d..abe93907 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/AudienceMessageRecipient.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/AudienceMessageRecipient.java @@ -6,7 +6,6 @@ import net.juligames.core.api.message.MessageRecipient; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.identity.Identity; -import net.kyori.adventure.pointer.Pointered; import net.kyori.adventure.text.Component; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/BackedPrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/BackedPrompt.java index d606484b..487b5ed9 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/BackedPrompt.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/BackedPrompt.java @@ -4,7 +4,6 @@ import de.bentzin.conversationlib.prompt.Prompt; import de.bentzin.conversationlib.prompt.ValidatingPrompt; import de.bentzin.tools.misc.SubscribableType; -import net.juligames.core.api.config.Interpreter; import net.juligames.core.api.config.PrimitiveInterpreter; import net.juligames.core.api.misc.APIUtils; import org.jetbrains.annotations.ApiStatus; diff --git a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/MapBackedPrompt.java b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/MapBackedPrompt.java index 2ca50ae9..aab9bc95 100644 --- a/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/MapBackedPrompt.java +++ b/AdventureAPI/src/main/java/net/juligames/core/adventure/api/prompt/MapBackedPrompt.java @@ -21,7 +21,7 @@ public abstract class MapBackedPrompt extends ValidatingPrompt { private final Map map; - public MapBackedPrompt(@NotNull Map map) { + public MapBackedPrompt(@NotNull Map map) { this.map = map; } diff --git a/AdventureCore/src/main/java/net/juligames/core/adventure/CoreAdventureTagManager.java b/AdventureCore/src/main/java/net/juligames/core/adventure/CoreAdventureTagManager.java index cbcab713..8dbdc869 100644 --- a/AdventureCore/src/main/java/net/juligames/core/adventure/CoreAdventureTagManager.java +++ b/AdventureCore/src/main/java/net/juligames/core/adventure/CoreAdventureTagManager.java @@ -5,7 +5,6 @@ import net.juligames.core.api.jdbi.DBReplacement; import net.juligames.core.api.jdbi.ReplacementDAO; import net.juligames.core.api.message.Message; -import net.juligames.core.api.message.MiniMessageSerializer; import net.juligames.core.api.message.PatternType; import net.juligames.core.api.message.TagManager; import net.kyori.adventure.text.Component; diff --git a/Core/src/main/java/net/juligames/core/Core.java b/Core/src/main/java/net/juligames/core/Core.java index 2cf0d0fc..aef0bde2 100644 --- a/Core/src/main/java/net/juligames/core/Core.java +++ b/Core/src/main/java/net/juligames/core/Core.java @@ -173,14 +173,13 @@ public void start(String core_name, @NotNull Logger logger, boolean member) { .addMessageListener(coreNotificationApi); - if(getHazelDataApi().isMasterInformationAvailable()) - { + if (getHazelDataApi().isMasterInformationAvailable()) { if (!Boolean.getBoolean("acknowledgeUnsafeMasterCheck")) { coreLogger.info("checking compatibility with master.."); final String masterVersion = getHazelDataApi().getMasterInformation().get("master_version"); - if(masterVersion == null) { + if (masterVersion == null) { coreLogger.error("Flawed data! Please check if hazelcast is working correctly and if your master" + - " is operating normal! If you see this message on your Master, you should get in touch with me at " + + " is operating normal! If you see this message on your Master, you should get in touch with me at " + "mailto://bentzin@tdrstudios.de! Thank you for using JuliGamesCore. It is likely that your JuliGamesCore Cluster " + "starts but you should expect severe issues after reading this message!"); } @@ -196,8 +195,8 @@ public void start(String core_name, @NotNull Logger logger, boolean member) { coreLogger.warning("********************************************************"); } } - } - else logger.debug("master information is not available! If you see this on the Master it is expected behavior"); + } else + logger.debug("master information is not available! If you see this on the Master it is expected behavior"); logger.info("hooking to shutdown..."); getJavaRuntime().addShutdownHook(new Thread(() -> { diff --git a/Core/src/main/java/net/juligames/core/hcast/HazelConnector.java b/Core/src/main/java/net/juligames/core/hcast/HazelConnector.java index dc291539..dbf1a38d 100644 --- a/Core/src/main/java/net/juligames/core/hcast/HazelConnector.java +++ b/Core/src/main/java/net/juligames/core/hcast/HazelConnector.java @@ -70,6 +70,7 @@ public void disconnect() { /** * This method acts like {@link #disconnect()} but cant throw an {@link Exception} and does not wait for population of * the {@link #instance} field! + * * @return an Optional that might contain an {@link Exception} that was thrown while trying to kill hazelcast */ @ApiStatus.Internal @@ -79,7 +80,7 @@ public void disconnect() { Objects.requireNonNull(instance.getNow(null), "cant kill instance! Your cluster might be bricked now...") .shutdown(); return Optional.empty(); - }catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); //print but do not propagate! return Optional.of(e); } @@ -99,6 +100,7 @@ public HazelcastInstance getForce() { * Get the configured {@link #clientName}. * This represents a memberName if this {@link HazelConnector} is used for members (masters) or a real clientName if it is * used for creating members + * * @return the clientName */ protected @NotNull String getClientName() { diff --git a/HazelAPI/src/main/java/net/juligames/core/api/hazel/NativeHazelDataAPI.java b/HazelAPI/src/main/java/net/juligames/core/api/hazel/NativeHazelDataAPI.java index 065d33a4..46adf8f4 100644 --- a/HazelAPI/src/main/java/net/juligames/core/api/hazel/NativeHazelDataAPI.java +++ b/HazelAPI/src/main/java/net/juligames/core/api/hazel/NativeHazelDataAPI.java @@ -74,11 +74,12 @@ public interface NativeHazelDataAPI { * This method can be used to automatically determine the type of hazel! * The implementation might be changed over a version. * This one should not be used outside user interface applications - * @apiNote The implementation currently uses {@link #getAll()} and {@link java.util.function.Predicate}s to - * determine what will be returned. + * * @param hazel hazel + * @param the implementation of {@link DistributedObject} * @return the optional that may contain a {@link DistributedObject} - * @param the implementation of {@link DistributedObject} + * @apiNote The implementation currently uses {@link #getAll()} and {@link java.util.function.Predicate}s to + * determine what will be returned. */ @ApiStatus.AvailableSince("1.6") Optional get(@NotNull String hazel); diff --git a/Master/dependency-reduced-pom.xml b/Master/dependency-reduced-pom.xml index ba2c20fc..e15127da 100644 --- a/Master/dependency-reduced-pom.xml +++ b/Master/dependency-reduced-pom.xml @@ -1,44 +1,45 @@ - - - JuliGamesCore - net.juligames.core - 1.6 - - 4.0.0 - Master - - - - maven-shade-plugin - 3.4.1 - - - package - - shade - - - - - - - maven-jar-plugin - 3.3.0 - - - - true - net.juligames.core.master.CoreMaster - - - - - - - - 17 - 17 - UTF-8 - + + + JuliGamesCore + net.juligames.core + 1.6 + + 4.0.0 + Master + + + + maven-shade-plugin + 3.4.1 + + + package + + shade + + + + + + + maven-jar-plugin + 3.3.0 + + + + true + net.juligames.core.master.CoreMaster + + + + + + + + 17 + 17 + UTF-8 + diff --git a/Master/src/main/java/net/juligames/core/master/cmd/PrintMapCommand.java b/Master/src/main/java/net/juligames/core/master/cmd/PrintMapCommand.java index 8a7b7e99..849ac93c 100644 --- a/Master/src/main/java/net/juligames/core/master/cmd/PrintMapCommand.java +++ b/Master/src/main/java/net/juligames/core/master/cmd/PrintMapCommand.java @@ -5,7 +5,6 @@ import de.bentzin.tools.logging.Logger; import net.juligames.core.Core; import net.juligames.core.api.TODO; -import net.juligames.core.api.misc.APIUtils; import org.jetbrains.annotations.NotNull; import java.util.Optional; @@ -13,7 +12,6 @@ import java.util.function.Predicate; import static net.juligames.core.api.misc.APIUtils.executeAndReturnFirstSuccess; -import static net.juligames.core.api.misc.APIUtils.executeAndSwallow; /** * @author Ture Bentzin @@ -59,9 +57,9 @@ public void executeCommand(@NotNull String commandString) { protected IMap findMap(String query) { return (IMap) executeAndReturnFirstSuccess( //Equal names - () -> findMapHard(query,distributedObject -> distributedObject.getName().equals(query)), + () -> findMapHard(query, distributedObject -> distributedObject.getName().equals(query)), //Semi Equal names - () -> findMapHard(query,distributedObject -> distributedObject.getName().equalsIgnoreCase(query)), + () -> findMapHard(query, distributedObject -> distributedObject.getName().equalsIgnoreCase(query)), //Starts with () -> findMapHard(query, distributedObject -> distributedObject.getName().startsWith(query)), //Starts with (semi) @@ -83,6 +81,6 @@ protected IMap findMap(String query) { if (optionalDistributedObject.isEmpty()) { throw new IllegalArgumentException("cant find: " + name); } - return (IMap)optionalDistributedObject.get(); + return (IMap) optionalDistributedObject.get(); } } diff --git a/Master/src/main/java/net/juligames/core/master/logging/MasterLogger.java b/Master/src/main/java/net/juligames/core/master/logging/MasterLogger.java index 943c39dc..70661d35 100644 --- a/Master/src/main/java/net/juligames/core/master/logging/MasterLogger.java +++ b/Master/src/main/java/net/juligames/core/master/logging/MasterLogger.java @@ -14,11 +14,6 @@ */ public final class MasterLogger extends JavaLogger { - @ApiStatus.AvailableSince("1.6") - public static void setupJavaLogging() { - System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tF %1$tT] [%4$-7s] %5$s %n"); - } - public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(" HH:mm:ss"); public MasterLogger(String name, @NotNull Logger parent, java.util.logging.@NotNull Logger logger) { @@ -31,6 +26,11 @@ public MasterLogger(String name, java.util.logging.@NotNull Logger logger) { logger.addHandler(LogFileHandlerManager.generateFileHandler()); } + @ApiStatus.AvailableSince("1.6") + public static void setupJavaLogging() { + System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tF %1$tT] [%4$-7s] %5$s %n"); + } + @Override public void log(String message, @NotNull LogLevel logLevel) { super.log(timeAndDate(message), logLevel); diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/PaperConversationManager.java b/PaperAPI/src/main/java/net/juligames/core/paper/PaperConversationManager.java index 890dc99f..3028199b 100644 --- a/PaperAPI/src/main/java/net/juligames/core/paper/PaperConversationManager.java +++ b/PaperAPI/src/main/java/net/juligames/core/paper/PaperConversationManager.java @@ -12,25 +12,25 @@ * 25.03.2023 */ public class PaperConversationManager extends ConversationManager { - + private static PaperConversationManager instance; - public static PaperConversationManager getInstance() { - return instance; - } - public PaperConversationManager(@NotNull Map audienceConverserMap) { super(audienceConverserMap); - if(instance != null) { + if (instance != null) { throw new IllegalStateException("instance is already present!"); } instance = this; } public PaperConversationManager() { - if(instance != null) { + if (instance != null) { throw new IllegalStateException("instance is already present!"); } instance = this; } + + public static PaperConversationManager getInstance() { + return instance; + } } \ No newline at end of file diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/PaperMessageRecipient.java b/PaperAPI/src/main/java/net/juligames/core/paper/PaperMessageRecipient.java index a349e2c7..011bf8e1 100644 --- a/PaperAPI/src/main/java/net/juligames/core/paper/PaperMessageRecipient.java +++ b/PaperAPI/src/main/java/net/juligames/core/paper/PaperMessageRecipient.java @@ -12,6 +12,7 @@ /** * Represents a message recipient on a Paper server, which is capable of receiving messages * through the Bukkit {@link CommandSender} interface. + * * @author Ture Bentzin * 19.11.2022 */ @@ -21,6 +22,7 @@ public class PaperMessageRecipient implements MessageRecipient { /** * Constructs a new {@code PaperMessageRecipient} with the specified {@link CommandSender}. + * * @param commandSender the Bukkit {@link CommandSender} for this recipient */ public PaperMessageRecipient(CommandSender commandSender) { @@ -29,6 +31,7 @@ public PaperMessageRecipient(CommandSender commandSender) { /** * Returns a human-readable name that defines this recipient. + * * @return the name of this recipient, which is equivalent to the name of the Bukkit {@link CommandSender} */ @Override @@ -38,6 +41,7 @@ public PaperMessageRecipient(CommandSender commandSender) { /** * Delivers a message to this recipient using the Adventure API. + * * @param message the {@link Message} to be delivered */ @Override @@ -47,6 +51,7 @@ public void deliver(@NotNull Message message) { /** * Delivers a miniMessage string to this recipient using the Adventure API. + * * @param miniMessage the miniMessage to be delivered to the Bukkit {@link CommandSender} */ @Override @@ -57,6 +62,7 @@ public void deliver(@NotNull String miniMessage) { /** * Returns the locale of the player associated with this recipient, if applicable. + * * @return the locale string of the player, or {@code null} if the recipient is not a player */ @Override diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/inventory/InventoryConfigWriter.java b/PaperAPI/src/main/java/net/juligames/core/paper/inventory/InventoryConfigWriter.java index c1cbaea5..a35ba2ca 100644 --- a/PaperAPI/src/main/java/net/juligames/core/paper/inventory/InventoryConfigWriter.java +++ b/PaperAPI/src/main/java/net/juligames/core/paper/inventory/InventoryConfigWriter.java @@ -31,8 +31,8 @@ public record InventoryConfigWriter(Inventory inventory) implements ConfigWriter * Populates an inventory with items from the given configuration. * * @param configuration the configuration to read items from - * @param keyspace the keyspace in the configuration to read items from - * @param inventory the inventory to populate + * @param keyspace the keyspace in the configuration to read items from + * @param inventory the inventory to populate */ public static void populateInventory(@NotNull Configuration configuration, @NotNull String keyspace, @NotNull Inventory inventory) { Collection collection = configuration.getCollection(keyspace, itemStackInterpreter); @@ -44,8 +44,8 @@ public static void populateInventory(@NotNull Configuration configuration, @NotN *

* * @param configuration the configuration to read items from - * @param keyspace the keyspace in the configuration to read items from - * @param inventory the inventory to populate + * @param keyspace the keyspace in the configuration to read items from + * @param inventory the inventory to populate * @return the populated inventory */ @ApiStatus.Experimental @@ -59,7 +59,7 @@ public static void populateInventory(@NotNull Configuration configuration, @NotN * Writes the inventory to the given configuration. * * @param configuration the configuration to write the inventory to - * @param keyspace the keyspace in the configuration to write the inventory to + * @param keyspace the keyspace in the configuration to write the inventory to */ @Override public void write(@NotNull Configuration configuration, @NotNull String keyspace) { diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/ObjectifiedConfiguration.java b/PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/ObjectifiedConfiguration.java index b5548233..db805879 100644 --- a/PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/ObjectifiedConfiguration.java +++ b/PaperAPI/src/main/java/net/juligames/core/paper/misc/configmapping/ObjectifiedConfiguration.java @@ -148,7 +148,6 @@ public ObjectifiedConfiguration(@NotNull Representation se } - public final @NotNull ConfigurationSection getAssociatedSection() { return associatedSection; } diff --git a/PaperAPI/src/main/java/net/juligames/core/paper/prompt/MaterialPrompt.java b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/MaterialPrompt.java index 0f7097db..ccec998b 100644 --- a/PaperAPI/src/main/java/net/juligames/core/paper/prompt/MaterialPrompt.java +++ b/PaperAPI/src/main/java/net/juligames/core/paper/prompt/MaterialPrompt.java @@ -4,7 +4,6 @@ import de.bentzin.conversationlib.prompt.Prompt; import de.bentzin.conversationlib.prompt.ValidatingPrompt; import org.bukkit.Material; -import org.bukkit.map.MapPalette; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/PaperCore/dependency-reduced-pom.xml b/PaperCore/dependency-reduced-pom.xml index 5a4833ac..7b5ba6d8 100644 --- a/PaperCore/dependency-reduced-pom.xml +++ b/PaperCore/dependency-reduced-pom.xml @@ -1,54 +1,55 @@ - - - JuliGamesCore - net.juligames.core - 1.6 - - 4.0.0 - PaperCore - - - - true - src/main/resources - - - - - maven-shade-plugin - 3.4.1 - - - package - - shade - - - - - false - - - - - - - papermc - https://repo.papermc.io/repository/maven-public/ - - - - - io.papermc.paper - paper-api - 1.18.2-R0.1-SNAPSHOT - provided - - - - 17 - 17 - UTF-8 - + + + JuliGamesCore + net.juligames.core + 1.6 + + 4.0.0 + PaperCore + + + + true + src/main/resources + + + + + maven-shade-plugin + 3.4.1 + + + package + + shade + + + + + false + + + + + + + papermc + https://repo.papermc.io/repository/maven-public/ + + + + + io.papermc.paper + paper-api + 1.18.2-R0.1-SNAPSHOT + provided + + + + 17 + 17 + UTF-8 + diff --git a/PaperCore/src/main/java/net/juligames/core/paper/PaperCorePlugin.java b/PaperCore/src/main/java/net/juligames/core/paper/PaperCorePlugin.java index 3a4b8a13..a17952dc 100644 --- a/PaperCore/src/main/java/net/juligames/core/paper/PaperCorePlugin.java +++ b/PaperCore/src/main/java/net/juligames/core/paper/PaperCorePlugin.java @@ -8,7 +8,6 @@ import net.juligames.core.api.jdbi.MessageDAO; import net.juligames.core.api.minigame.BasicMiniGame; import net.juligames.core.caching.MessageCaching; -import net.juligames.core.command.CoreCommandNotificationListener; import net.juligames.core.paper.bstats.Metrics; import net.juligames.core.paper.conversation.ConversationListener; import net.juligames.core.paper.events.ServerBootFinishedEvent; diff --git a/PaperCore/src/main/java/net/juligames/core/paper/conversation/ConversationListener.java b/PaperCore/src/main/java/net/juligames/core/paper/conversation/ConversationListener.java index 6a1a5f73..e3a44c90 100644 --- a/PaperCore/src/main/java/net/juligames/core/paper/conversation/ConversationListener.java +++ b/PaperCore/src/main/java/net/juligames/core/paper/conversation/ConversationListener.java @@ -1,7 +1,6 @@ package net.juligames.core.paper.conversation; import net.juligames.core.Core; -import net.juligames.core.api.API; import net.juligames.core.paper.PaperConversationManager; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; @@ -28,7 +27,7 @@ public void onChat(@NotNull AsyncPlayerChatEvent event) { @EventHandler public void onCommand(@NotNull ServerCommandEvent serverCommandEvent) { if (PaperConversationManager.getInstance().handleInput(serverCommandEvent.getSender(), - serverCommandEvent.getCommand())){ + serverCommandEvent.getCommand())) { serverCommandEvent.setCancelled(true); } } diff --git a/SuperCore/pom.xml b/SuperCore/pom.xml index 0610287d..853cac7a 100644 --- a/SuperCore/pom.xml +++ b/SuperCore/pom.xml @@ -1,6 +1,6 @@ - 4.0.0 diff --git a/VelocityCore/dependency-reduced-pom.xml b/VelocityCore/dependency-reduced-pom.xml index b4552eb7..44cd80c5 100644 --- a/VelocityCore/dependency-reduced-pom.xml +++ b/VelocityCore/dependency-reduced-pom.xml @@ -1,54 +1,55 @@ - - - JuliGamesCore - net.juligames.core - 1.6 - - 4.0.0 - VelocityCore - - - - maven-shade-plugin - 3.4.1 - - - package - - shade - - - - - false - - - - - - - papermc - papermc - https://repo.papermc.io/repository/maven-public/ - - - juligames-juligames - Juligames Maven - https://maven.juligames.net/juligames - - - - - com.velocitypowered - velocity-api - 3.1.1 - provided - - - - 17 - 17 - UTF-8 - + + + JuliGamesCore + net.juligames.core + 1.6 + + 4.0.0 + VelocityCore + + + + maven-shade-plugin + 3.4.1 + + + package + + shade + + + + + false + + + + + + + papermc + papermc + https://repo.papermc.io/repository/maven-public/ + + + juligames-juligames + Juligames Maven + https://maven.juligames.net/juligames + + + + + com.velocitypowered + velocity-api + 3.1.1 + provided + + + + 17 + 17 + UTF-8 +