From 5755368ffea5f83eff323f2d7f6b418d70e42149 Mon Sep 17 00:00:00 2001 From: Zach Levis Date: Tue, 13 Oct 2020 18:03:23 -0700 Subject: [PATCH] Update for configurate 4 and API changes --- SpongeAPI | 2 +- build.gradle.kts | 27 +- .../common/command/SpongeCommandFactory.java | 2 +- .../provider/PluginConfigurationModule.java | 4 +- .../config/common/BrokenModCategory.java | 8 +- .../config/common/BungeeCordCategory.java | 8 +- .../config/common/CommandsCategory.java | 35 +-- .../config/common/CommandsHiddenCategory.java | 21 +- .../applaunch/config/common/CommonConfig.java | 24 +- .../config/common/DebugCategory.java | 16 +- .../config/common/EigenRedstoneCategory.java | 14 +- .../config/common/ExploitCategory.java | 47 ++-- .../config/common/GeneralCategory.java | 38 +-- .../config/common/ModuleCategory.java | 48 ++-- .../config/common/OptimizationCategory.java | 121 ++++---- .../config/common/PermissionCategory.java | 8 +- .../config/common/PhaseTrackerCategory.java | 100 ++++--- .../config/common/ServicesCategory.java | 54 ++-- .../applaunch/config/common/SqlCategory.java | 8 +- .../config/common/StructureModCategory.java | 13 +- .../config/common/StructureSaveCategory.java | 32 ++- .../config/common/TeleportHelperCategory.java | 24 +- .../config/common/TimingsCategory.java | 12 +- .../config/common/WorldCategory.java | 17 +- .../common/applaunch/config/core/Config.java | 19 +- .../applaunch/config/core/ConfigHandle.java | 108 +++---- .../config/core/DuplicateRemovalVisitor.java | 38 +-- ...FileMovingConfigurationTransformation.java | 49 ++-- .../config/core/InheritableConfigHandle.java | 20 +- .../applaunch/config/core/SpongeConfigs.java | 28 +- .../config/core/TokenHoldingString.java | 9 +- .../config/inheritable/BaseConfig.java | 33 ++- .../BlockEntityActivationCategory.java | 18 +- .../BlockEntityActivationModCategory.java | 22 +- .../inheritable/CollisionModCategory.java | 21 +- .../EntityActivationModCategory.java | 12 +- .../EntityActivationRangeCategory.java | 14 +- .../config/inheritable/EntityCategory.java | 51 ++-- .../inheritable/EntityCollisionCategory.java | 20 +- .../config/inheritable/GlobalConfig.java | 51 ++-- .../config/inheritable/LoggingCategory.java | 81 +++--- .../inheritable/MovementChecksCategory.java | 14 +- .../inheritable/PlayerBlockTracker.java | 15 +- .../config/inheritable/SpawnerCategory.java | 30 +- .../config/inheritable/WorldCategory.java | 116 ++++---- .../spongepowered/common/SpongeCommon.java | 22 +- .../org/spongepowered/common/SpongeGame.java | 11 +- .../spongepowered/common/SpongeLifecycle.java | 11 +- .../common/advancement/SpongeTrigger.java | 13 +- .../advancement/SpongeTriggerBuilder.java | 97 +++++-- .../common/adventure/SpongeAdventure.java | 2 +- .../context/SpongeCommandContextBuilder.java | 3 +- .../command/manager/SpongeCommandManager.java | 2 +- .../command/parameter/SpongeParameterKey.java | 33 ++- .../parameter/SpongeParameterKeyBuilder.java | 9 +- .../SpongeParameterValueBuilder.java | 6 +- .../SpongeParameterValueFactory.java | 6 +- .../registrar/BrigadierCommandRegistrar.java | 2 +- .../SpongeParameterizedCommandRegistrar.java | 4 +- .../registrar/SpongeRawCommandRegistrar.java | 4 +- .../common/command/sponge/SpongeCommand.java | 8 +- .../config/CatalogTypeTypeSerializer.java | 39 ++- .../DataSerializableTypeSerializer.java | 48 ++-- .../common/config/PluginConfigManager.java | 75 +++-- .../common/config/PluginConfigRoot.java | 34 +-- .../common/config/SpongeGameConfigs.java | 8 +- .../config/customdata/CustomDataConfig.java | 8 +- .../CustomDataRegistrationCategory.java | 61 ++-- .../config/metrics/MetricsConfiguration.java | 25 +- .../tracker/BlockEntityTrackerCategory.java | 10 +- .../BlockEntityTrackerModCategory.java | 27 +- .../config/tracker/BlockTrackerCategory.java | 12 +- .../tracker/BlockTrackerModCategory.java | 23 +- .../config/tracker/EntityTrackerCategory.java | 11 +- .../tracker/EntityTrackerModCategory.java | 28 +- .../common/config/tracker/TrackerConfig.java | 2 +- .../common/data/SpongeDataManager.java | 24 +- .../common/data/SpongeDataRegistration.java | 27 +- .../data/SpongeDataRegistrationBuilder.java | 9 +- .../data/SpongeKeyValueMatcherBuilder.java | 5 +- .../common/data/key/SpongeKey.java | 22 +- .../common/data/key/SpongeKeyBuilder.java | 46 ++- .../persistence/ConfigurateTranslator.java | 54 ++-- .../data/persistence/DataSerializers.java | 58 ++-- .../DataTranslatorTypeSerializer.java | 28 +- .../data/persistence/HoconDataFormat.java | 29 +- .../data/persistence/NbtTranslator.java | 4 +- .../data/persistence/SpongeDataStore.java | 12 +- .../persistence/SpongeDataStoreBuilder.java | 70 +++-- .../provider/DataProviderRegistrator.java | 39 ++- .../GenericImmutableDataProviderBase.java | 8 +- .../GenericMutableDataProviderBase.java | 8 +- .../data/value/ValueConstructorFactory.java | 7 +- .../spongepowered/common/event/EventType.java | 15 +- .../common/event/ListenerChecker.java | 32 ++- .../common/event/SpongeEventContextKey.java | 32 ++- .../event/SpongeEventContextKeyBuilder.java | 19 +- .../common/event/SpongeEventManager.java | 63 +++-- .../AbstractEngineLifecycleEvent.java | 2 +- .../ProvideEngineServiceEventImpl.java | 2 +- .../lifecycle/ProvideServiceEventImpl.java | 2 +- .../lifecycle/RegisterCatalogEventImpl.java | 2 +- .../lifecycle/RegisterCommandEventImpl.java | 2 +- .../lifecycle/StartedEngineEventImpl.java | 2 +- .../lifecycle/StartingEngineEventImpl.java | 2 +- .../lifecycle/StoppingEngineEventImpl.java | 2 +- .../common/inject/InjectionPointProvider.java | 7 +- .../common/inject/SpongeCommonModule.java | 1 - .../common/inject/SpongeInjectionPoint.java | 12 +- .../common/inject/plugin/PluginModule.java | 4 + .../provider/PluginConfigurationModule.java | 263 ++++++++++++++++-- .../plugin/PluginContainerExtension.java | 33 --- .../registry/SpongeCatalogRegistry.java | 7 +- .../EventContextKeyStreamGenerator.java | 107 ++++--- .../builtin/sponge/KeyStreamGenerator.java | 2 +- .../co/aikar/timings/TimingsExport.java | 16 +- .../common/service/SpongeServiceProvider.java | 2 +- .../game/SpongeGameScopedServiceProvider.java | 4 +- .../game/pagination/PaginationCalculator.java | 36 +-- .../SpongeServerScopedServiceProvider.java | 4 +- .../SpongeStatisticCategoryType.java | 2 +- .../org/spongepowered/common/util/IpSet.java | 16 +- .../util/SpongeMetricsConfigManager.java | 6 +- .../common/util/TypeTokenHelper.java | 58 +++- .../common/util/UsernameCache.java | 2 +- .../common/world/server/WorldMigrator.java | 17 +- .../ICriterionTrigger_ListenerMixin.java | 4 +- .../data/manipulator/ManipulatorTest.java | 2 +- .../common/util/TypeTokenHelperTest.java | 256 ----------------- .../core/DuplicateRemovalVisitorTest.java | 216 +++++++------- .../persistence/ConfigurateDataViewTest.java | 53 ++-- .../common/util/ReflectionTest.java | 50 ++-- .../common/util/TypeTokenHelperTest.java | 164 +++++++++++ .../test/commandtest/CommandTestPlugin.java | 18 +- .../test/configtest/ConfigTest.java | 32 +-- .../test/configtest/ExampleConfiguration.java | 4 +- .../test/customdatatest/CustomDataTest.java | 12 +- .../handler/AbstractVanillaLaunchHandler.java | 23 +- 138 files changed, 2354 insertions(+), 1802 deletions(-) delete mode 100644 src/main/java/org/spongepowered/common/plugin/PluginContainerExtension.java delete mode 100644 src/test/invalid/common/util/TypeTokenHelperTest.java rename src/test/{invalid => java/org/spongepowered}/common/util/ReflectionTest.java (78%) create mode 100644 src/test/java/org/spongepowered/common/util/TypeTokenHelperTest.java diff --git a/SpongeAPI b/SpongeAPI index 9c58e76ad03..81ee7c63eb1 160000 --- a/SpongeAPI +++ b/SpongeAPI @@ -1 +1 @@ -Subproject commit 9c58e76ad03a2f21fc2e255e3ac511dab7ec4c2b +Subproject commit 81ee7c63eb1e229dd1ca79b98564b6d65048ddf8 diff --git a/build.gradle.kts b/build.gradle.kts index e960451c9a1..54c5f6f4a16 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -212,7 +212,7 @@ dependencies { implementation("org.ow2.asm:asm-tree:$asmVersion") // Implementation-only Adventure - implementation("net.kyori:adventure-serializer-configurate3:4.1.1") + implementation("net.kyori:adventure-serializer-configurate4:4.2.0-SNAPSHOT") annotationProcessor("org.spongepowered:mixin:$mixinVersion:processor") @@ -239,19 +239,16 @@ dependencies { applaunchConfig("org.spongepowered:plugin-spi:$pluginSpiVersion") applaunchConfig("org.apache.logging.log4j:log4j-api:2.11.2") applaunchConfig("com.google.guava:guava:$guavaVersion") - applaunchConfig("org.spongepowered:configurate-core:3.7.1") { - exclude(group = "com.google.inject", module = "guice") - exclude(group = "com.google.guava", module = "guava") + applaunchConfig(platform("org.spongepowered:configurate-bom:4.0.0-SNAPSHOT")) + applaunchConfig("org.spongepowered:configurate-core") { exclude(group = "org.checkerframework", module = "checker-qual") // We use our own version } - applaunchConfig("org.spongepowered:configurate-hocon:3.7.1") { + applaunchConfig("org.spongepowered:configurate-hocon") { exclude(group = "org.spongepowered", module = "configurate-core") - exclude(group = "com.google.guava", module = "guava") exclude(group = "org.checkerframework", module = "checker-qual") // We use our own version } - applaunchConfig("org.spongepowered:configurate-json:3.7.1") { + applaunchConfig("org.spongepowered:configurate-jackson") { exclude(group = "org.spongepowered", module = "configurate-core") - exclude(group = "com.google.guava", module = "guava") exclude(group = "org.checkerframework", module = "checker-qual") // We use our own version } applaunchConfig("org.apache.logging.log4j:log4j-core:2.11.2") @@ -563,6 +560,7 @@ project("SpongeVanilla") { add(vanillaLaunch.implementationConfigurationName, vanillaMinecraftConfig) vanillaInstallerConfig("com.google.code.gson:gson:2.8.0") + vanillaInstallerConfig("org.spongepowered:configurate-hocon:4.0.0-SNAPSHOT") vanillaInstallerConfig("net.sf.jopt-simple:jopt-simple:5.0.3") vanillaInstallerConfig("org.apache.logging.log4j:log4j-api:2.11.2") vanillaInstallerConfig("org.apache.logging.log4j:log4j-core:2.11.2") @@ -571,7 +569,7 @@ project("SpongeVanilla") { vanillaInstallerImplementation(vanillaInstallerConfig) vanillaAppLaunchConfig(project(":SpongeAPI")) - vanillaAppLaunchConfig("net.kyori:adventure-serializer-configurate3:4.1.1") + vanillaAppLaunchConfig("net.kyori:adventure-serializer-configurate4:4.2.0-SNAPSHOT") vanillaAppLaunchConfig("org.spongepowered:mixin:$mixinVersion") vanillaAppLaunchConfig("org.ow2.asm:asm-util:$asmVersion") vanillaAppLaunchConfig("org.ow2.asm:asm-tree:$asmVersion") @@ -582,19 +580,16 @@ project("SpongeVanilla") { vanillaAppLaunchConfig("org.apache.logging.log4j:log4j-core:2.11.2") vanillaAppLaunchConfig("com.zaxxer:HikariCP:2.6.3") vanillaAppLaunchConfig("org.apache.logging.log4j:log4j-slf4j-impl:2.11.2") - vanillaAppLaunchConfig("org.spongepowered:configurate-core:3.7.1") { - exclude(group = "com.google.guava", module = "guava") - exclude(group = "com.google.inject", module = "guice") + vanillaAppLaunchConfig(platform("org.spongepowered:configurate-bom:4.0.0-SNAPSHOT")) + vanillaAppLaunchConfig("org.spongepowered:configurate-core") { exclude(group = "org.checkerframework", module = "checker-qual") } - vanillaAppLaunchConfig("org.spongepowered:configurate-hocon:3.7.1") { + vanillaAppLaunchConfig("org.spongepowered:configurate-hocon") { exclude(group = "org.spongepowered", module = "configurate-core") - exclude(group = "com.google.guava", module = "guava") exclude(group = "org.checkerframework", module = "checker-qual") } - vanillaAppLaunchConfig("org.spongepowered:configurate-json:3.7.1") { + vanillaAppLaunchConfig("org.spongepowered:configurate-jackson") { exclude(group = "org.spongepowered", module = "configurate-core") - exclude(group = "com.google.guava", module = "guava") exclude(group = "org.checkerframework", module = "checker-qual") } diff --git a/invalid/main/java/org/spongepowered/common/command/SpongeCommandFactory.java b/invalid/main/java/org/spongepowered/common/command/SpongeCommandFactory.java index 7dba97aeef8..134f1a0199d 100644 --- a/invalid/main/java/org/spongepowered/common/command/SpongeCommandFactory.java +++ b/invalid/main/java/org/spongepowered/common/command/SpongeCommandFactory.java @@ -54,7 +54,7 @@ import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.server.ServerWorld; -import ninja.leaping.configurate.commented.CommentedConfigurationNode; +import org.spongepowered.configurate.CommentedConfigurationNode; import org.spongepowered.api.Sponge; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.command.Command; diff --git a/invalid/main/java/org/spongepowered/common/inject/provider/PluginConfigurationModule.java b/invalid/main/java/org/spongepowered/common/inject/provider/PluginConfigurationModule.java index d56970ad8c2..d49b74642f1 100644 --- a/invalid/main/java/org/spongepowered/common/inject/provider/PluginConfigurationModule.java +++ b/invalid/main/java/org/spongepowered/common/inject/provider/PluginConfigurationModule.java @@ -27,8 +27,8 @@ import com.google.inject.AbstractModule; import com.google.inject.Provider; import com.google.inject.TypeLiteral; -import ninja.leaping.configurate.commented.CommentedConfigurationNode; -import ninja.leaping.configurate.loader.ConfigurationLoader; +import org.spongepowered.configurate.CommentedConfigurationNode; +import org.spongepowered.configurate.loader.ConfigurationLoader; import org.spongepowered.api.config.ConfigDir; import org.spongepowered.api.config.DefaultConfig; import org.spongepowered.api.plugin.PluginContainer; diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/BrokenModCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/BrokenModCategory.java index 10bf1f41cff..68974bb8233 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/BrokenModCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/BrokenModCategory.java @@ -24,8 +24,9 @@ */ package org.spongepowered.common.applaunch.config.common; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; import java.util.ArrayList; import java.util.List; @@ -33,7 +34,8 @@ @ConfigSerializable public class BrokenModCategory { - @Setting(value = "broken-network-handler-mods", comment = "A list of mod ids that have broken network handlers (they interact with the game from a Netty handler thread).\n" + @Setting("broken-network-handler-mods") + @Comment("A list of mod ids that have broken network handlers (they interact with the game from a Netty handler thread).\n" + "All network handlers from a forcibly scheduled to run on the main thread.\n" + "Note that this setting should be considered a last resort, and should only be used as a stopgap measure while waiting for a mod to properly fix the issue.") private List brokenNetworkHandlerMods = new ArrayList<>(); diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/BungeeCordCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/BungeeCordCategory.java index fbfce93d941..0601ad323f9 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/BungeeCordCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/BungeeCordCategory.java @@ -24,13 +24,15 @@ */ package org.spongepowered.common.applaunch.config.common; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; @ConfigSerializable public class BungeeCordCategory { - @Setting(value = "ip-forwarding", comment = "If 'true', allows BungeeCord to forward IP address, UUID, and Game Profile to this server.") + @Setting(value = "ip-forwarding") + @Comment("If 'true', allows BungeeCord to forward IP address, UUID, and Game Profile to this server.") private boolean ipForwarding = false; public boolean getIpForwarding() { diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/CommandsCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/CommandsCategory.java index df169b693cc..94b69f64411 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/CommandsCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/CommandsCategory.java @@ -24,8 +24,9 @@ */ package org.spongepowered.common.applaunch.config.common; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; import java.util.HashMap; import java.util.Map; @@ -33,28 +34,30 @@ @ConfigSerializable public class CommandsCategory { - @Setting(comment = "Command aliases will resolve conflicts when multiple plugins request a specific command, \n" + @Setting + @Comment("Command aliases will resolve conflicts when multiple plugins request a specific command, \n" + "Correct syntax is = e.g. \"sethome=homeplugin\"") private Map aliases = new HashMap<>(); - @Setting(value = "enforce-permission-checks-on-non-sponge-commands", - comment = "Some mods may not trigger a permission check when running their command. Setting this to\n" - + "true will enforce a check of the Sponge provided permission (\".command.\").\n" - + "Note that setting this to true may cause some commands that are generally accessible to all to\n" - + "require a permission to run.\n\n" - + "Setting this to true will enable greater control over whether a command will appear in\n" - + "tab completion and Sponge's help command.\n\n" - + "If you are not using a permissions plugin, it is highly recommended that this is set to false\n" - + "(as it is by default).") + @Setting + @Comment("Some mods may not trigger a permission check when running their command. Setting this to\n" + + "true will enforce a check of the Sponge provided permission (\".command.\").\n" + + "Note that setting this to true may cause some commands that are generally accessible to all to\n" + + "require a permission to run.\n\n" + + "Setting this to true will enable greater control over whether a command will appear in\n" + + "tab completion and Sponge's help command.\n\n" + + "If you are not using a permissions plugin, it is highly recommended that this is set to false\n" + + "(as it is by default).") private boolean enforcePermissionChecksOnNonSpongeCommands = false; - @Setting(value = "multi-world-patches", comment = "Patches the specified commands to respect the world of the sender instead of applying the \n" + @Setting("multi-world-patches") + @Comment("Patches the specified commands to respect the world of the sender instead of applying the \n" + "changes on the all worlds.") private Map multiWorldCommandPatches = new HashMap<>(); - @Setting(value = "command-hiding", - comment = "Defines how Sponge should act when a user tries to access a command they do not have\n" - + "permission for") + @Setting + @Comment("Defines how Sponge should act when a user tries to access a command they do not have\n" + + "permission for") private CommandsHiddenCategory commandHiding = new CommandsHiddenCategory(); public boolean isEnforcePermissionChecksOnNonSpongeCommands() { diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/CommandsHiddenCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/CommandsHiddenCategory.java index 4b0602a102e..d9c56ebe97b 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/CommandsHiddenCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/CommandsHiddenCategory.java @@ -24,22 +24,23 @@ */ package org.spongepowered.common.applaunch.config.common; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; @ConfigSerializable public class CommandsHiddenCategory { - @Setting(value = "hide-on-discovery-attempt", - comment = "If this is true, when a user tries to tab complete a command, or use \"/sponge which\" or \n" - + "\"/sponge:help\" this prevents commands a user does not have permission for from being completed.\n\n" - + "Note that some commands may not show up during tab complete if a user does not have permission\n" - + "regardless of this setting.") + @Setting("hide-on-discovery-attempt") + @Comment("If this is true, when a user tries to tab complete a command, or use \"/sponge which\" or \n" + + "\"/sponge:help\" this prevents commands a user does not have permission for from being completed.\n\n" + + "Note that some commands may not show up during tab complete if a user does not have permission\n" + + "regardless of this setting.") private boolean hideDuringDiscovery = true; - @Setting(value = "hide-on-execution-attempt", - comment = "If this is true, when a user tries to use a command they don't have permission for, Sponge\n" - + "will act as if the command doesn't exist, rather than showing a no permissions message.") + @Setting("hide-on-execution-attempt") + @Comment("If this is true, when a user tries to use a command they don't have permission for, Sponge\n" + + "will act as if the command doesn't exist, rather than showing a no permissions message.") private boolean hideDuringExecution = false; public boolean isHideDuringDiscovery() { diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/CommonConfig.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/CommonConfig.java index 40cd4115834..4debb61f422 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/CommonConfig.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/CommonConfig.java @@ -24,7 +24,8 @@ */ package org.spongepowered.common.applaunch.config.common; -import ninja.leaping.configurate.objectmapping.Setting; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; import org.spongepowered.common.applaunch.config.core.Config; import java.util.HashMap; @@ -47,7 +48,8 @@ public class CommonConfig implements Config { @Setting private GeneralCategory general = new GeneralCategory(); - @Setting(comment = "Configuration options related to the SQL manager, including connection aliases etc") + @Setting + @Comment("Configuration options related to the SQL manager, including connection aliases etc") private SqlCategory sql = new SqlCategory(); @Setting @@ -56,32 +58,34 @@ public class CommonConfig implements Config { @Setting private PermissionCategory permission = new PermissionCategory(); - @Setting(value = "modules") + @Setting("modules") private ModuleCategory mixins = new ModuleCategory(); @Setting("ip-sets") private Map> ipSets = new HashMap<>(); - @Setting(value = "bungeecord") + @Setting("bungeecord") private BungeeCordCategory bungeeCord = new BungeeCordCategory(); @Setting private ExploitCategory exploits = new ExploitCategory(); - @Setting(value = "optimizations") + @Setting("optimizations") private OptimizationCategory optimizations = new OptimizationCategory(); - @Setting(value = "cause-tracker") + @Setting("cause-tracker") private PhaseTrackerCategory causeTracker = new PhaseTrackerCategory(); - @Setting(value = "teleport-helper", comment = "Blocks to blacklist for safe teleportation.") + @Setting("teleport-helper") + @Comment("Blocks to blacklist for safe teleportation.") private TeleportHelperCategory teleportHelper = new TeleportHelperCategory(); - @Setting(value = "broken-mods", comment = "Stopgap measures for dealing with broken mods") + @Setting("broken-mods") + @Comment("Stopgap measures for dealing with broken mods") private BrokenModCategory brokenMods = new BrokenModCategory(); - @Setting(value = "service-registration", - comment = "Enables server owners to require specific plugins to provide Sponge services") + @Setting("service-registration") + @Comment("Enables server owners to require specific plugins to provide Sponge services") private ServicesCategory servicesCategory = new ServicesCategory(); @Setting diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/DebugCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/DebugCategory.java index 6d9a8ccfaa9..47f86948c7a 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/DebugCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/DebugCategory.java @@ -24,21 +24,25 @@ */ package org.spongepowered.common.applaunch.config.common; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; @ConfigSerializable public class DebugCategory { - @Setting(value = "thread-contention-monitoring", comment = "If 'true', Java's thread contention monitoring for thread dumps is enabled.") + @Setting("thread-contention-monitoring") + @Comment("If 'true', Java's thread contention monitoring for thread dumps is enabled.") private boolean enableThreadContentionMonitoring = false; - @Setting(value = "concurrent-entity-checks", comment = "Detect and prevent certain attempts to use entities concurrently. \n" + @Setting("concurrent-entity-checks") + @Comment("Detect and prevent certain attempts to use entities concurrently. \n" + "WARNING: May drastically decrease server performance. Only set this to 'true' " + "to debug a pre-existing issue.") private boolean concurrentEntityChecks = false; - @Setting(value = "concurrent-chunk-map-checks", comment = "Detect and prevent parts of PlayerChunkMap being called off the main thread.\n" + @Setting("concurrent-chunk-map-checks") + @Comment("Detect and prevent parts of PlayerChunkMap being called off the main thread.\n" + "This may decrease sever preformance, so you should only enable it when debugging a specific issue.") private boolean concurrentChunkMapChecks = false; @@ -54,7 +58,7 @@ public boolean isEnableThreadContentionMonitoring() { return this.enableThreadContentionMonitoring; } - public void setEnableThreadContentionMonitoring(boolean enableThreadContentionMonitoring) { + public void setEnableThreadContentionMonitoring(final boolean enableThreadContentionMonitoring) { this.enableThreadContentionMonitoring = enableThreadContentionMonitoring; } } diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/EigenRedstoneCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/EigenRedstoneCategory.java index 39976104431..dd5346ae9e2 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/EigenRedstoneCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/EigenRedstoneCategory.java @@ -24,20 +24,24 @@ */ package org.spongepowered.common.applaunch.config.common; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; @ConfigSerializable public class EigenRedstoneCategory { - @Setting(value = "enabled", comment = "If 'true', uses theosib's redstone implementation which improves performance. \n" + @Setting("enabled") + @Comment("If 'true', uses theosib's redstone implementation which improves performance. \n" + "See https://bugs.mojang.com/browse/MC-11193 and \n " + " https://bugs.mojang.com/browse/MC-81098 for more information. \n" + "Note: We cannot guarantee compatibility with mods. Use at your discretion.") private boolean isEnabled = false; - @Setting(value = "vanilla-search", comment = "If 'true', restores the vanilla algorithm for propagating redstone wire changes.") + @Setting("vanilla-search") + @Comment("If 'true', restores the vanilla algorithm for propagating redstone wire changes.") private boolean vanillaSearch = false; - @Setting(value = "vanilla-decrement", comment = "If 'true', restores the vanilla algorithm for computing wire power levels when powering off.") + @Setting("vanilla-decrement") + @Comment("If 'true', restores the vanilla algorithm for computing wire power levels when powering off.") private boolean vanillaDecrement = false; public EigenRedstoneCategory() { diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/ExploitCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/ExploitCategory.java index 32f775cfc5c..cb1ee159292 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/ExploitCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/ExploitCategory.java @@ -24,26 +24,28 @@ */ package org.spongepowered.common.applaunch.config.common; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; @ConfigSerializable public class ExploitCategory { - @Setting(value = "prevent-creative-itemstack-name-exploit", comment = "Prevents an exploit in which the client sends a packet with the \n" - + "itemstack name exceeding the string limit.") + @Setting("prevent-creative-itemstack-name-exploit") + @Comment("Prevents an exploit in which the client sends a packet with the \n" + + "itemstack name exceeding the string limit.") private boolean preventItemNameOverflow = true; - @Setting(value = "mark-chunks-as-dirty-on-entity-list-modification", - comment = "Enables forcing chunks to save when an entity is added\n" - + "or removed from said chunk. This is a partial fix for\n" - + "some exploits using vehicles." - + "See https://github.com/PaperMC/Paper/blob/fd1bd5223a461b6d98280bb8f2d67280a30dd24a/Spigot-Server-Patches/0306-Mark-chunk-dirty-anytime-entities-change-to-guarante.patch\n" - + "(Only affects SpongeVanilla)") + @Setting("mark-chunks-as-dirty-on-entity-list-modification") + @Comment("Enables forcing chunks to save when an entity is added\n" + + "or removed from said chunk. This is a partial fix for\n" + + "some exploits using vehicles." + + "See https://github.com/PaperMC/Paper/blob/fd1bd5223a461b6d98280bb8f2d67280a30dd24a/Spigot-Server-Patches/0306-Mark-chunk-dirty-anytime-entities-change-to-guarante.patch\n" + + "(Only affects SpongeVanilla)") private boolean chunksAlwaysSave = true; - @Setting(value = "update-tracked-chunk-on-entity-move", - comment = "Enables forcing a chunk-tracking refresh on entity movement.\n" + @Setting("update-tracked-chunk-on-entity-move") + @Comment("Enables forcing a chunk-tracking refresh on entity movement.\n" + "This enables a guarantee that the entity is tracked in the \n" + "proper chunk when moving." + "https://github.com/PaperMC/Paper/blob/fd1bd5223a461b6d98280bb8f2d67280a30dd24a/Spigot-Server-Patches/0315-Always-process-chunk-registration-after-moving.patch\n" @@ -51,8 +53,8 @@ public class ExploitCategory { ) private boolean chunkRegistrationOnMove = true; - @Setting(value = "load-chunk-on-position-set", - comment = "Enables focing a chunk load when an entity position\n" + @Setting("load-chunk-on-position-set") + @Comment("Enables focing a chunk load when an entity position\n" + "is set. Usually due to teleportation, vehicle movement\n" + "etc. can a position lead an entity to no longer exist\n" + "within it's currently marked and tracked chunk. This will\n" @@ -63,8 +65,8 @@ public class ExploitCategory { ) private boolean chunkLoadOnPosition = true; - @Setting(value = "sync-player-positions-for-vehicle-movement", - comment = "Enables forcing updates to the player's location on vehicle movement.\n" + @Setting("sync-player-positions-for-vehicle-movement") + @Comment("Enables forcing updates to the player's location on vehicle movement.\n" + "This is partially required to update the server's understanding of\n" + "where the player exists, and allows chunk loading issues to be avoided\n" + "with laggy connections and/or hack clients." @@ -73,8 +75,8 @@ public class ExploitCategory { ) private boolean playerVehicleSync = true; - @Setting(value = "filter-invalid-entities-on-chunk-save", - comment = "Enables filtering invalid entities when a chunk is being saved\n" + @Setting("filter-invalid-entities-on-chunk-save") + @Comment("Enables filtering invalid entities when a chunk is being saved\n" + "such that the entity that does not \"belong\" in the saving\n" + "chunk will not be saved, and forced an update to the world's\n" + "tracked entity lists for chunks.\n" @@ -82,15 +84,18 @@ public class ExploitCategory { ) private boolean chunkSaveFiltersEntities = true; - @Setting(value = "limit-book-size", comment = "Limits the size of a book that can be sent by the client.\n" + @Setting("limit-book-size") + @Comment("Limits the size of a book that can be sent by the client.\n" + "See https://github.com/PaperMC/Paper/blob/f8058a8187da9f6185d95bb786783e12c79c8b18/Spigot-Server-Patches/0403-Book-Size-Limits.patch\n" + "(Only affects SpongeVanilla)") private boolean limitBookSize = true; - @Setting(value = "max-book-page-size", comment = "If limit-book-size is enabled, controls the maximum size of a book page") + @Setting("max-book-page-size") + @Comment("If limit-book-size is enabled, controls the maximum size of a book page") private int maxBookPageSize = 2560; - @Setting(value = "book-size-total-multiplier", comment = "If limit-book-size is enabled, controls the multiplier applied to each book page size") + @Setting("book-size-total-multiplier") + @Comment("If limit-book-size is enabled, controls the multiplier applied to each book page size") private double bookSizeTotalMultiplier = 0.98; public boolean isPreventItemNameOverflow() { diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/GeneralCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/GeneralCategory.java index bec57c191bc..0dd5ae42fdf 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/GeneralCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/GeneralCategory.java @@ -24,31 +24,35 @@ */ package org.spongepowered.common.applaunch.config.common; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.common.applaunch.config.core.TokenHoldingString; @ConfigSerializable public class GeneralCategory { - @Setting(value = "file-io-thread-sleep", comment = "If 'true', sleeping between chunk saves will be enabled, beware of memory issues.") + @Setting("file-io-thread-sleep") + @Comment("If 'true', sleeping between chunk saves will be enabled, beware of memory issues.") private boolean fileIOThreadSleep = false; - @Setting(value = "plugins-dir", comment = "Additional directory to search for plugins, relative to the \n" - + "execution root or specified as an absolute path. \n" - + "Note that the default: \"${CANONICAL_MODS_DIR}/plugins\" \n" - + "is going to search for a plugins folder in the mods directory. \n" - + "If you wish for the plugins folder to reside in the root game \n" - + "directory, change the value to \"${CANONICAL_GAME_DIR}/plugins\".") + @Setting("plugins-dir") + @Comment("Additional directory to search for plugins, relative to the \n" + + "execution root or specified as an absolute path. \n" + + "Note that the default: \"${CANONICAL_MODS_DIR}/plugins\" \n" + + "is going to search for a plugins folder in the mods directory. \n" + + "If you wish for the plugins folder to reside in the root game \n" + + "directory, change the value to \"${CANONICAL_GAME_DIR}/plugins\".") private TokenHoldingString pluginsDir = TokenHoldingString.of("${CANONICAL_MODS_DIR}/plugins"); - @Setting(value = "config-dir", comment = "The directory for Sponge plugin configurations, relative to the \n" - + "execution root or specified as an absolute path. \n" - + "Note that the default: \"${CANONICAL_GAME_DIR}/config\" \n" - + "is going to use the \"config\" directory in the root game directory. \n" - + "If you wish for plugin configs to reside within a child of the configuration \n" - + "directory, change the value to, for example, \"${CANONICAL_CONFIG_DIR}/sponge/plugins\". \n" - + "Note: It is not recommended to set this to \"${CANONICAL_CONFIG_DIR}/sponge\", as there is \n" - + "a possibility that plugin configurations can conflict the Sponge core configurations. \n") + @Setting("config-dir") + @Comment("The directory for Sponge plugin configurations, relative to the \n" + + "execution root or specified as an absolute path. \n" + + "Note that the default: \"${CANONICAL_GAME_DIR}/config\" \n" + + "is going to use the \"config\" directory in the root game directory. \n" + + "If you wish for plugin configs to reside within a child of the configuration \n" + + "directory, change the value to, for example, \"${CANONICAL_CONFIG_DIR}/sponge/plugins\". \n" + + "Note: It is not recommended to set this to \"${CANONICAL_CONFIG_DIR}/sponge\", as there is \n" + + "a possibility that plugin configurations can conflict the Sponge core configurations. \n") private TokenHoldingString configDir = TokenHoldingString.of("${CANONICAL_GAME_DIR}/config"); public boolean getFileIoThreadSleep() { diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/ModuleCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/ModuleCategory.java index 889de2a5788..81f552503dd 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/ModuleCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/ModuleCategory.java @@ -24,32 +24,35 @@ */ package org.spongepowered.common.applaunch.config.common; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; @ConfigSerializable public class ModuleCategory { - @Setting(value = "bungeecord") + @Setting("bungeecord") private boolean pluginBungeeCord = false; - @Setting(value = "entity-activation-range") + @Setting("entity-activation-range") private boolean pluginEntityActivation = true; - @Setting(value = "tileentity-activation", comment = "Controls block range and tick rate of tileentities. \n" - + "Use with caution as this can break intended functionality.") + @Setting("tileentity-activation") + @Comment("Controls block range and tick rate of tileentities. \n" + + "Use with caution as this can break intended functionality.") private boolean pluginTileEntityActivation = false; - @Setting(value = "entity-collisions") + @Setting("entity-collisions") private boolean pluginEntityCollisions = true; @Setting("timings") private boolean pluginTimings = true; - @Setting(value = "exploits", comment = "Controls whether any exploit patches are applied.\n" - + "If there are issues with any specific exploits, please\n" - + "test in the exploit category first, before disabling all\n" - + "exploits with this toggle.") + @Setting("exploits") + @Comment("Controls whether any exploit patches are applied.\n" + + "If there are issues with any specific exploits, please\n" + + "test in the exploit category first, before disabling all\n" + + "exploits with this toggle.") private boolean enableExploitPatches = true; @Setting("optimizations") @@ -58,13 +61,16 @@ public class ModuleCategory { @Setting("tracking") private boolean tracking = true; - @Setting(value = "realtime", comment = "Use real (wall) time instead of ticks as much as possible") + @Setting("realtime") + @Comment("Use real (wall) time instead of ticks as much as possible") private boolean pluginRealTime = false; - @Setting(value = "movement-checks", comment = "Allows configuring Vanilla movement and speed checks") + @Setting("movement-checks") + @Comment("Allows configuring Vanilla movement and speed checks") private boolean movementChecks = false; - @Setting(value = "broken-mod", comment = "Enables experimental fixes for broken mods") + @Setting("broken-mod") + @Comment("Enables experimental fixes for broken mods") private boolean brokenMods = false; public boolean useBrokenMods() { @@ -75,7 +81,7 @@ public boolean usePluginBungeeCord() { return this.pluginBungeeCord; } - public void setPluginBungeeCord(boolean state) { + public void setPluginBungeeCord(final boolean state) { this.pluginBungeeCord = state; } @@ -87,7 +93,7 @@ public boolean usePluginTileEntityActivation() { return this.pluginTileEntityActivation; } - public void setPluginEntityActivation(boolean state) { + public void setPluginEntityActivation(final boolean state) { this.pluginEntityActivation = state; } @@ -95,7 +101,7 @@ public boolean usePluginEntityCollisions() { return this.pluginEntityCollisions; } - public void setPluginEntityCollisions(boolean state) { + public void setPluginEntityCollisions(final boolean state) { this.pluginEntityCollisions = state; } @@ -103,7 +109,7 @@ public boolean usePluginTimings() { return this.pluginTimings; } - public void setPluginTimings(boolean state) { + public void setPluginTimings(final boolean state) { this.pluginTimings = state; } @@ -111,7 +117,7 @@ public boolean useExploitPatches() { return this.enableExploitPatches; } - public void setExploitPatches(boolean enableExploitPatches) { + public void setExploitPatches(final boolean enableExploitPatches) { this.enableExploitPatches = enableExploitPatches; } @@ -123,7 +129,7 @@ public boolean useTracking() { return this.tracking; } - public void setTracking(boolean tracking) { + public void setTracking(final boolean tracking) { this.tracking = tracking; } @@ -135,7 +141,7 @@ public boolean usePluginRealTime() { return this.pluginRealTime; } - public void setPluginRealTime(boolean state) { + public void setPluginRealTime(final boolean state) { this.pluginRealTime = state; } } diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/OptimizationCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/OptimizationCategory.java index 30e13a97c39..117d79ae41b 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/OptimizationCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/OptimizationCategory.java @@ -24,76 +24,87 @@ */ package org.spongepowered.common.applaunch.config.common; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.common.applaunch.config.core.SpongeConfigs; @ConfigSerializable public class OptimizationCategory { - @Setting(value = "drops-pre-merge", comment = "If 'true', block item drops are pre-processed to avoid \n" - + "having to spawn extra entities that will be merged post spawning. \n" - + "Usually, Sponge is smart enough to determine when to attempt an item pre-merge \n" - + "and when not to, however, in certain cases, some mods rely on items not being \n" - + "pre-merged and actually spawned, in which case, the items will flow right through \n" - + "without being merged.") + @Setting("drops-pre-merge") + @Comment("If 'true', block item drops are pre-processed to avoid \n" + + "having to spawn extra entities that will be merged post spawning. \n" + + "Usually, Sponge is smart enough to determine when to attempt an item pre-merge \n" + + "and when not to, however, in certain cases, some mods rely on items not being \n" + + "pre-merged and actually spawned, in which case, the items will flow right through \n" + + "without being merged.") private boolean preItemDropMerge = false; - @Setting(value = "cache-tameable-owners", comment = "Caches tameable entities owners to avoid constant lookups against data watchers. If mods \n" - + "cause issues, disable this.") + @Setting("cache-tameable-owners") + @Comment("Caches tameable entities owners to avoid constant lookups against data watchers. If mods \n" + + "cause issues, disable this.") private boolean cacheTameableOwners = true; - @Setting(value = "structure-saving", comment = "Handles structures that are saved to disk. Certain structures can take up large amounts \n" - + "of disk space for very large maps and the data for these structures is only needed while the \n" - + "world around them is generating. Disabling saving of these structures can save disk space and \n" - + "time during saves if your world is already fully generated. \n" - + "Warning: disabling structure saving will break the vanilla locate command.") - private StructureSaveCategory structureSaveCategory = new StructureSaveCategory(); - - @Setting(value = "eigen-redstone", comment = "Uses theosib's redstone algorithms to completely overhaul the way redstone works.") - private EigenRedstoneCategory eigenRedstonCategory = new EigenRedstoneCategory(); - - @Setting(value = "faster-thread-checks", comment = "If 'true', allows for Sponge to make better assumptinos on single threaded\n" - + "operations with relation to various checks for server threaded operations.\n" - + "This is default to true due to Sponge being able to precisely inject when\n" - + "the server thread is available. This should make an already fast operation\n" - + "much faster for better thread checks to ensure stability of sponge's systems.") + @Setting("structure-saving") + @Comment("Handles structures that are saved to disk. Certain structures can take up large amounts \n" + + "of disk space for very large maps and the data for these structures is only needed while the \n" + + "world around them is generating. Disabling saving of these structures can save disk space and \n" + + "time during saves if your world is already fully generated. \n" + + "Warning: disabling structure saving will break the vanilla locate command.") + private StructureSaveCategory structureSaving = new StructureSaveCategory(); + + @Setting("eigen-redstone") + @Comment("Uses theosib's redstone algorithms to completely overhaul the way redstone works.") + private EigenRedstoneCategory eigenRedstone = new EigenRedstoneCategory(); + + @Setting("faster-thread-checks") + @Comment("If 'true', allows for Sponge to make better assumptions on single threaded\n" + + "operations with relation to various checks for server threaded operations.\n" + + "This is default to true due to Sponge being able to precisely inject when\n" + + "the server thread is available. This should make an already fast operation\n" + + "much faster for better thread checks to ensure stability of sponge's systems.") private boolean fasterThreadChecks = true; - @Setting(value = "map-optimization", comment = "If 'true', re-writes the incredibly inefficient Vanilla Map code.\n" + @Setting("map-optimization") + @Comment("If 'true', re-writes the incredibly inefficient Vanilla Map code.\n" + "This yields enormous performance enhancements when using many maps, but has a tiny chance of breaking mods that invasively modify Vanilla." + "It is strongly reccomended to keep this on, unless explicitly advised otherwise by a Sponge developer") private boolean mapOptimization = true; - @Setting(value = "optimize-hoppers", comment = "Based on Aikar's optimizationo of Hoppers, setting this to 'true'\n" - + "will allow for hoppers to save performing server -> client updates\n" - + "when transferring items. Because hoppers can transfer items multiple\n" - + "times per tick, these updates can get costly on the server, with\n" - + "little to no benefit to the client. Because of the nature of the\n" - + "change, the default will be 'false' due to the inability to pre-emptively\n" - + "foretell whether mod compatibility will fail with these changes or not.\n" - + "Refer to: https://github.com/PaperMC/Paper/blob/8175ec916f31dcd130fe0884fe46bdc187d829aa/Spigot-Server-Patches/0269-Optimize-Hoppers.patch\n" - + "for more details.") + @Setting("optimize-hoppers") + @Comment("Based on Aikar's optimizationo of Hoppers, setting this to 'true'\n" + + "will allow for hoppers to save performing server -> client updates\n" + + "when transferring items. Because hoppers can transfer items multiple\n" + + "times per tick, these updates can get costly on the server, with\n" + + "little to no benefit to the client. Because of the nature of the\n" + + "change, the default will be 'false' due to the inability to pre-emptively\n" + + "foretell whether mod compatibility will fail with these changes or not.\n" + + "Refer to: https://github.com/PaperMC/Paper/blob/8175ec916f31dcd130fe0884fe46bdc187d829aa/Spigot-Server-Patches/0269-Optimize-Hoppers.patch\n" + + "for more details.") private boolean optimizeHoppers = false; - @Setting(value = "use-active-chunks-for-collisions", comment = "Vanilla performs a lot of is area loaded checks during\n" - + "entity collision calculations with blocks, and because\n" - + "these calculations require fetching the chunks to see\n" - + "if they are loaded, before getting the block states\n" - + "from those chunks, there can be some small performance\n" - + "increase by checking the entity's owned active chunk\n" - + "it may currently reside in. Essentially, instead of\n" - + "asking the world if those chunks are loaded, the entity\n" - + "would know whether it's chunks are loaded and that neighbor's\n" - + "chunks are loaded.") + @Setting("use-active-chunks-for-collisions") + @Comment("Vanilla performs a lot of is area loaded checks during\n" + + "entity collision calculations with blocks, and because\n" + + "these calculations require fetching the chunks to see\n" + + "if they are loaded, before getting the block states\n" + + "from those chunks, there can be some small performance\n" + + "increase by checking the entity's owned active chunk\n" + + "it may currently reside in. Essentially, instead of\n" + + "asking the world if those chunks are loaded, the entity\n" + + "would know whether it's chunks are loaded and that neighbor's\n" + + "chunks are loaded.") private boolean useActiveChunkForCollisions = false; - @Setting(value = "tileentity-ticking-optimization", comment = "Based on Paper's TileEntity Ticking optimization\n" - + "setting this to 'true' prevents unnecessary ticking in Chests and EnderChests\n" - + "See https://github.com/PaperMC/Paper/blob/bb4002d82e355f033906fc894cc2320f665ba72d/Spigot-Server-Patches/0022-Optimize-TileEntity-Ticking.patch") + @Setting("tileentity-ticking-optimization") + @Comment("Based on Paper's TileEntity Ticking optimization\n" + + "setting this to 'true' prevents unnecessary ticking in Chests and EnderChests\n" + + "See https://github.com/PaperMC/Paper/blob/bb4002d82e355f033906fc894cc2320f665ba72d/Spigot-Server-Patches/0022-Optimize-TileEntity-Ticking.patch") private boolean optimizeTileEntityTicking = true; - @Setting(value = "disable-failing-deserialization-log-spam", comment = "Occasionally, some built in advancements, \n" + + @Setting("disable-failing-deserialization-log-spam") + @Comment("Occasionally, some built in advancements, \n" + "recipes, etc. can fail to deserialize properly\n" + "which ends up potentially spamming the server log\n" + "and the original provider of the failing content\n" + @@ -107,13 +118,12 @@ public OptimizationCategory() { this.preItemDropMerge = SpongeConfigs.getPluginEnvironment().getBlackboard().get(SpongeConfigs.IS_VANILLA_PLATFORM).orElse(true); } - - public StructureSaveCategory getStructureSaveCategory() { - return this.structureSaveCategory; + public StructureSaveCategory getStructureSaving() { + return this.structureSaving; } public boolean useStructureSave() { - return this.structureSaveCategory.isEnabled(); + return this.structureSaving.isEnabled(); } public boolean useMapOptimization() { @@ -138,11 +148,11 @@ public boolean useCacheTameableOwners() { } public EigenRedstoneCategory getEigenRedstoneCategory() { - return this.eigenRedstonCategory; + return this.eigenRedstone; } public boolean useEigenRedstone() { - return this.eigenRedstonCategory.isEnabled(); + return this.eigenRedstone.isEnabled(); } public boolean useFastThreadChecks() { @@ -164,4 +174,5 @@ public boolean isOptimizedTileEntityTicking() { public boolean disableFailingAdvancementDeserialization() { return this.disableFailingAdvancementDeserialization; } + } diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/PermissionCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/PermissionCategory.java index ba98bd4f414..1f1a8fe3cb4 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/PermissionCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/PermissionCategory.java @@ -24,13 +24,15 @@ */ package org.spongepowered.common.applaunch.config.common; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; @ConfigSerializable public class PermissionCategory { - @Setting(value = "forge-permissions-handler", comment = "If 'true', Sponge plugins will be used to handle permissions rather " + @Setting(value = "forge-permissions-handler") + @Comment("If 'true', Sponge plugins will be used to handle permissions rather " + "than any Forge mod") private boolean enableHandler = false; diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/PhaseTrackerCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/PhaseTrackerCategory.java index f061b16eeaf..f0cc3feb07d 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/PhaseTrackerCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/PhaseTrackerCategory.java @@ -24,8 +24,9 @@ */ package org.spongepowered.common.applaunch.config.common; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.common.applaunch.config.core.SpongeConfigs; import java.util.HashMap; @@ -34,19 +35,22 @@ @ConfigSerializable public class PhaseTrackerCategory { - @Setting(value = "verbose", comment = "If 'true', the phase tracker will print out when there are too many phases \n" + @Setting("verbose") + @Comment("If 'true', the phase tracker will print out when there are too many phases \n" + "being entered, usually considered as an issue of phase re-entrance and \n" + "indicates an unexpected issue of tracking phases not to complete. \n" + "If this is not reported yet, please report to Sponge. If it has been \n" + "reported, you may disable this.") private boolean isVerbose = true; - @Setting(value = "verbose-errors", comment = "If 'true', the phase tracker will dump extra information about the current phases \n" + @Setting("verbose-errors") + @Comment("If 'true', the phase tracker will dump extra information about the current phases \n" + "when certain non-PhaseTracker related exceptions occur. This is usually not necessary, as the information \n" + "in the exception itself can normally be used to determine the cause of the issue") private boolean verboseErrors = false; - @Setting(value = "capture-async-spawning-entities", comment = "If set to 'true', when a mod or plugin attempts to spawn an entity \n" + @Setting("capture-async-spawning-entities") + @Comment("If set to 'true', when a mod or plugin attempts to spawn an entity \n" + "off the main server thread, Sponge will automatically \n" + "capture said entity to spawn it properly on the main \n" + "server thread. The catch to this is that some mods are \n" @@ -57,7 +61,8 @@ public class PhaseTrackerCategory { + "and emit a warning about said spawn anyways.") private boolean captureAndSpawnEntitiesSync = true; - @Setting(value = "resync-commands-from-async", comment = "If set to 'true', when a mod or plugin attempts to submit a command\n" + @Setting("resync-commands-from-async") + @Comment("If set to 'true', when a mod or plugin attempts to submit a command\n" + "asynchronously, Sponge will automatically capture said command\n" + "and submit it for processing on the server thread. The catch to\n" + "this is that some mods are performing these commands in vanilla\n" @@ -68,7 +73,8 @@ public class PhaseTrackerCategory { + "about said command anyways.") private boolean resyncAsyncCommands = true; - @Setting(value = "generate-stacktrace-per-phase", comment = "If 'true', more thorough debugging for PhaseStates \n" + @Setting("generate-stacktrace-per-phase") + @Comment("If 'true', more thorough debugging for PhaseStates \n" + "such that a StackTrace is created every time a PhaseState \n" + "switches, allowing for more fine grained troubleshooting \n" + "in the cases of runaway phase states. Note that this is \n" @@ -76,7 +82,8 @@ public class PhaseTrackerCategory { + "with generating the stack traces constantly.") private boolean generateStackTracePerStateEntry = false; - @Setting(value = "maximum-printed-runaway-counts", comment = "If verbose is not enabled, this restricts the amount of \n" + @Setting("maximum-printed-runaway-counts") + @Comment("If verbose is not enabled, this restricts the amount of \n" + "runaway phase state printouts, usually happens on a server \n" + "where a PhaseState is not completing. Although rare, it should \n" + "never happen, but when it does, sometimes it can continuously print \n" @@ -88,7 +95,8 @@ public boolean isVerbose() { return this.isVerbose; } - @Setting(value = "max-block-processing-depth", comment = "The maximum number of times to recursively process transactions in a single phase.\n" + @Setting("max-block-processing-depth") + @Comment("The maximum number of times to recursively process transactions in a single phase.\n" + "Some mods may interact badly with Sponge's block capturing system, causing Sponge to\n" + "end up capturing block transactions every time it tries to process an existing batch.\n" + "Due to the recursive nature of the depth-first processing that Sponge uses to handle block transactions,\n" @@ -98,44 +106,44 @@ public boolean isVerbose() { + "The default value should almost always work properly - it's unlikely you'll ever have to change it.") private int maxBlockProcessingDepth = 1000; - @Setting(value = "report-null-source-blocks-on-neighbor-notifications", - comment = "If true, when a mod attempts to perform a neighbor notification\n" - + "on a block, some mods do not know to perform a \'null\' check\n" - + "on the source block of their TileEntity. This usually goes by\n" - + "unnoticed by other mods, because they may perform \'==\' instance\n" - + "equality checks instead of calling methods on the potentially\n" - + "null Block, but Sponge uses the block to build information to\n" - + "help tracking. This has caused issues in the past. Generally,\n" - + "this can be useful for leaving \"true\" so a proper report is\n" - + "generated once for your server, and can be reported to the\n" - + "offending mod author.\n" - + "This is 'false' by default in SpongeVanilla.\n" - + "Review the following links for more info:\n" - + " https://gist.github.com/gabizou/ad570dc09dfed259cac9d74284e78e8b\n" - + " https://github.com/SpongePowered/SpongeForge/issues/2787\n" + @Setting("report-null-source-blocks-on-neighbor-notifications") + @Comment("If true, when a mod attempts to perform a neighbor notification\n" + + "on a block, some mods do not know to perform a 'null' check\n" + + "on the source block of their TileEntity. This usually goes by\n" + + "unnoticed by other mods, because they may perform '==' instance\n" + + "equality checks instead of calling methods on the potentially\n" + + "null Block, but Sponge uses the block to build information to\n" + + "help tracking. This has caused issues in the past. Generally,\n" + + "this can be useful for leaving \"true\" so a proper report is\n" + + "generated once for your server, and can be reported to the\n" + + "offending mod author.\n" + + "This is 'false' by default in SpongeVanilla.\n" + + "Review the following links for more info:\n" + + " https://gist.github.com/gabizou/ad570dc09dfed259cac9d74284e78e8b\n" + + " https://github.com/SpongePowered/SpongeForge/issues/2787\n" ) private boolean reportNullSourceBlocks = this.isVanilla(); - @Setting(value = "auto-fix-null-source-block-providing-tile-entities", - comment = "A mapping that is semi-auto-populating for TileEntities whose types\n" - + "are found to be providing \"null\" Block sources as neighbor notifications\n" - + "that end up causing crashes or spam reports. If the value is set to \n" - + "\"true\", then a \"workaround\" will be attempted. If not, the \n" - + "\ncurrent BlockState at the target source will be queried from the world.\n" - + "This map having a specific\n" - + "entry of a TileEntity will prevent a log or warning come up to any logs\n" - + "when that \"null\" arises, and Sponge will self-rectify the TileEntity\n" - + "by calling the method \"getBlockType()\". It is advised that if the mod\n" - + "id in question is coming up, that the mod author is notified about the\n" - + "error-prone usage of the field \"blockType\". You can refer them to\n" - + "the following links for the issue:\n" - + " https://gist.github.com/gabizou/ad570dc09dfed259cac9d74284e78e8b\n" - + " https://github.com/SpongePowered/SpongeForge/issues/2787\n" - + "Also, please provide them with these links for the example PR to\n" - + "fix the issue itself, as the fix is very simple:\n" - + "https://github.com/TehNut/Soul-Shards-Respawn/pull/24\n" - + "https://github.com/Epoxide-Software/Enchanting-Plus/pull/135\n" - ) private Map autoFixedTiles = new HashMap<>(); + @Setting("auto-fix-null-source-block-providing-tile-entities") + @Comment("A mapping that is semi-auto-populating for TileEntities whose types\n" + + "are found to be providing \"null\" Block sources as neighbor notifications\n" + + "that end up causing crashes or spam reports. If the value is set to \n" + + "\"true\", then a \"workaround\" will be attempted. If not, the \n" + + "\ncurrent BlockState at the target source will be queried from the world.\n" + + "This map having a specific\n" + + "entry of a TileEntity will prevent a log or warning come up to any logs\n" + + "when that \"null\" arises, and Sponge will self-rectify the TileEntity\n" + + "by calling the method \"getBlockType()\". It is advised that if the mod\n" + + "id in question is coming up, that the mod author is notified about the\n" + + "error-prone usage of the field \"blockType\". You can refer them to\n" + + "the following links for the issue:\n" + + " https://gist.github.com/gabizou/ad570dc09dfed259cac9d74284e78e8b\n" + + " https://github.com/SpongePowered/SpongeForge/issues/2787\n" + + "Also, please provide them with these links for the example PR to\n" + + "fix the issue itself, as the fix is very simple:\n" + + "https://github.com/TehNut/Soul-Shards-Respawn/pull/24\n" + + "https://github.com/Epoxide-Software/Enchanting-Plus/pull/135\n") + private Map autoFixedTiles = new HashMap<>(); public int getMaxBlockProcessingDepth() { return this.maxBlockProcessingDepth; @@ -169,7 +177,7 @@ public boolean isReportNullSourceBlocks() { return this.reportNullSourceBlocks; } - public void setReportNullSourceBlocks(boolean reportNullSourceBlocks) { + public void setReportNullSourceBlocks(final boolean reportNullSourceBlocks) { this.reportNullSourceBlocks = reportNullSourceBlocks; } @@ -181,7 +189,7 @@ private boolean isVanilla() { return SpongeConfigs.getPluginEnvironment().getBlackboard().get(SpongeConfigs.IS_VANILLA_PLATFORM).orElse(true); } - public void setAutoFixedTiles(Map autoFixedTiles) { + public void setAutoFixedTiles(final Map autoFixedTiles) { this.autoFixedTiles = autoFixedTiles; } } diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/ServicesCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/ServicesCategory.java index b39c0740156..fe7fee44120 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/ServicesCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/ServicesCategory.java @@ -24,23 +24,26 @@ */ package org.spongepowered.common.applaunch.config.common; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; @ConfigSerializable public final class ServicesCategory { - @Setting(value = "service-plugin", - comment = "Services specified here can be implemented by plugins. To ensure that a" - + "specific plugin implements a given service, set the relevant option to its" - + "plugin ID. If you wish to use Sponge's default for a given service, use" - + "'sponge' as the ID.\n\n" - + "If the plugin ID is unknown, or the option is set to '?', all plugins will" - + "be given the opportunity to register their service. If multiple plugins" - + "attempt to register, one will be picked in an implementation dependent way." - + "If no plugins attempt to register a service, the Sponge default will be used" - + "if one exists.\n\n" - + "No Sponge default service exists for the Economy service.") + public static final String UNSPECIFIED = "?"; + + @Setting("service-plugin") + @Comment("Services specified here can be implemented by plugins. To ensure that a" + + "specific plugin implements a given service, set the relevant option to its" + + "plugin ID. If you wish to use Sponge's default for a given service, use" + + "'sponge' as the ID.\n\n" + + "If the plugin ID is unknown, or the option is set to '?', all plugins will" + + "be given the opportunity to register their service. If multiple plugins" + + "attempt to register, one will be picked in an implementation dependent way." + + "If no plugins attempt to register a service, the Sponge default will be used" + + "if one exists.\n\n" + + "No Sponge default service exists for the Economy service.") private ServicePluginSubCategory servicePlugin = new ServicePluginSubCategory(); public ServicePluginSubCategory getServicePlugin() { @@ -50,20 +53,25 @@ public ServicePluginSubCategory getServicePlugin() { @ConfigSerializable public static final class ServicePluginSubCategory { - @Setting(value = "ban-service", comment = "Specifies the plugin that will provide the ban service") - private String banService = "?"; + @Setting("ban-service") + @Comment("Specifies the plugin that will provide the ban service") + private String banService = UNSPECIFIED; - @Setting(value = "economy-service", comment = "Specifies the plugin that will provide the economy service") - private String economyService = "?"; + @Setting("economy-service") + @Comment("Specifies the plugin that will provide the economy service") + private String economyService = UNSPECIFIED; - @Setting(value = "pagination-service", comment = "Specifies the plugin that will provide the pagination service") - private String paginationService = "?"; + @Setting("pagination-service") + @Comment("Specifies the plugin that will provide the pagination service") + private String paginationService = UNSPECIFIED; - @Setting(value = "permission-service", comment = "Specifies the plugin that will provide the permission service") - private String permissionService = "?"; + @Setting("permission-service") + @Comment("Specifies the plugin that will provide the permission service") + private String permissionService = UNSPECIFIED; - @Setting(value = "whitelist-service", comment = "Specifies the plugin that will provide the whitelist service") - private String whitelistService = "?"; + @Setting("whitelist-service") + @Comment("Specifies the plugin that will provide the whitelist service") + private String whitelistService = UNSPECIFIED; public String getBanService() { return this.banService; diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/SqlCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/SqlCategory.java index b984251bc1a..9576f4092ec 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/SqlCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/SqlCategory.java @@ -24,8 +24,9 @@ */ package org.spongepowered.common.applaunch.config.common; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; import java.util.HashMap; import java.util.Map; @@ -33,7 +34,8 @@ @ConfigSerializable public class SqlCategory { - @Setting(comment = "Aliases for SQL connections, in the format jdbc:protocol://[username[:password]@]host/database") + @Setting + @Comment("Aliases for SQL connections, in the format jdbc:protocol://[username[:password]@]host/database") private Map aliases = new HashMap<>(); public Map getAliases() { diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/StructureModCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/StructureModCategory.java index 9eb4ba0e617..e47ba3137d9 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/StructureModCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/StructureModCategory.java @@ -24,8 +24,9 @@ */ package org.spongepowered.common.applaunch.config.common; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; import java.util.HashMap; import java.util.Map; @@ -33,21 +34,23 @@ @ConfigSerializable public class StructureModCategory { - @Setting(value = "enabled", comment = "If 'false', this mod will never save its structures. This may\n" + @Setting("enabled") + @Comment("If 'false', this mod will never save its structures. This may\n" + "break some mod functionalities when requesting to locate their\n" + "structures in a World. If true, allows structures not overridden\n" + "in the section below to be saved by default. If you wish to find\n" + "a structure to prevent it being saved, enable 'auto-populate' and\n" + "restart the server/world instance.") private boolean isEnabled = true; - @Setting(value = "structures", comment = "Per structure override. Having the value of 'false' will prevent\n" + @Setting("structures") + @Comment("Per structure override. Having the value of 'false' will prevent\n" + "that specific named structure from saving.") private Map structureList = new HashMap<>(); public StructureModCategory() { } - public StructureModCategory(String modId) { + public StructureModCategory(final String modId) { if (modId.equals("minecraft")) { this.structureList.put("mineshaft", false); } diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/StructureSaveCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/StructureSaveCategory.java index f227dbab678..af4b5146f4d 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/StructureSaveCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/StructureSaveCategory.java @@ -24,8 +24,9 @@ */ package org.spongepowered.common.applaunch.config.common; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; import java.util.HashMap; import java.util.Map; @@ -33,20 +34,23 @@ @ConfigSerializable public class StructureSaveCategory { - @Setting(value = "enabled", comment = "If 'false', disables the modification to prevent certain structures\n" - + "from saving to the world's data folder. If you wish to prevent certain\n" - + "structures from saving, leave this \"enabled=true\". When \'true\', the\n" - + "modification allows for specific \'named\' structures to NOT be saved to\n" - + "disk. Examples of some structures that are costly and somewhat irrelivent\n" - + "is 'mineshaft's, as they build several structures and save, even after\n" - + "finished generating.") + @Setting("enabled") + @Comment("If 'false', disables the modification to prevent certain structures\n" + + "from saving to the world's data folder. If you wish to prevent certain\n" + + "structures from saving, leave this \"enabled=true\". When 'true', the\n" + + "modification allows for specific 'named' structures to NOT be saved to\n" + + "disk. Examples of some structures that are costly and somewhat irrelevant\n" + + "is 'mineshaft's, as they build several structures and save, even after\n" + + "finished generating.") private boolean isEnabled = false; - @Setting(value = "auto-populate", comment = "If 'true', newly discovered structures will be added to this config\n" - + "with a default value of \'true\'. This is useful for finding out\n" - + "potentially what structures are being saved from various mods, and\n" - + "allowing those structures to be selectively disabled.") + @Setting("auto-populate") + @Comment("If 'true', newly discovered structures will be added to this config\n" + + "with a default value of 'true'. This is useful for finding out\n" + + "potentially what structures are being saved from various mods, and\n" + + "allowing those structures to be selectively disabled.") private boolean autoPopulate = false; - @Setting(value = "mods", comment = "Per-mod overrides. Refer to the minecraft default mod for example.") + @Setting("mods") + @Comment("Per-mod overrides. Refer to the minecraft default mod for example.") private Map modList = new HashMap<>(); public StructureSaveCategory() { diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/TeleportHelperCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/TeleportHelperCategory.java index 050703d923b..9e6baf2efb0 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/TeleportHelperCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/TeleportHelperCategory.java @@ -24,8 +24,9 @@ */ package org.spongepowered.common.applaunch.config.common; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; import java.util.ArrayList; import java.util.List; @@ -33,18 +34,21 @@ @ConfigSerializable public class TeleportHelperCategory { - @Setting(value = "force-blacklist", comment = "If 'true', this blacklist will always be respected, otherwise, plugins can choose whether \n" - + "or not to respect it.") + @Setting("force-blacklist") + @Comment("If 'true', this blacklist will always be respected, otherwise, plugins can choose whether \n" + + "or not to respect it.") private boolean forceBlacklistOn = false; - @Setting(value = "unsafe-floor-block-ids", comment = "Block IDs that are listed here will not be selected by Sponge's safe \n" - + "teleport routine as a safe floor block.") + @Setting("unsafe-floor-block-ids") + @Comment("Block IDs that are listed here will not be selected by Sponge's safe \n" + + "teleport routine as a safe floor block.") private List unsafeFloorBlockIds = new ArrayList<>(); - @Setting(value = "unsafe-body-block-ids", comment = "Block IDs that are listed here will not be selected by Sponge's safe teleport routine as \n" - + "a safe block for players to warp into. \n" - + "You should only list blocks here that are incorrectly selected, solid blocks that prevent \n" - + "movement are automatically excluded.") + @Setting("unsafe-body-block-ids") + @Comment("Block IDs that are listed here will not be selected by Sponge's safe teleport routine as \n" + + "a safe block for players to warp into. \n" + + "You should only list blocks here that are incorrectly selected, solid blocks that prevent \n" + + "movement are automatically excluded.") private List unsafeBlockBlockIds = new ArrayList<>(); public boolean isForceBlacklistOn() { diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/TimingsCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/TimingsCategory.java index fdc0e18f854..0bc2fa1de8b 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/TimingsCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/TimingsCategory.java @@ -25,8 +25,8 @@ package org.spongepowered.common.applaunch.config.common; import com.google.common.collect.Lists; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; import java.util.List; @@ -55,7 +55,7 @@ public boolean isVerbose() { return this.verbose; } - public void setVerbose(boolean verbose) { + public void setVerbose(final boolean verbose) { this.verbose = verbose; } @@ -63,7 +63,7 @@ public boolean isEnabled() { return this.enabled; } - public void setEnabled(boolean enabled) { + public void setEnabled(final boolean enabled) { this.enabled = enabled; } @@ -79,7 +79,7 @@ public int getHistoryInterval() { return this.historyInterval; } - public void setHistoryInterval(int historyInterval) { + public void setHistoryInterval(final int historyInterval) { this.historyInterval = historyInterval; } @@ -87,7 +87,7 @@ public int getHistoryLength() { return this.historyLength; } - public void setHistoryLength(int historyLength) { + public void setHistoryLength(final int historyLength) { this.historyLength = historyLength; } diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/WorldCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/WorldCategory.java index 580f56b152c..f2c2348dbfe 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/common/WorldCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/common/WorldCategory.java @@ -24,8 +24,9 @@ */ package org.spongepowered.common.applaunch.config.common; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; import java.util.ArrayList; import java.util.List; @@ -34,20 +35,24 @@ @ConfigSerializable public final class WorldCategory { - @Setting(value = "auto-player-save-interval", comment = "The auto-save tick interval used when saving global player data. (Default: 6000) \n" + @Setting(value = "auto-player-save-interval") + @Comment("The auto-save tick interval used when saving global player data. (Default: 6000) \n" + "Note: 20 ticks is equivalent to 1 second. Set to 0 to disable.") private int autoPlayerSaveInterval = 6000; - @Setting(value = "leaf-decay", comment = "If 'true', natural leaf decay is allowed.") + @Setting(value = "leaf-decay") + @Comment("If 'true', natural leaf decay is allowed.") private boolean leafDecay = true; - @Setting(value = "gameprofile-lookup-task-interval", comment = "The interval, in seconds, used by the GameProfileQueryTask to process queued GameProfile requests. (Default: 4) \n" + @Setting(value = "gameprofile-lookup-task-interval") + @Comment("The interval, in seconds, used by the GameProfileQueryTask to process queued GameProfile requests. (Default: 4) \n" + "Note: This setting should be raised if you experience the following error: \n" + "\"The client has sent too many requests within a certain amount of time\". \n" + "Finally, if set to 0 or less, the default interval will be used.") private int gameProfileQueryTaskInterval = 4; - @Setting(value = "invalid-lookup-uuids", comment = "The list of uuid's that should never perform a lookup against Mojang's session server. \n" + @Setting(value = "invalid-lookup-uuids") + @Comment("The list of uuid's that should never perform a lookup against Mojang's session server. \n" + "Note: If you are using SpongeForge, make sure to enter any mod fake player's UUID to this list.") private List invalidLookupUuids = new ArrayList<>(); diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/core/Config.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/core/Config.java index adf09d6c2df..936ebc76613 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/core/Config.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/core/Config.java @@ -24,22 +24,11 @@ */ package org.spongepowered.common.applaunch.config.core; -import ninja.leaping.configurate.transformation.ConfigurationTransformation; +import org.spongepowered.configurate.ScopedConfigurationNode; +import org.spongepowered.configurate.transformation.ConfigurationTransformation; public interface Config { - ConfigurationTransformation EMPTY_VERSIONED = ConfigurationTransformation.versionedBuilder().build(); - - /** - * Path array builder. Will be removed in configurate 4.0. - * - * @param path path - * @return path - */ - static Object[] path(Object... path) { - return path; - } - /** * Get a transformation that will be applied to this configuration on load. * @@ -52,7 +41,7 @@ static Object[] path(Object... path) { * * @return A transformation instance */ - default ConfigurationTransformation getTransformation() { - return EMPTY_VERSIONED; + default > ConfigurationTransformation getTransformation() { + return ConfigurationTransformation.empty(); } } diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/core/ConfigHandle.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/core/ConfigHandle.java index 7712e10a68f..a662105ce1f 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/core/ConfigHandle.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/core/ConfigHandle.java @@ -26,16 +26,17 @@ import static java.util.Objects.requireNonNull; -import com.google.common.reflect.TypeToken; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.commented.CommentedConfigurationNode; -import ninja.leaping.configurate.loader.ConfigurationLoader; -import ninja.leaping.configurate.objectmapping.ObjectMapper; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; +import io.leangen.geantyref.TypeToken; +import org.spongepowered.configurate.ConfigurateException; +import org.spongepowered.configurate.ConfigurationNode; +import org.spongepowered.configurate.CommentedConfigurationNode; +import org.spongepowered.configurate.loader.ConfigurationLoader; +import org.spongepowered.configurate.objectmapping.ObjectMapper; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.Nullable; +import org.spongepowered.configurate.serialize.SerializationException; import java.io.IOException; import java.util.Iterator; @@ -74,13 +75,13 @@ public class ConfigHandle { * @implNote Default save suppression is {@code true}. * @param suppressed whether saves should be suppressed */ - public static void setSaveSuppressed(boolean suppressed) { + public static void setSaveSuppressed(final boolean suppressed) { ConfigHandle.saveSuppressed = suppressed; if (!suppressed && !ConfigHandle.saveQueue.isEmpty()) { for (final Iterator> it = ConfigHandle.saveQueue.iterator(); it.hasNext();) { try { it.next().doSave(); - } catch (IOException | ObjectMappingException ex) { + } catch (final ConfigurateException ex) { LOGGER.error("Unable to save a Sponge configuration!", ex); } it.remove(); @@ -88,27 +89,34 @@ public static void setSaveSuppressed(boolean suppressed) { } } + @SuppressWarnings("unchecked") + private static ObjectMapper.Mutable mutableMapper(final T instance) { + try { + final ObjectMapper mapper = SpongeConfigs.OBJECT_MAPPERS.get(instance.getClass()); + if (mapper instanceof ObjectMapper.Mutable) { + return (ObjectMapper.Mutable) mapper; + } + } catch (final SerializationException ex) { + throw new AssertionError(ex); + } + // object mapper classes are constant from compile onwards, this failure will always happen. + throw new AssertionError("Object mapper for " + instance + " was not mutable"); + } + protected final @Nullable ConfigurationLoader loader; - protected final ObjectMapper.BoundInstance mapper; + protected final ObjectMapper.Mutable mapper; + protected final T instance; protected @MonotonicNonNull CommentedConfigurationNode node; ConfigHandle(final T instance) { - try { - this.mapper = ObjectMapper.forObject(instance); - } catch (final ObjectMappingException ex) { - // object mapper classes are constant from compile onwards, this failure will always happen. - throw new AssertionError(ex); - } + this.mapper = mutableMapper(instance); + this.instance = instance; this.loader = null; } ConfigHandle(final T instance, final @Nullable ConfigurationLoader loader) { - try { - this.mapper = ObjectMapper.forObject(instance); - } catch (ObjectMappingException ex) { - // object mapper classes are constant from compile onwards, this failure will always happen. - throw new AssertionError(ex); - } + this.mapper = mutableMapper(instance); + this.instance = instance; this.loader = loader; } @@ -124,11 +132,11 @@ public boolean isAttached() { } public T get() { - return this.mapper.getInstance(); + return this.instance; } public CompletableFuture updateAndSave(final UnaryOperator updater) { - final T updated = requireNonNull(updater, "updater").apply(this.mapper.getInstance()); + final T updated = requireNonNull(updater, "updater").apply(this.instance); return asyncFailableFuture(() -> { // TODO: Force one save at a time this.save(); @@ -136,31 +144,31 @@ public CompletableFuture updateAndSave(final UnaryOperator updater) { }, ForkJoinPool.commonPool()); } - void load() throws IOException, ObjectMappingException { + void load() throws ConfigurateException { if (this.loader == null) { // we are virtual return; } this.node = this.loader.load(); this.doVersionUpdate(); - this.mapper.populate(this.node); + this.mapper.load(this.instance, this.node); this.doSave(); } - protected final void doVersionUpdate() { - final boolean wasEmpty = this.node.isEmpty(); - final CommentedConfigurationNode versionNode = this.node.getNode(VERSION_PATH); + protected final void doVersionUpdate() throws ConfigurateException { + final boolean wasEmpty = this.node.empty(); + final CommentedConfigurationNode versionNode = this.node.node(VERSION_PATH); final int existingVersion = versionNode.getInt(-1); - this.mapper.getInstance().getTransformation().apply(this.node); + this.instance.getTransformation().apply(this.node); final int newVersion = versionNode.getInt(-1); if (!wasEmpty && newVersion > existingVersion) { - LOGGER.info("Updated {} from version {} to {}", this.mapper.getInstance(), existingVersion, newVersion); + LOGGER.info("Updated {} from version {} to {}", this.instance, existingVersion, newVersion); } - versionNode.setCommentIfAbsent(VERSION_COMMENT); - this.node.getNode(VERSION_PATH).setValue(versionNode); // workaround for some weird issue, can remove @configurate 4.0 + versionNode.commentIfAbsent(VERSION_COMMENT); + this.node.node(VERSION_PATH).set(versionNode); } - public void reload() throws IOException, ObjectMappingException { + public void reload() throws ConfigurateException { // TODO: Something nicer? this.load(); } @@ -171,52 +179,52 @@ public final void save() { } else { try { doSave(); - } catch (final IOException | ObjectMappingException ex) { + } catch (final ConfigurateException ex) { LOGGER.error("Unable to save configuration to {}", this.loader, ex); } } } - protected void doSave() throws ObjectMappingException, IOException { + protected void doSave() throws ConfigurateException { if (this.loader == null) { return; } if (this.node == null) { - this.node = this.loader.createEmptyNode(); + this.node = this.loader.createNode(); } - this.mapper.serialize(this.node); + this.mapper.save(this.instance, this.node); this.loader.save(this.node); } - @Nullable - private CommentedConfigurationNode getSetting(String key) { + private @Nullable CommentedConfigurationNode getSetting(final String key) { if (key.equalsIgnoreCase("config-enabled")) { - return this.node.getNode(key); + return this.node.node(key); } else if (!key.contains(".") || key.indexOf('.') == key.length() - 1) { return null; } else { - CommentedConfigurationNode node = this.node; + final CommentedConfigurationNode node = this.node; final String[] split = key.split("\\."); - return node.getNode((Object[]) split); + return node.node((Object[]) split); } } - public CompletableFuture updateSetting(String key, Object value) { + public CompletableFuture updateSetting(final String key, final Object value) { return asyncFailableFuture(() -> { - CommentedConfigurationNode upd = this.getSetting(key); - this.mapper.populate(this.node); + final CommentedConfigurationNode upd = this.getSetting(key); + upd.set(value); + this.mapper.load(this.instance, this.node); this.save(); return upd; }, ForkJoinPool.commonPool()); } - public CompletableFuture updateSetting(String key, V value, TypeToken token) { + public CompletableFuture updateSetting(final String key, final V value, final TypeToken token) { return asyncFailableFuture(() -> { - CommentedConfigurationNode upd = this.getSetting(key); - upd.setValue(token, value); - this.mapper.populate(this.node); + final CommentedConfigurationNode upd = this.getSetting(key); + upd.set(token, value); + this.mapper.load(this.instance, this.node); this.save(); return upd; }, ForkJoinPool.commonPool()); @@ -227,7 +235,7 @@ private static CompletableFuture asyncFailableFuture(final Callable ac executor.execute(() -> { try { future.complete(action.call()); - } catch (Exception ex) { + } catch (final Exception ex) { future.completeExceptionally(ex); } }); diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/core/DuplicateRemovalVisitor.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/core/DuplicateRemovalVisitor.java index a6390e25863..6d2690f81e3 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/core/DuplicateRemovalVisitor.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/core/DuplicateRemovalVisitor.java @@ -24,9 +24,9 @@ */ package org.spongepowered.common.applaunch.config.core; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.ConfigurationVisitor; -import ninja.leaping.configurate.Types; +import org.spongepowered.configurate.ConfigurationNode; +import org.spongepowered.configurate.ConfigurationVisitor; +import org.spongepowered.configurate.serialize.Scalars; import java.util.Objects; import java.util.concurrent.atomic.AtomicReference; @@ -55,7 +55,7 @@ public AtomicReference newState() { } private boolean isListElement(final ConfigurationNode node) { - return node.getParent() != null && node.getParent().isList(); + return node.parent() != null && node.parent().isList(); } @Override @@ -65,8 +65,8 @@ public void beginVisit(final ConfigurationNode node, final AtomicReference parent) { - if (node.getParent() != null) { // exclude root nodes - parent.set(parent.get().getNode(node.getKey())); + if (node.parent() != null) { // exclude root nodes + parent.set(parent.get().node(node.key())); } } @@ -76,8 +76,8 @@ public void enterMappingNode(final ConfigurationNode node, final AtomicReference @Override public void enterListNode(final ConfigurationNode node, final AtomicReference parent) { - if (!this.isListElement(node) && Objects.equals(node.getValue(), parent.get().getValue())) { - node.setValue(null); + if (!this.isListElement(node) && Objects.equals(node.raw(), parent.get().raw())) { + node.raw(null); } } @@ -91,17 +91,17 @@ public void enterScalarNode(final ConfigurationNode node, final AtomicReference< } // if the node already exists in the parent config, remove it - if (Objects.equals(node.getValue(), parentNode.getValue())) { - node.setValue(null); + if (Objects.equals(node.raw(), parentNode.raw())) { + node.raw(null); return; } // Fix double bug - final Double nodeVal = node.getValue(Types::asDouble); + final Double nodeVal = Scalars.DOUBLE.tryDeserialize(node.raw()); if (nodeVal != null) { - final Double parentVal = parentNode.getValue(Types::asDouble); + final Double parentVal = Scalars.DOUBLE.tryDeserialize(parentNode.raw()); if (parentVal == null && nodeVal.doubleValue() == 0 || (parentVal != null && nodeVal.doubleValue() == parentVal.doubleValue())) { - node.setValue(null); + node.raw(null); } } } @@ -111,16 +111,16 @@ public void exitMappingNode(final ConfigurationNode node, final AtomicReference< this.popParent(parent); // remove empty maps - if (node.isEmpty() && !this.isListElement(node)) { - node.setValue(null); + if (node.empty() && !this.isListElement(node)) { + node.raw(null); } } @Override public void exitListNode(final ConfigurationNode node, final AtomicReference parent) { final ConfigurationNode parentNode = this.popParent(parent); - if (parentNode.isEmpty() && node.isEmpty()) { - node.setValue(null); + if (parentNode.empty() && node.empty()) { + node.raw(null); } } @@ -131,8 +131,8 @@ public Void endVisit(final AtomicReference parent) { private ConfigurationNode popParent(final AtomicReference parentRef) { final ConfigurationNode parent = parentRef.get(); - if (parent.getParent() != null) { - parentRef.set(parent.getParent()); + if (parent.parent() != null) { + parentRef.set(parent.parent()); } return parent; } diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/core/FileMovingConfigurationTransformation.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/core/FileMovingConfigurationTransformation.java index 1ce31485b06..4719f0ebde3 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/core/FileMovingConfigurationTransformation.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/core/FileMovingConfigurationTransformation.java @@ -25,50 +25,47 @@ package org.spongepowered.common.applaunch.config.core; import com.google.common.collect.ImmutableSet; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.loader.ConfigurationLoader; -import ninja.leaping.configurate.transformation.ConfigurationTransformation; +import org.spongepowered.configurate.ConfigurateException; +import org.spongepowered.configurate.ConfigurationNode; +import org.spongepowered.configurate.loader.ConfigurationLoader; +import org.spongepowered.configurate.transformation.ConfigurationTransformation; import org.checkerframework.checker.nullness.qual.NonNull; +import org.spongepowered.configurate.transformation.NodePath; -import java.io.IOException; import java.util.Set; /** * A transformation that moves a set of entries from the loaded file into another file. */ -public class FileMovingConfigurationTransformation extends ConfigurationTransformation { - private final Set paths; +public class FileMovingConfigurationTransformation implements ConfigurationTransformation { + private final Set paths; private final ConfigurationLoader destinationLoader; private final boolean override; - public FileMovingConfigurationTransformation(final Set paths, final ConfigurationLoader destinationLoader, final boolean override) { + public FileMovingConfigurationTransformation(final Set paths, final ConfigurationLoader destinationLoader, final boolean override) { this.paths = ImmutableSet.copyOf(paths); this.destinationLoader = destinationLoader; this.override = override; } @Override - public void apply(final @NonNull ConfigurationNode oldConfig) { - try { - final ConfigurationNode newConfig = this.destinationLoader.load(); - boolean acted = false; - for (final Object[] path : this.paths) { - final ConfigurationNode source = oldConfig.getNode(path); - if (!source.isVirtual()) { - acted = true; - if (override) { - newConfig.getNode(path).setValue(source); - } else { - newConfig.getNode(path).mergeValuesFrom(source); - } - source.setValue(null); + public void apply(final @NonNull ConfigurationNode oldConfig) throws ConfigurateException { + final ConfigurationNode newConfig = this.destinationLoader.load(); + boolean acted = false; + for (final NodePath path : this.paths) { + final ConfigurationNode source = oldConfig.node(path); + if (!source.virtual()) { + acted = true; + if (this.override) { + newConfig.node(path).from(source); + } else { + newConfig.node(path).mergeFrom(source); } + source.raw(null); } - if (acted) { - this.destinationLoader.save(newConfig); - } - } catch (final IOException ex) { - SpongeConfigs.LOGGER.error("Unable to save destination configuration while migrating {}", oldConfig, ex); + } + if (acted) { + this.destinationLoader.save(newConfig); } } } diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/core/InheritableConfigHandle.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/core/InheritableConfigHandle.java index 2c69809fec3..daff8023faa 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/core/InheritableConfigHandle.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/core/InheritableConfigHandle.java @@ -24,9 +24,9 @@ */ package org.spongepowered.common.applaunch.config.core; -import ninja.leaping.configurate.commented.CommentedConfigurationNode; -import ninja.leaping.configurate.loader.ConfigurationLoader; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; +import org.spongepowered.configurate.CommentedConfigurationNode; +import org.spongepowered.configurate.ConfigurateException; +import org.spongepowered.configurate.loader.ConfigurationLoader; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.common.applaunch.config.inheritable.BaseConfig; @@ -67,7 +67,7 @@ public InheritableConfigHandle(final T instance, * @param value type * @return value or default */ - public V getOrCreateValue(final Function getter, final Consumer setter, boolean populate) { + public V getOrCreateValue(final Function getter, final Consumer setter, final boolean populate) { V ret = getter.apply(this.get()); if (ret == null && populate) { setter.accept(this.get()); @@ -79,7 +79,7 @@ public V getOrCreateValue(final Function getter, final Consumer node - this.mapper.serialize(this.node); + this.mapper.save(this.instance, this.node); // before saving this config, remove any values already declared with the same value on the parent if (this.parent != null) { @@ -129,7 +129,7 @@ public void doSave() { if (this.parent != null) { this.parent.doSave(); } - } catch (IOException | ObjectMappingException e) { + } catch (final ConfigurateException e) { SpongeConfigs.LOGGER.error("Failed to save configuration", e); } } @@ -140,7 +140,7 @@ public void doSave() { * * @param root The node to process */ - private void removeDuplicates(CommentedConfigurationNode root) { + private void removeDuplicates(final CommentedConfigurationNode root) { if (!this.isAttached()) { return; } diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/core/SpongeConfigs.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/core/SpongeConfigs.java index 7f1bc217cbb..3974be91d0b 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/core/SpongeConfigs.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/core/SpongeConfigs.java @@ -24,15 +24,17 @@ */ package org.spongepowered.common.applaunch.config.core; -import ninja.leaping.configurate.ConfigurationOptions; -import ninja.leaping.configurate.hocon.HoconConfigurationLoader; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; +import org.spongepowered.configurate.ConfigurateException; +import org.spongepowered.configurate.ConfigurationOptions; +import org.spongepowered.configurate.hocon.HoconConfigurationLoader; +import org.spongepowered.configurate.objectmapping.ObjectMapper; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.spongepowered.common.applaunch.config.common.CommonConfig; import org.spongepowered.common.applaunch.config.inheritable.GlobalConfig; import org.spongepowered.common.applaunch.config.inheritable.WorldConfig; +import org.spongepowered.configurate.objectmapping.meta.NodeResolver; import org.spongepowered.plugin.Blackboard; import org.spongepowered.plugin.PluginEnvironment; import org.spongepowered.plugin.PluginKeys; @@ -57,10 +59,16 @@ public class SpongeConfigs { + "# Discord: https://discord.gg/sponge\n" + "# Forums: https://forums.spongepowered.org/\n"; + static final ObjectMapper.Factory OBJECT_MAPPERS = ObjectMapper.factoryBuilder() + .addNodeResolver(NodeResolver.onlyWithSetting()) + .build(); + static final ConfigurationOptions OPTIONS = ConfigurationOptions.defaults() - .withHeader(HEADER) - .withShouldCopyDefaults(true) - .withSerializers(collection -> collection.register(TokenHoldingString.SERIALIZER)); + .header(HEADER) + .shouldCopyDefaults(true) + .implicitInitialization(true) + .serializers(collection -> collection.register(TokenHoldingString.SERIALIZER) + .registerAnnotatedObjects(OBJECT_MAPPERS)); static final Logger LOGGER = LogManager.getLogger(); @@ -129,8 +137,8 @@ public static HoconConfigurationLoader createLoader(final Path path) { } return HoconConfigurationLoader.builder() - .setPath(path) - .setDefaultOptions(OPTIONS) + .path(path) + .defaultOptions(OPTIONS) .build(); } @@ -140,7 +148,7 @@ public static ConfigHandle create(final T instance, final final ConfigHandle handle = new ConfigHandle<>(instance, loader); handle.load(); return handle; - } catch (final IOException | ObjectMappingException ex) { + } catch (final ConfigurateException ex) { LOGGER.error("Unable to load configuration {}. Sponge will operate in " + "fallback mode, with default configuration options and will not write to the invalid file", fileName, ex); return new ConfigHandle<>(instance); @@ -156,7 +164,7 @@ public static InheritableConfigHandle getGlobalInheritable() { global = new InheritableConfigHandle<>(new GlobalConfig(), createLoader(getDirectory().resolve(GlobalConfig.FILE_NAME)), null); global.load(); - } catch (IOException | ObjectMappingException e) { + } catch (final ConfigurateException e) { LOGGER.error("Unable to load global world configuration in {}. Sponge will run with default settings", GlobalConfig.FILE_NAME, e); global = new InheritableConfigHandle<>(new GlobalConfig(), null); } diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/core/TokenHoldingString.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/core/TokenHoldingString.java index d46d0bd735a..d65ea4ed22a 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/core/TokenHoldingString.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/core/TokenHoldingString.java @@ -24,13 +24,12 @@ */ package org.spongepowered.common.applaunch.config.core; -import com.google.common.reflect.TypeToken; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; -import ninja.leaping.configurate.objectmapping.serialize.ScalarSerializer; +import org.spongepowered.configurate.serialize.ScalarSerializer; import org.spongepowered.plugin.Blackboard; import org.spongepowered.plugin.PluginEnvironment; import org.spongepowered.plugin.PluginKeys; +import java.lang.reflect.Type; import java.nio.file.Path; import java.util.Collections; import java.util.HashMap; @@ -132,12 +131,12 @@ static class Serializer extends ScalarSerializer { } @Override - public TokenHoldingString deserialize(TypeToken type, Object obj) throws ObjectMappingException { + public TokenHoldingString deserialize(final Type type, final Object obj) { return TokenHoldingString.of(obj.toString()); } @Override - public Object serialize(TokenHoldingString item, Predicate> typeSupported) { + public Object serialize(final TokenHoldingString item, final Predicate> typeSupported) { return item.getPlain(); } diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/BaseConfig.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/BaseConfig.java index 9243e08a71f..2e2e460835a 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/BaseConfig.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/BaseConfig.java @@ -24,9 +24,12 @@ */ package org.spongepowered.common.applaunch.config.inheritable; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.transformation.ConfigurationTransformation; +import org.spongepowered.configurate.ScopedConfigurationNode; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.transformation.ConfigurationTransformation; import org.spongepowered.common.applaunch.config.core.Config; +import org.spongepowered.configurate.transformation.NodePath; import java.util.ArrayList; import java.util.List; @@ -35,22 +38,24 @@ public abstract class BaseConfig implements Config { @Setting protected WorldCategory world = new WorldCategory(); - @Setting(value = "player-block-tracker") + @Setting private PlayerBlockTracker playerBlockTracker = new PlayerBlockTracker(); - @Setting(value = "entity") + @Setting private EntityCategory entity = new EntityCategory(); - @Setting(value = "entity-activation-range") + @Setting("entity-activation-range") private EntityActivationRangeCategory entityActivationRange = new EntityActivationRangeCategory(); - @Setting(value = "entity-collisions") + @Setting("entity-collisions") private EntityCollisionCategory entityCollisionCategory = new EntityCollisionCategory(); @Setting private LoggingCategory logging = new LoggingCategory(); - @Setting(value = "spawner", comment = "Used to control spawn limits around players. \n" - + "Note: The radius uses the lower value of mob spawn range and server's view distance.") + @Setting("spawner") + @Comment("Used to control spawn limits around players. \n" + + "Note: The radius uses the lower value of mob spawn range and server's view distance.") private SpawnerCategory spawner = new SpawnerCategory(); - @Setting(value = "tileentity-activation") + @Setting("tileentity-activation") private BlockEntityActivationCategory blockEntityActivationCategory = new BlockEntityActivationCategory(); - @Setting(value = "world-generation-modifiers", comment = "World Generation Modifiers to apply to the world") + @Setting("world-generation-modifiers") + @Comment("World Generation Modifiers to apply to the world") private final List worldModifiers = new ArrayList<>(); @Setting("movement-checks") private MovementChecksCategory movementChecks = new MovementChecksCategory(); @@ -96,7 +101,7 @@ public MovementChecksCategory getMovementChecks() { } @Override - public ConfigurationTransformation getTransformation() { + public > ConfigurationTransformation getTransformation() { return ConfigurationTransformation.versionedBuilder() .addVersion(2, this.buildOneToTwo()) // move everything out of sponge subcategory @@ -106,8 +111,8 @@ public ConfigurationTransformation getTransformation() { protected ConfigurationTransformation buildOneToTwo() { return ConfigurationTransformation.builder() - .addAction(new Object[] { "world", "portal-agents" }, (path, value) -> { - value.setValue(null); + .addAction(NodePath.path("world", "portal-agents"), (path, value) -> { + value.set(null); return null; }) .build(); @@ -115,7 +120,7 @@ protected ConfigurationTransformation buildOneToTwo() { protected ConfigurationTransformation buildInitialToOne() { return ConfigurationTransformation.builder() - .addAction(new Object[] {"sponge"}, (path, value) -> new Object[0]) + .addAction(NodePath.path("sponge"), (path, value) -> new Object[0]) .build(); } } diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/BlockEntityActivationCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/BlockEntityActivationCategory.java index 62b239f4948..4da0d6f2097 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/BlockEntityActivationCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/BlockEntityActivationCategory.java @@ -24,8 +24,10 @@ */ package org.spongepowered.common.applaunch.config.inheritable; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; + +import org.spongepowered.configurate.objectmapping.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; import java.util.HashMap; import java.util.Map; @@ -33,13 +35,17 @@ @ConfigSerializable public final class BlockEntityActivationCategory { - @Setting(value = "auto-populate", comment = "If 'true', newly discovered block entities will be added to this config with default settings.") + @Setting + @Comment("If 'true', newly discovered block entities will be added to this config with default settings.") private boolean autoPopulate = false; - @Setting(value = "default-block-range", comment = "Default activation block range used for all block entities unless overridden.") + @Setting + @Comment("Default activation block range used for all block entities unless overridden.") private int defaultBlockRange = 64; - @Setting(value = "default-tick-rate", comment = "Default tick rate used for all block entities unless overridden.") + @Setting + @Comment("Default tick rate used for all block entities unless overridden.") private int defaultTickRate = 1; - @Setting(value = "mods", comment = "Per-mod overrides. Refer to the minecraft default mod for example.") + @Setting("mods") + @Comment("Per-mod overrides. Refer to the minecraft default mod for example.") private Map modList = new HashMap<>(); public BlockEntityActivationCategory() { diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/BlockEntityActivationModCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/BlockEntityActivationModCategory.java index 9f90f5d95a1..903ba9ec6c6 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/BlockEntityActivationModCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/BlockEntityActivationModCategory.java @@ -24,8 +24,9 @@ */ package org.spongepowered.common.applaunch.config.inheritable; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; import java.util.HashMap; import java.util.Map; @@ -33,21 +34,22 @@ @ConfigSerializable public final class BlockEntityActivationModCategory { - @Setting(value = "enabled", comment = "If 'false', tileentity activation rules for this mod will be ignored and always tick.") - private boolean isEnabled = true; - @Setting(value = "default-block-range") + @Setting + @Comment("If 'false', tileentity activation rules for this mod will be ignored and always tick.") + private boolean enabled = true; + @Setting private Integer defaultBlockRange; - @Setting(value = "default-tick-rate") + @Setting private Integer defaultTickRate; - @Setting(value = "block-range") + @Setting("block-range") private Map tileEntityRangeList = new HashMap<>(); - @Setting(value = "tick-rate") + @Setting("tick-rate") private Map tileEntityTickRateList = new HashMap<>(); public BlockEntityActivationModCategory() { } - public BlockEntityActivationModCategory(String modId) { + public BlockEntityActivationModCategory(final String modId) { if (modId.equalsIgnoreCase("computercraft")) { this.tileEntityRangeList.put("advanced_modem", 0); this.tileEntityRangeList.put("ccprinter", 0); @@ -61,7 +63,7 @@ public BlockEntityActivationModCategory(String modId) { } public boolean isEnabled() { - return this.isEnabled; + return this.enabled; } public Integer getDefaultBlockRange() { diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/CollisionModCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/CollisionModCategory.java index 055e87b7536..2c128595d3a 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/CollisionModCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/CollisionModCategory.java @@ -24,8 +24,9 @@ */ package org.spongepowered.common.applaunch.config.inheritable; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; import java.util.HashMap; import java.util.Map; @@ -33,13 +34,15 @@ @ConfigSerializable public final class CollisionModCategory { - @Setting(value = "enabled", comment = "If 'false', entity collision rules for this mod will be ignored.") - private boolean isEnabled = true; - @Setting(value = "defaults", comment = "Default maximum collisions used for all entities/blocks unless overridden.") + @Setting("enabled") + @Comment("If 'false', entity collision rules for this mod will be ignored.") + private boolean enabled = true; + @Setting("defaults") + @Comment("Default maximum collisions used for all entities/blocks unless overridden.") private Map defaultMaxCollisions = new HashMap<>(); - @Setting(value = "blocks") + @Setting("blocks") private Map blockList = new HashMap<>(); - @Setting(value = "entities") + @Setting("entities") private Map entityList = new HashMap<>(); public CollisionModCategory() { @@ -47,7 +50,7 @@ public CollisionModCategory() { this.defaultMaxCollisions.put("entities", 8); } - public CollisionModCategory(String modId) { + public CollisionModCategory(final String modId) { if (modId.equals("minecraft")) { this.blockList.put("detector_rail", 1); this.blockList.put("heavy_weighted_pressure_plate", 150); @@ -64,7 +67,7 @@ public CollisionModCategory(String modId) { } public boolean isEnabled() { - return this.isEnabled; + return this.enabled; } public Map getDefaultMaxCollisions() { diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/EntityActivationModCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/EntityActivationModCategory.java index 5d692b212ca..6d1c48048ba 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/EntityActivationModCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/EntityActivationModCategory.java @@ -24,8 +24,9 @@ */ package org.spongepowered.common.applaunch.config.inheritable; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; import java.util.HashMap; import java.util.Map; @@ -33,11 +34,12 @@ @ConfigSerializable public final class EntityActivationModCategory { - @Setting(value = "enabled", comment = "If 'false', entity activation rules for this mod will be ignored and always tick.") + @Setting("enabled") + @Comment("If 'false', entity activation rules for this mod will be ignored and always tick.") private boolean isEnabled = true; - @Setting(value = "defaults") + @Setting("defaults") private Map defaultRanges = new HashMap<>(); - @Setting(value = "entities") + @Setting("entities") private Map entityList = new HashMap<>(); public boolean isEnabled() { diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/EntityActivationRangeCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/EntityActivationRangeCategory.java index 22cadd05bbc..4cd3995d006 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/EntityActivationRangeCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/EntityActivationRangeCategory.java @@ -24,8 +24,9 @@ */ package org.spongepowered.common.applaunch.config.inheritable; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; import java.util.HashMap; import java.util.Map; @@ -33,11 +34,14 @@ @ConfigSerializable public final class EntityActivationRangeCategory { - @Setting(value = "auto-populate", comment = "If 'true', newly discovered entities will be added to this config with a default value.") + @Setting + @Comment("If 'true', newly discovered entities will be added to this config with a default value.") private boolean autoPopulate = false; - @Setting(value = "defaults", comment = "Default activation ranges used for all entities unless overridden.") + @Setting("defaults") + @Comment("Default activation ranges used for all entities unless overridden.") private Map defaultRanges = new HashMap<>(); - @Setting(value = "mods", comment = "Per-mod overrides. Refer to the minecraft default mod for example.") + @Setting("mods") + @Comment("Per-mod overrides. Refer to the minecraft default mod for example.") private Map modList = new HashMap<>(); public EntityActivationRangeCategory() { diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/EntityCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/EntityCategory.java index 98bfc1b5446..3212bb0bd73 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/EntityCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/EntityCategory.java @@ -24,39 +24,46 @@ */ package org.spongepowered.common.applaunch.config.inheritable; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; @ConfigSerializable public final class EntityCategory { - @Setting(value = "max-bounding-box-size", comment = "Maximum size of an entity's bounding box before removing it. Set to 0 to disable") + @Setting + @Comment("Maximum size of an entity's bounding box before removing it. Set to 0 to disable") private int maxBoundingBoxSize = 1000; - @Setting(value = "collision-warn-size", - comment = "Number of colliding entities in one spot before logging a warning. Set to 0 to disable") + @Setting("collision-warn-size") + @Comment("Number of colliding entities in one spot before logging a warning. Set to 0 to disable") private int maxCollisionSize = 200; - @Setting(value = "max-speed", comment = "Square of the maximum speed of an entity before removing it. Set to 0 to disable") + @Setting + @Comment("Square of the maximum speed of an entity before removing it. Set to 0 to disable") private int maxSpeed = 100; - @Setting(value = "item-despawn-rate", comment = "Controls the time in ticks for when an item despawns.") + @Setting + @Comment("Controls the time in ticks for when an item despawns.") private int itemDespawnRate = 6000; - @Setting(value = "human-player-list-remove-delay", - comment = "Number of ticks before the fake player entry of a human is removed from the tab list (range of 0 to 100 ticks).") + @Setting + @Comment("Number of ticks before the fake player entry of a human is removed from the tab list (range of 0 to 100 ticks).") private int humanPlayerListRemoveDelay = 10; - @Setting(value = "entity-painting-respawn-delay", - comment = "Number of ticks before a painting is respawned on clients when their art is changed") + @Setting("entity-painting-respawn-delay") + @Comment("Number of ticks before a painting is respawned on clients when their art is changed") private int paintingRespawnDelaly = 2; - @Setting(value = "living-soft-despawn-range", comment = "The lower bounded range where living entities near a player may potentially despawn") + @Setting("living-soft-despawn-range") + @Comment("The lower bounded range where living entities near a player may potentially despawn") private int softDespawnRange = 32; - @Setting(value = "living-hard-despawn-range", comment = "The upper bounded range where living entities farther from a player will likely despawn") + @Setting("living-hard-despawn-range") + @Comment("The upper bounded range where living entities farther from a player will likely despawn") private int hardDespawnRange = 128; - @Setting(value = "living-soft-despawn-minimum-life", comment = "The amount of seconds before a living entity between the soft and hard despawn ranges from a player to be considered for despawning") + @Setting("living-soft-despawn-minimum-life") + @Comment("The amount of seconds before a living entity between the soft and hard despawn ranges from a player to be considered for despawning") private int minimumLife = 30; public int getMaxSpeed() { return this.maxSpeed; } - public void setMaxSpeed(int maxSpeed) { + public void setMaxSpeed(final int maxSpeed) { this.maxSpeed = maxSpeed; } @@ -64,7 +71,7 @@ public int getMaxBoundingBoxSize() { return this.maxBoundingBoxSize; } - public void setMaxBoundingBoxSize(int maxBoundingBoxSize) { + public void setMaxBoundingBoxSize(final int maxBoundingBoxSize) { this.maxBoundingBoxSize = maxBoundingBoxSize; } @@ -72,7 +79,7 @@ public int getMaxCollisionSize() { return this.maxCollisionSize; } - public void setMaxCollisionSize(int maxCollisionSize) { + public void setMaxCollisionSize(final int maxCollisionSize) { this.maxCollisionSize = maxCollisionSize; } @@ -80,7 +87,7 @@ public int getItemDespawnRate() { return this.itemDespawnRate; } - public void setItemDespawnRate(int itemDespawnRate) { + public void setItemDespawnRate(final int itemDespawnRate) { this.itemDespawnRate = itemDespawnRate; } @@ -88,7 +95,7 @@ public int getHumanPlayerListRemoveDelay() { return this.humanPlayerListRemoveDelay; } - public void setHumanPlayerListRemoveDelay(int delay) { + public void setHumanPlayerListRemoveDelay(final int delay) { this.humanPlayerListRemoveDelay = Math.max(0, Math.min(delay, 100)); } @@ -96,7 +103,7 @@ public int getPaintingRespawnDelay() { return this.paintingRespawnDelaly; } - public void setPaintingRespawnDelaly(int paintingRespawnDelaly) { + public void setPaintingRespawnDelaly(final int paintingRespawnDelaly) { this.paintingRespawnDelaly = Math.min(paintingRespawnDelaly, 1); } @@ -104,7 +111,7 @@ public int getSoftDespawnRange() { return this.softDespawnRange; } - public void setSoftDespawnRange(int softDespawnRange) { + public void setSoftDespawnRange(final int softDespawnRange) { this.softDespawnRange = Math.min(softDespawnRange, 10); } @@ -112,7 +119,7 @@ public int getHardDespawnRange() { return this.hardDespawnRange; } - public void setHardDespawnRange(int hardDespawnRange) { + public void setHardDespawnRange(final int hardDespawnRange) { this.hardDespawnRange = Math.min(hardDespawnRange, 10); } diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/EntityCollisionCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/EntityCollisionCategory.java index 285645ce70c..e9553b0de40 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/EntityCollisionCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/EntityCollisionCategory.java @@ -24,8 +24,9 @@ */ package org.spongepowered.common.applaunch.config.inheritable; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; import java.util.HashMap; import java.util.Map; @@ -33,13 +34,16 @@ @ConfigSerializable public final class EntityCollisionCategory { - @Setting(value = "auto-populate", comment = "If 'true', newly discovered entities/blocks will be added to this config with a default value.") + @Setting("auto-populate") + @Comment("If 'true', newly discovered entities/blocks will be added to this config with a default value.") private boolean autoPopulate = false; - @Setting(value = "max-entities-within-aabb", comment = "Maximum amount of entities any given entity or block can collide with. This improves \n" - + "performance when there are more than 8 entities on top of each other such as a 1x1 \n" - + "spawn pen. Set to 0 to disable.") + @Setting("max-entities-within-aabb") + @Comment("Maximum amount of entities any given entity or block can collide with. This improves \n" + + "performance when there are more than 8 entities on top of each other such as a 1x1 \n" + + "spawn pen. Set to 0 to disable.") private int maxEntitiesWithinAABB = 8; - @Setting(value = "mods", comment = "Per-mod overrides. Refer to the minecraft default mod for example.") + @Setting("mods") + @Comment("Per-mod overrides. Refer to the minecraft default mod for example.") private Map modList = new HashMap<>(); public EntityCollisionCategory() { @@ -59,7 +63,7 @@ public int getMaxEntitiesWithinAABB() { return this.maxEntitiesWithinAABB; } - public void setMaxEntitiesWithinAABB(int maxEntities) { + public void setMaxEntitiesWithinAABB(final int maxEntities) { this.maxEntitiesWithinAABB = maxEntities; } } diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/GlobalConfig.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/GlobalConfig.java index 1463e9cd0ba..f82f8deb0d4 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/GlobalConfig.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/GlobalConfig.java @@ -25,10 +25,11 @@ package org.spongepowered.common.applaunch.config.inheritable; import com.google.common.collect.ImmutableSet; -import ninja.leaping.configurate.transformation.ConfigurationTransformation; +import org.spongepowered.configurate.transformation.ConfigurationTransformation; import org.spongepowered.common.applaunch.config.core.FileMovingConfigurationTransformation; import org.spongepowered.common.applaunch.config.core.SpongeConfigs; import org.spongepowered.common.applaunch.config.common.CommonConfig; +import org.spongepowered.configurate.transformation.NodePath; import java.util.Set; @@ -36,36 +37,32 @@ public final class GlobalConfig extends BaseConfig { public static final String FILE_NAME = "global.conf"; - private static Object[] p(final Object... els) { - return els; - } - // Paths moved to sponge.conf - private static final Set MIGRATE_SPONGE_PATHS = ImmutableSet.of( - p("world", "auto-player-save-interval"), - p("world", "leaf-decay"), - p("world", "game-profile-query-task-interval"), - p("world", "invalid-lookup-uuids"), - p("general"), - p("sql"), - p("commands"), - p("permission"), - p("modules"), - p("ip-sets"), - p("bungeecord"), - p("exploits"), - p("optimizations"), - p("cause-tracker"), - p("teleport-helper"), - p("broken-mods"), - p("service-registration"), - p("debug"), - p("timings") + private static final Set MIGRATE_SPONGE_PATHS = ImmutableSet.of( + NodePath.path("world", "auto-player-save-interval"), + NodePath.path("world", "leaf-decay"), + NodePath.path("world", "game-profile-query-task-interval"), + NodePath.path("world", "invalid-lookup-uuids"), + NodePath.path("general"), + NodePath.path("sql"), + NodePath.path("commands"), + NodePath.path("permission"), + NodePath.path("modules"), + NodePath.path("ip-sets"), + NodePath.path("bungeecord"), + NodePath.path("exploits"), + NodePath.path("optimizations"), + NodePath.path("cause-tracker"), + NodePath.path("teleport-helper"), + NodePath.path("broken-mods"), + NodePath.path("service-registration"), + NodePath.path("debug"), + NodePath.path("timings") ); // Paths moved to metrics.conf - private static final Set MIGRATE_METRICS_PATHS = ImmutableSet.of( - p("metrics") + private static final Set MIGRATE_METRICS_PATHS = ImmutableSet.of( + NodePath.path("metrics") ); public GlobalConfig() { diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/LoggingCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/LoggingCategory.java index 3dcf6ad90a9..bc58c24df4e 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/LoggingCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/LoggingCategory.java @@ -24,50 +24,67 @@ */ package org.spongepowered.common.applaunch.config.inheritable; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; @ConfigSerializable public final class LoggingCategory { - @Setting(value = "block-break", comment = "Log when blocks are broken") + @Setting("block-break") + @Comment("Log when blocks are broken") private boolean blockBreakLogging = false; - @Setting(value = "block-modify", comment = "Log when blocks are modified") + @Setting("block-modify") + @Comment("Log when blocks are modified") private boolean blockModifyLogging = false; - @Setting(value = "block-place", comment = "Log when blocks are placed") + @Setting("block-place") + @Comment("Log when blocks are placed") private boolean blockPlaceLogging = false; - @Setting(value = "block-populate", comment = "Log when blocks are populated in a chunk") + @Setting("block-populate") + @Comment("Log when blocks are populated in a chunk") private boolean blockPopulateLogging = false; - @Setting(value = "block-tracking", comment = "Log when blocks are placed by players and tracked") + @Setting("block-tracking") + @Comment("Log when blocks are placed by players and tracked") private boolean blockTrackLogging = false; - @Setting(value = "chunk-load", comment = "Log when chunks are loaded") + @Setting("chunk-load") + @Comment("Log when chunks are loaded") private boolean chunkLoadLogging = false; - @Setting(value = "chunk-unload", comment = "Log when chunks are unloaded") + @Setting("chunk-unload") + @Comment("Log when chunks are unloaded") private boolean chunkUnloadLogging = false; - @Setting(value = "chunk-gc-queue-unload", comment = "Log when chunks are queued to be unloaded by the chunk garbage collector.") + @Setting("chunk-gc-queue-unload") + @Comment("Log when chunks are queued to be unloaded by the chunk garbage collector.") private boolean chunkGCQueueUnloadLogging = false; - @Setting(value = "entity-spawn", comment = "Log when living entities are spawned") + @Setting("entity-spawn") + @Comment("Log when living entities are spawned") private boolean entitySpawnLogging = false; - @Setting(value = "entity-despawn", comment = "Log when living entities are despawned") + @Setting("entity-despawn") + @Comment("Log when living entities are despawned") private boolean entityDespawnLogging = false; - @Setting(value = "entity-death", comment = "Log when living entities are destroyed") + @Setting("entity-death") + @Comment("Log when living entities are destroyed") private boolean entityDeathLogging = false; - @Setting(value = "exploit-itemstack-name-overflow", comment = "Log when server receives exploited packet with itemstack name exceeding string limit.") + @Setting("exploit-itemstack-name-overflow") + @Comment("Log when server receives exploited packet with itemstack name exceeding string limit.") public boolean logExploitItemStackNameOverflow = false; - @Setting(value = "log-stacktraces", comment = "Add stack traces to dev logging") + @Setting("log-stacktraces") + @Comment("Add stack traces to dev logging") private boolean logWithStackTraces = false; - @Setting(value = "entity-collision-checks", comment = "Whether to log entity collision/count checks") + @Setting("entity-collision-checks") + @Comment("Whether to log entity collision/count checks") private boolean logEntityCollisionChecks = false; - @Setting(value = "entity-speed-removal", comment = "Whether to log entity removals due to speed") + @Setting("entity-speed-removal") + @Comment("Whether to log entity removals due to speed") private boolean logEntitySpeedRemoval = false; - @Setting(value = "world-auto-save", comment = "Log when a world auto-saves its chunk data. Note: This may be spammy depending on the auto-save-interval configured for world.") + @Setting("world-auto-save") + @Comment("Log when a world auto-saves its chunk data. Note: This may be spammy depending on the auto-save-interval configured for world.") private boolean logWorldAutomaticSaving = false; public boolean blockBreakLogging() { return this.blockBreakLogging; } - public void setBlockBreakLogging(boolean flag) { + public void setBlockBreakLogging(final boolean flag) { this.blockBreakLogging = flag; } @@ -75,7 +92,7 @@ public boolean blockModifyLogging() { return this.blockModifyLogging; } - public void setBlockModifyLogging(boolean flag) { + public void setBlockModifyLogging(final boolean flag) { this.blockModifyLogging = flag; } @@ -83,7 +100,7 @@ public boolean blockPlaceLogging() { return this.blockPlaceLogging; } - public void setBlockPlaceLogging(boolean flag) { + public void setBlockPlaceLogging(final boolean flag) { this.blockPlaceLogging = flag; } @@ -91,7 +108,7 @@ public boolean blockPopulateLogging() { return this.blockPopulateLogging; } - public void setBlockPopulateLogging(boolean flag) { + public void setBlockPopulateLogging(final boolean flag) { this.blockPopulateLogging = flag; } @@ -99,7 +116,7 @@ public boolean blockTrackLogging() { return this.blockTrackLogging; } - public void setBlockTrackLogging(boolean flag) { + public void setBlockTrackLogging(final boolean flag) { this.blockTrackLogging = flag; } @@ -107,7 +124,7 @@ public boolean chunkLoadLogging() { return this.chunkLoadLogging; } - public void setChunkLoadLogging(boolean flag) { + public void setChunkLoadLogging(final boolean flag) { this.chunkLoadLogging = flag; } @@ -115,11 +132,11 @@ public boolean chunkUnloadLogging() { return this.chunkUnloadLogging; } - public void setChunkUnloadLogging(boolean flag) { + public void setChunkUnloadLogging(final boolean flag) { this.chunkUnloadLogging = flag; } - public void setChunkGCQueueUnloadLogging(boolean flag) { + public void setChunkGCQueueUnloadLogging(final boolean flag) { this.chunkGCQueueUnloadLogging = flag; } @@ -131,7 +148,7 @@ public boolean entitySpawnLogging() { return this.entitySpawnLogging; } - public void setEntitySpawnLogging(boolean flag) { + public void setEntitySpawnLogging(final boolean flag) { this.entitySpawnLogging = flag; } @@ -139,7 +156,7 @@ public boolean entityDespawnLogging() { return this.entityDespawnLogging; } - public void setEntityDespawnLogging(boolean flag) { + public void setEntityDespawnLogging(final boolean flag) { this.entityDespawnLogging = flag; } @@ -147,7 +164,7 @@ public boolean entityDeathLogging() { return this.entityDeathLogging; } - public void setEntityDeathLogging(boolean flag) { + public void setEntityDeathLogging(final boolean flag) { this.entityDeathLogging = flag; } @@ -155,7 +172,7 @@ public boolean logWithStackTraces() { return this.logWithStackTraces; } - public void setLogWithStackTraces(boolean flag) { + public void setLogWithStackTraces(final boolean flag) { this.logWithStackTraces = flag; } @@ -163,7 +180,7 @@ public boolean logEntityCollisionChecks() { return this.logEntityCollisionChecks; } - public void setLogEntityCollisionChecks(boolean flag) { + public void setLogEntityCollisionChecks(final boolean flag) { this.logEntityCollisionChecks = flag; } @@ -171,7 +188,7 @@ public boolean logEntitySpeedRemoval() { return this.logEntitySpeedRemoval; } - public void setLogEntitySpeedRemoval(boolean flag) { + public void setLogEntitySpeedRemoval(final boolean flag) { this.logEntitySpeedRemoval = flag; } diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/MovementChecksCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/MovementChecksCategory.java index 2fe81bbee8e..096aa5779a9 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/MovementChecksCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/MovementChecksCategory.java @@ -24,19 +24,23 @@ */ package org.spongepowered.common.applaunch.config.inheritable; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; @ConfigSerializable public class MovementChecksCategory { - @Setting(value = "player-moved-too-quickly", comment = "Controls whether the 'player moved too quickly!' check will be enforced") + @Setting("player-moved-too-quickly") + @Comment("Controls whether the 'player moved too quickly!' check will be enforced") private boolean playerMovedTooQuickly = true; - @Setting(value = "player-vehicle-moved-too-quickly", comment = "Controls whether the 'vehicle of player moved too quickly!' check will be enforced") + @Setting("player-vehicle-moved-too-quickly") + @Comment("Controls whether the 'vehicle of player moved too quickly!' check will be enforced") private boolean playerVehicleMovedTooQuickly = true; - @Setting(value = "moved-wrongly", comment = "Controls whether the 'player/entity moved wrongly!' check will be enforced") + @Setting("moved-wrongly") + @Comment("Controls whether the 'player/entity moved wrongly!' check will be enforced") private boolean movedWrongly = true; public boolean playerMovedTooQuickly() { diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/PlayerBlockTracker.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/PlayerBlockTracker.java index 2ba858f186a..65b2330943b 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/PlayerBlockTracker.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/PlayerBlockTracker.java @@ -24,8 +24,9 @@ */ package org.spongepowered.common.applaunch.config.inheritable; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; import java.util.ArrayList; import java.util.List; @@ -33,18 +34,20 @@ @ConfigSerializable public final class PlayerBlockTracker { - @Setting(value = "enabled", comment = "If 'true', adds player tracking support for block positions. \n" - + "Note: This should only be disabled if you do not care who caused a block to change.") + @Setting("enabled") + @Comment("If 'true', adds player tracking support for block positions. \n" + + "Note: This should only be disabled if you do not care who caused a block to change.") private boolean enabled = true; - @Setting(value = "block-blacklist", comment = "Block IDs that will be blacklisted for player block placement tracking.") + @Setting("block-blacklist") + @Comment("Block IDs that will be blacklisted for player block placement tracking.") private List blockBlacklist = new ArrayList<>(); public boolean isEnabled() { return this.enabled; } - public void setEnabled(boolean flag) { + public void setEnabled(final boolean flag) { this.enabled = flag; } diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/SpawnerCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/SpawnerCategory.java index e9f15ac27b0..35ff9e68593 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/SpawnerCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/SpawnerCategory.java @@ -24,31 +24,39 @@ */ package org.spongepowered.common.applaunch.config.inheritable; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; @ConfigSerializable public final class SpawnerCategory { - @Setting(value = "spawn-limit-ambient", comment = "The number of ambients the spawner can potentially spawn around a player.") + @Setting("spawn-limit-ambient") + @Comment("The number of ambients the spawner can potentially spawn around a player.") private int spawnLimitAmbient = 15; - @Setting(value = "spawn-limit-animal", comment = "The number of animals the spawner can potentially spawn around a player.") + @Setting("spawn-limit-animal") + @Comment("The number of animals the spawner can potentially spawn around a player.") private int spawnLimitAnimal = 15; - @Setting(value = "spawn-limit-aquatic", comment = "The number of aquatics the spawner can potentially spawn around a player.") + @Setting("spawn-limit-aquatic") + @Comment("The number of aquatics the spawner can potentially spawn around a player.") private int spawnLimitAquatic = 5; - @Setting(value = "spawn-limit-monster", comment = "The number of monsters the spawner can potentially spawn around a player.") + @Setting("spawn-limit-monster") + @Comment("The number of monsters the spawner can potentially spawn around a player.") private int spawnLimitMonster = 70; - @Setting(value = "tick-rate-ambient", comment = "The ambient spawning tick rate. Default: 400") + @Setting("tick-rate-ambient") + @Comment("The ambient spawning tick rate. Default: 400") private int tickRateAmbient = 400; - @Setting(value = "tick-rate-animal", comment = "The animal spawning tick rate. Default: 400") + @Setting("tick-rate-animal") + @Comment("The animal spawning tick rate. Default: 400") private int tickRateAnimal = 400; - @Setting(value = "tick-rate-aquatic", comment = "The aquatic spawning tick rate. Default: 1") + @Setting("tick-rate-aquatic") + @Comment("The aquatic spawning tick rate. Default: 1") private int tickRateAquatic = 1; - @Setting(value = "tick-rate-monster", comment = "The monster spawning tick rate. Default: 1") + @Setting("tick-rate-monster") + @Comment("The monster spawning tick rate. Default: 1") private int tickRateMonster = 1; public SpawnerCategory() { - } public int getAnimalSpawnLimit() { diff --git a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/WorldCategory.java b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/WorldCategory.java index b811e1d6d5d..5702ec0dc9b 100644 --- a/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/WorldCategory.java +++ b/src/applaunch/java/org/spongepowered/common/applaunch/config/inheritable/WorldCategory.java @@ -24,85 +24,99 @@ */ package org.spongepowered.common.applaunch.config.inheritable; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.common.applaunch.config.core.SpongeConfigs; @ConfigSerializable public class WorldCategory { - @Setting(value = "auto-save-interval", comment = "The auto-save tick interval used to save all loaded chunks in a world. \n" - + "Set to 0 to disable. (Default: 6000) \n" - + "Note: 20 ticks is equivalent to 1 second.") + @Setting("auto-save-interval") + @Comment("The auto-save tick interval used to save all loaded chunks in a world. \n" + + "Set to 0 to disable. (Default: 6000) \n" + + "Note: 20 ticks is equivalent to 1 second.") private int autoSaveInterval = 6000; - @Setting(value = "mob-spawn-range", comment = "Specifies the radius (in chunks) of where creatures will spawn. \n" - + "This value is capped to the current view distance setting in server.properties") + @Setting("mob-spawn-range") + @Comment("Specifies the radius (in chunks) of where creatures will spawn. \n" + + "This value is capped to the current view distance setting in server.properties") private int mobSpawnRange = 4; - @Setting(value = "world-enabled", comment = "If 'true', this world will be registered.") + @Setting("world-enabled") + @Comment("If 'true', this world will be registered.") private boolean worldEnabled = true; - @Setting(value = "load-on-startup", comment = "If 'true', this world will load on startup.") + @Setting("load-on-startup") + @Comment("If 'true', this world will load on startup.") private Boolean loadOnStartup = true; - @Setting(value = "generate-spawn-on-load", comment = "If 'true', this world will generate its spawn the moment its loaded.") + @Setting("generate-spawn-on-load") + @Comment("If 'true', this world will generate its spawn the moment its loaded.") private Boolean generateSpawnOnLoad = false; - @Setting(value = "keep-spawn-loaded", comment = "If 'true', this worlds spawn will remain loaded with no players.") + @Setting("keep-spawn-loaded") + @Comment("If 'true', this worlds spawn will remain loaded with no players.") private Boolean keepSpawnLoaded = true; - @Setting(value = "pvp-enabled", comment = "If 'true', this world will allow PVP combat.") + @Setting("pvp-enabled") + @Comment("If 'true', this world will allow PVP combat.") private boolean pvpEnabled = true; - @Setting(value = "deny-chunk-requests", comment = "If 'true', any request for a chunk not currently loaded will be denied (exceptions apply \n" - + "for things like world gen and player movement). \n" - + "Warning: As this is an experimental setting for performance gain, if you encounter any issues \n" - + "then we recommend disabling it.") + @Setting("deny-chunk-requests") + @Comment("If 'true', any request for a chunk not currently loaded will be denied (exceptions apply \n" + + "for things like world gen and player movement). \n" + + "Warning: As this is an experimental setting for performance gain, if you encounter any issues \n" + + "then we recommend disabling it.") private boolean denyChunkRequests = false; - @Setting(value = "chunk-gc-tick-interval", comment = "The tick interval used to cleanup all inactive chunks that have leaked in a world. \n" - + "Set to 0 to disable which restores vanilla handling. (Default: 600)") + @Setting("chunk-gc-tick-interval") + @Comment("The tick interval used to cleanup all inactive chunks that have leaked in a world. \n" + + "Set to 0 to disable which restores vanilla handling. (Default: 600)") private int chunkGCTickInterval = 600; - @Setting(value = "max-chunk-unloads-per-tick", comment = "The maximum number of queued unloaded chunks that will be unloaded in a single tick. \n" - + "Note: With the chunk gc enabled, this setting only applies to the ticks \n" - + "where the gc runs (controlled by 'chunk-gc-tick-interval') \n" - + "Note: If the maximum unloads is too low, too many chunks may remain \n" - + "loaded on the world and increases the chance for a drop in tps. (Default: 100)") + @Setting("max-chunk-unloads-per-tick") + @Comment("The maximum number of queued unloaded chunks that will be unloaded in a single tick. \n" + + "Note: With the chunk gc enabled, this setting only applies to the ticks \n" + + "where the gc runs (controlled by 'chunk-gc-tick-interval') \n" + + "Note: If the maximum unloads is too low, too many chunks may remain \n" + + "loaded on the world and increases the chance for a drop in tps. (Default: 100)") private int maxChunkUnloads = 100; - @Setting(value = "chunk-gc-load-threshold", comment = "The number of newly loaded chunks before triggering a forced cleanup. \n" - + "Note: When triggered, the loaded chunk threshold will reset and start incrementing. \n" - + "Disabled by default.") + @Setting("chunk-gc-load-threshold") + @Comment("The number of newly loaded chunks before triggering a forced cleanup. \n" + + "Note: When triggered, the loaded chunk threshold will reset and start incrementing. \n" + + "Disabled by default.") private int chunkGCLoadThreshold = 0; - @Setting(value = "chunk-unload-delay", comment = "The number of seconds to delay a chunk unload once marked inactive. (Default: 15) \n" - + "Note: This gets reset if the chunk becomes active again.") + @Setting("chunk-unload-delay") + @Comment("The number of seconds to delay a chunk unload once marked inactive. (Default: 15) \n" + + "Note: This gets reset if the chunk becomes active again.") private int chunkUnloadDelay = 15; - @Setting(value = "item-merge-radius", comment = "The defined merge radius for Item entities such that when two items are \n" - + "within the defined radius of each other, they will attempt to merge. Usually, \n" - + "the default radius is set to 0.5 in Vanilla, however, for performance reasons \n" - + "2.5 is generally acceptable. \n" - + "Note: Increasing the radius higher will likely cause performance degradation \n" - + "with larger amount of items as they attempt to merge and search nearby \n" - + "areas for more items. Setting to a negative value is not supported!") + @Setting("item-merge-radius") + @Comment("The defined merge radius for Item entities such that when two items are \n" + + "within the defined radius of each other, they will attempt to merge. Usually, \n" + + "the default radius is set to 0.5 in Vanilla, however, for performance reasons \n" + + "2.5 is generally acceptable. \n" + + "Note: Increasing the radius higher will likely cause performance degradation \n" + + "with larger amount of items as they attempt to merge and search nearby \n" + + "areas for more items. Setting to a negative value is not supported!") private double itemMergeRadius = 2.5D; - @Setting(value = "weather-thunder", comment = "If 'true', thunderstorms will be initiated in supported biomes.") + @Setting("weather-thunder") + @Comment("If 'true', thunderstorms will be initiated in supported biomes.") private boolean weatherThunder = true; - @Setting(value = "weather-ice-and-snow", comment = "If 'true', natural formation of ice and snow in supported biomes will be allowed.") + @Setting("weather-ice-and-snow") + @Comment("If 'true', natural formation of ice and snow in supported biomes will be allowed.") private boolean weatherIceAndSnow = true; public static final int USE_SERVER_VIEW_DISTANCE = -1; - @Setting( - value = "view-distance", - comment = "Override world distance per world/dimension \n" - + "The value must be greater than or equal to 3 and less than or equal to 32 \n" - + "The server-wide view distance will be used when the value is " + USE_SERVER_VIEW_DISTANCE + "." - ) + @Setting("view-distance") + @Comment("Override world distance per world/dimension \n" + + "The value must be greater than or equal to 3 and less than or equal to 32 \n" + + "The server-wide view distance will be used when the value is " + USE_SERVER_VIEW_DISTANCE + ".") private int viewDistance = USE_SERVER_VIEW_DISTANCE; public WorldCategory() { @@ -110,7 +124,7 @@ public WorldCategory() { // Enabled by default on SpongeVanilla, disabled by default on SpongeForge. // Because of how early this constructor gets called, we can't use SpongeImplHooks or even Game this.denyChunkRequests = SpongeConfigs.getPluginEnvironment().getBlackboard().get(SpongeConfigs.IS_VANILLA_PLATFORM).orElse(true); - } catch (Exception e) { + } catch (final Exception e) { e.printStackTrace(); } } @@ -123,7 +137,7 @@ public boolean isWorldEnabled() { return this.worldEnabled; } - public void setWorldEnabled(boolean enabled) { + public void setWorldEnabled(final boolean enabled) { this.worldEnabled = enabled; } @@ -131,7 +145,7 @@ public long getChunkUnloadDelay() { return this.chunkUnloadDelay; } - public void setChunkUnloadDelay(int delay) { + public void setChunkUnloadDelay(final int delay) { this.chunkUnloadDelay = delay; } @@ -139,7 +153,7 @@ public Boolean getLoadOnStartup() { return this.loadOnStartup; } - public void setLoadOnStartup(Boolean state) { + public void setLoadOnStartup(final Boolean state) { this.loadOnStartup = state; } @@ -147,7 +161,7 @@ public Boolean getKeepSpawnLoaded() { return this.keepSpawnLoaded; } - public void setKeepSpawnLoaded(Boolean loaded) { + public void setKeepSpawnLoaded(final Boolean loaded) { this.keepSpawnLoaded = loaded; } @@ -155,7 +169,7 @@ public boolean getPVPEnabled() { return this.pvpEnabled; } - public void setPVPEnabled(boolean allow) { + public void setPVPEnabled(final boolean allow) { this.pvpEnabled = allow; } @@ -163,7 +177,7 @@ public Boolean getGenerateSpawnOnLoad() { return this.generateSpawnOnLoad; } - public void setGenerateSpawnOnLoad(Boolean allow) { + public void setGenerateSpawnOnLoad(final Boolean allow) { this.generateSpawnOnLoad = allow; } @@ -171,7 +185,7 @@ public int getMobSpawnRange() { return this.mobSpawnRange; } - public void setMobSpawnRange(int range) { + public void setMobSpawnRange(final int range) { this.mobSpawnRange = range; } diff --git a/src/main/java/org/spongepowered/common/SpongeCommon.java b/src/main/java/org/spongepowered/common/SpongeCommon.java index 02d6e895afd..1baf61e956d 100644 --- a/src/main/java/org/spongepowered/common/SpongeCommon.java +++ b/src/main/java/org/spongepowered/common/SpongeCommon.java @@ -29,12 +29,11 @@ import com.google.inject.Singleton; import net.minecraft.server.MinecraftServer; import org.apache.logging.log4j.Logger; +import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.Sponge; import org.spongepowered.api.event.Event; import org.spongepowered.api.util.Direction; -import org.spongepowered.common.applaunch.config.core.InheritableConfigHandle; import org.spongepowered.common.applaunch.config.core.SpongeConfigs; -import org.spongepowered.common.applaunch.config.inheritable.GlobalConfig; import org.spongepowered.common.launch.Launch; import org.spongepowered.common.registry.SpongeGameRegistry; import org.spongepowered.common.scheduler.AsyncScheduler; @@ -43,7 +42,7 @@ import org.spongepowered.plugin.PluginContainer; import org.spongepowered.plugin.PluginKeys; -import javax.annotation.Nullable; +import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; @@ -58,9 +57,6 @@ public final class SpongeCommon { Constants.MINECRAFT_PROTOCOL_VERSION ); - // Can't @Inject these because they are referenced before everything is initialized - @Nullable private static InheritableConfigHandle globalConfigAdapter; - @Inject @Nullable private static SpongeGame game; @Nullable private static PluginContainer activePlugin; @@ -68,6 +64,19 @@ public final class SpongeCommon { private SpongeCommon() { } + static { + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + final @Nullable SpongeGame game = SpongeCommon.game; + if (game != null) { + try { + game.getConfigManager().close(); + } catch (final IOException e) { + SpongeCommon.getLogger().error("Failed to shut down configuration watch service", e); + } + } + }, "Sponge shutdown thread")); + } + private static T check(@Nullable T instance) { Preconditions.checkState(instance != null, "SpongeCommon has not been initialized!"); return instance; @@ -206,4 +215,5 @@ public static Direction getSecondaryDirection(Direction direction) { return Direction.NONE; } } + } diff --git a/src/main/java/org/spongepowered/common/SpongeGame.java b/src/main/java/org/spongepowered/common/SpongeGame.java index 695e11b89eb..dc3b38f75dc 100644 --- a/src/main/java/org/spongepowered/common/SpongeGame.java +++ b/src/main/java/org/spongepowered/common/SpongeGame.java @@ -45,6 +45,7 @@ import org.spongepowered.api.service.ServiceProvider; import org.spongepowered.api.sql.SqlManager; import org.spongepowered.api.util.metric.MetricsConfigManager; +import org.spongepowered.common.config.PluginConfigManager; import org.spongepowered.common.scheduler.AsyncScheduler; import org.spongepowered.common.server.ServerConsoleSystemSubject; import org.spongepowered.common.util.LocaleCache; @@ -61,7 +62,7 @@ public final class SpongeGame implements Game { private final PluginManager pluginManager; private final EventManager eventManager; private final AssetManager assetManager; - private final ConfigManager configManager; + private final PluginConfigManager configManager; private final ChannelRegistry channelRegistry; private final MetricsConfigManager metricsConfigManager; private final CommandManager commandManager; @@ -76,9 +77,9 @@ public final class SpongeGame implements Game { @Inject public SpongeGame(final Platform platform, final GameRegistry registry, final DataManager dataManager, final PluginManager pluginManager, - final EventManager eventManager, final AssetManager assetManager, final ConfigManager configManager, final ChannelRegistry channelRegistry, - final MetricsConfigManager metricsConfigManager, final CommandManager commandManager, final SqlManager sqlManager, - final ServiceProvider.GameScoped serviceProvider) { + final EventManager eventManager, final AssetManager assetManager, final PluginConfigManager configManager, + final ChannelRegistry channelRegistry, final MetricsConfigManager metricsConfigManager, final CommandManager commandManager, + final SqlManager sqlManager, final ServiceProvider.GameScoped serviceProvider) { this.platform = platform; this.registry = registry; @@ -138,7 +139,7 @@ public AssetManager getAssetManager() { } @Override - public ConfigManager getConfigManager() { + public PluginConfigManager getConfigManager() { return this.configManager; } diff --git a/src/main/java/org/spongepowered/common/SpongeLifecycle.java b/src/main/java/org/spongepowered/common/SpongeLifecycle.java index 4bace77a699..5d453b2e360 100644 --- a/src/main/java/org/spongepowered/common/SpongeLifecycle.java +++ b/src/main/java/org/spongepowered/common/SpongeLifecycle.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; @@ -151,11 +151,13 @@ public void callConstructEvent() { } public void callStartingEngineEvent(final Engine engine) { - this.game.getEventManager().post(new StartingEngineEventImpl<>(PhaseTracker.getCauseStackManager().getCurrentCause(), this.game, engine, (TypeToken) TypeToken.of(engine.getClass()))); + this.game.getEventManager().post(new StartingEngineEventImpl<>(PhaseTracker.getCauseStackManager().getCurrentCause(), this.game, engine, + (TypeToken) TypeToken.get(engine.getClass()))); } public void callStartedEngineEvent(final Engine engine) { - this.game.getEventManager().post(new StartedEngineEventImpl<>(PhaseTracker.getCauseStackManager().getCurrentCause(), this.game, engine, (TypeToken) TypeToken.of(engine.getClass()))); + this.game.getEventManager().post(new StartedEngineEventImpl<>(PhaseTracker.getCauseStackManager().getCurrentCause(), this.game, engine, + (TypeToken) TypeToken.get(engine.getClass()))); } public void callLoadedGameEvent() { @@ -163,7 +165,8 @@ public void callLoadedGameEvent() { } public void callStoppingEngineEvent(final Engine engine) { - this.game.getEventManager().post(new StoppingEngineEventImpl<>(PhaseTracker.getCauseStackManager().getCurrentCause(), this.game, engine, (TypeToken) TypeToken.of(engine.getClass()))); + this.game.getEventManager().post(new StoppingEngineEventImpl<>(PhaseTracker.getCauseStackManager().getCurrentCause(), this.game, engine, + (TypeToken) TypeToken.get(engine.getClass()))); } private Collection filterInternalPlugins(final Collection plugins) { diff --git a/src/main/java/org/spongepowered/common/advancement/SpongeTrigger.java b/src/main/java/org/spongepowered/common/advancement/SpongeTrigger.java index b231d462f7c..65ca7b5d091 100644 --- a/src/main/java/org/spongepowered/common/advancement/SpongeTrigger.java +++ b/src/main/java/org/spongepowered/common/advancement/SpongeTrigger.java @@ -26,7 +26,7 @@ import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonObject; import net.minecraft.advancements.ICriterionTrigger; @@ -46,6 +46,7 @@ import org.spongepowered.common.bridge.advancements.TriggerBridge; import org.spongepowered.common.event.tracking.PhaseTracker; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.function.Consumer; import java.util.function.Function; @@ -55,18 +56,18 @@ @SuppressWarnings("rawtypes") public class SpongeTrigger implements ICriterionTrigger, TriggerBridge { - private final Class triggerConfigurationClass; + private final Type triggerConfigurationType; final Function constructor; private final ResourceLocation id; private final Multimap listeners = HashMultimap.create(); @Nullable final Consumer eventHandler; private final String name; - SpongeTrigger(final Class triggerConfigurationClass, + SpongeTrigger(final Type triggerConfigurationType, final Function constructor, final ResourceLocation id, @Nullable final Consumer eventHandler, final String name) { - this.triggerConfigurationClass = triggerConfigurationClass; + this.triggerConfigurationType = triggerConfigurationType; this.eventHandler = eventHandler; this.constructor = constructor; this.id = id; @@ -106,7 +107,9 @@ public SpongeFilteredTrigger deserializeInstance(final JsonObject json, final Js public void bridge$trigger(final ServerPlayer player) { final PlayerAdvancements playerAdvancements = ((ServerPlayerEntity) player).getAdvancements(); final Cause cause = PhaseTracker.getCauseStackManager().getCurrentCause(); - final TypeToken typeToken = TypeToken.of(this.triggerConfigurationClass); + + @SuppressWarnings("unchecked") // correct type verified in builder + final TypeToken typeToken = (TypeToken) TypeToken.get(this.triggerConfigurationType); for (final Listener listener : new ArrayList<>(this.listeners.get(playerAdvancements))) { final ICriterionTrigger_ListenerAccessor mixinListener = (ICriterionTrigger_ListenerAccessor) listener; final Advancement advancement = (Advancement) mixinListener.accessor$getAdvancement(); diff --git a/src/main/java/org/spongepowered/common/advancement/SpongeTriggerBuilder.java b/src/main/java/org/spongepowered/common/advancement/SpongeTriggerBuilder.java index ee136526b18..b67f980e3be 100644 --- a/src/main/java/org/spongepowered/common/advancement/SpongeTriggerBuilder.java +++ b/src/main/java/org/spongepowered/common/advancement/SpongeTriggerBuilder.java @@ -26,16 +26,17 @@ import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; +import static java.util.Objects.requireNonNull; -import com.google.common.reflect.TypeToken; import com.google.gson.Gson; import com.google.gson.JsonObject; +import io.leangen.geantyref.TypeToken; import net.minecraft.util.ResourceLocation; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.gson.GsonConfigurationLoader; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; -import ninja.leaping.configurate.objectmapping.serialize.TypeSerializerCollection; -import ninja.leaping.configurate.objectmapping.serialize.TypeSerializers; +import org.spongepowered.common.SpongeCommon; +import org.spongepowered.configurate.ConfigurateException; +import org.spongepowered.configurate.ConfigurationNode; +import org.spongepowered.configurate.ConfigurationOptions; +import org.spongepowered.configurate.gson.GsonConfigurationLoader; import org.apache.commons.lang3.StringUtils; import org.spongepowered.api.Sponge; import org.spongepowered.api.advancement.criteria.trigger.FilteredTriggerConfiguration; @@ -52,19 +53,21 @@ import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; +import java.lang.reflect.Type; import java.util.function.Consumer; import java.util.function.Function; +import java.util.function.UnaryOperator; @SuppressWarnings("unchecked") public class SpongeTriggerBuilder implements Trigger.Builder { - private final static Gson GSON = new Gson(); + private static final Gson GSON = new Gson(); private final static FilteredTriggerConfiguration.Empty EMPTY_TRIGGER_CONFIGURATION = new FilteredTriggerConfiguration.Empty(); private final static Function EMPTY_TRIGGER_CONFIGURATION_CONSTRUCTOR = jsonObject -> EMPTY_TRIGGER_CONFIGURATION; - @Nullable private Class configType; + @Nullable private Type configType; @Nullable private Function constructor; @Nullable private Consumer> eventHandler; @Nullable private String id; @@ -74,7 +77,7 @@ public class SpongeTriggerBuilder implem @SuppressWarnings("rawtypes") public Trigger.Builder dataSerializableConfig(final Class dataConfigClass) { checkNotNull(dataConfigClass, "dataConfigClass"); - this.configType = (Class) dataConfigClass; + this.configType = dataConfigClass; this.constructor = new DataSerializableConstructor(dataConfigClass); return (Trigger.Builder) this; } @@ -93,47 +96,83 @@ public C apply(final JsonObject jsonObject) { try { final DataView dataView = JsonDataFormat.serialize(GSON, jsonObject); return builder.build(dataView).get(); - } catch (IOException e) { + } catch (final IOException e) { throw new IllegalStateException(e); } } } + // TODO: do these need to be hooked up for saving as well? currently they just load + + private static ConfigurationOptions defaultOptions() { + return ConfigurationOptions.defaults() + .serializers(SpongeCommon.getGame().getConfigManager().getSerializers()); + } + + @Override + public Trigger.Builder typeSerializableConfig(final TypeToken configType) { + return this.typeSerializableConfig(configType, SpongeTriggerBuilder.defaultOptions()); + } + + @Override + public Trigger.Builder typeSerializableConfig(final TypeToken configType, + final ConfigurationOptions options) { + checkNotNull(configType, "configType"); + checkNotNull(options, "options"); + this.configType = configType.getType(); + this.constructor = new ConfigurateConstructor<>(configType.getType(), options); + return (Trigger.Builder) this; + } + + @Override + public Trigger.Builder typeSerializableConfig(final TypeToken configType, + final UnaryOperator transformer) { + return this.typeSerializableConfig(configType, transformer.apply(SpongeTriggerBuilder.defaultOptions())); + } + @Override public Trigger.Builder typeSerializableConfig(final Class configClass) { - return this.typeSerializableConfig(configClass, TypeSerializerCollection.defaults()); + return this.typeSerializableConfig(configClass, SpongeTriggerBuilder.defaultOptions()); } @Override @SuppressWarnings("rawtypes") public Trigger.Builder typeSerializableConfig(final Class configClass, - final TypeSerializerCollection typeSerializerCollection) { + final ConfigurationOptions options) { checkNotNull(configClass, "configClass"); - checkNotNull(typeSerializerCollection, "typeSerializerCollection"); - this.configType = (Class) configClass; - this.constructor = new ConfigurateConstructor(configClass, typeSerializerCollection); + checkNotNull(options, "options"); + this.configType = configClass; + this.constructor = new ConfigurateConstructor(configClass, options); return (Trigger.Builder) this; } + @Override + public Trigger.Builder typeSerializableConfig(final Class configClass, + final UnaryOperator transformer) { + requireNonNull(transformer, "transformer"); + return typeSerializableConfig(configClass, transformer.apply(SpongeTriggerBuilder.defaultOptions())); + } + private static class ConfigurateConstructor implements Function { - private final TypeToken typeToken; - private final TypeSerializerCollection typeSerializerCollection; + private final Type typeToken; + private final ConfigurationOptions options; - private ConfigurateConstructor(final Class typeToken, final TypeSerializerCollection typeSerializerCollection) { - this.typeToken = TypeToken.of(typeToken); - this.typeSerializerCollection = typeSerializerCollection; + private ConfigurateConstructor(final Type typeToken, final ConfigurationOptions options) { + this.typeToken = typeToken; + this.options = options; } @Override public C apply(final JsonObject jsonObject) { final GsonConfigurationLoader loader = GsonConfigurationLoader.builder() - .setSource(() -> new BufferedReader(new StringReader(GSON.toJson(jsonObject)))) + .defaultOptions(this.options) + .source(() -> new BufferedReader(new StringReader(GSON.toJson(jsonObject)))) .build(); try { final ConfigurationNode node = loader.load(); - return this.typeSerializerCollection.get(this.typeToken).deserialize(this.typeToken, node); - } catch (IOException | ObjectMappingException e) { + return (C) node.get(this.typeToken); + } catch (final ConfigurateException e) { throw new IllegalStateException(e); } } @@ -143,7 +182,7 @@ public C apply(final JsonObject jsonObject) { @Override public Trigger.Builder jsonSerializableConfig(final Class configClass, final Gson gson) { checkNotNull(configClass, "configClass"); - this.configType = (Class) configClass; + this.configType = configClass; this.constructor = new JsonConstructor(configClass, gson); return (Trigger.Builder) this; } @@ -155,10 +194,10 @@ public Trigger.Builder jsonSerializa private static class JsonConstructor implements Function { - private final Class configClass; + private final Type configClass; private final Gson gson; - private JsonConstructor(final Class configClass, final Gson gson) { + private JsonConstructor(final Type configClass, final Gson gson) { this.configClass = configClass; this.gson = gson; } @@ -171,7 +210,7 @@ public C apply(final JsonObject jsonObject) { @Override public Trigger.Builder emptyConfig() { - this.configType = (Class) FilteredTriggerConfiguration.Empty.class; + this.configType = FilteredTriggerConfiguration.Empty.class; this.constructor = (Function) EMPTY_TRIGGER_CONFIGURATION_CONSTRUCTOR; return (Trigger.Builder) this; } @@ -203,12 +242,12 @@ public Trigger build() { checkState(this.configType != null, "The configType must be set"); final PluginContainer plugin = PhaseTracker.getCauseStackManager().getCurrentCause().first(PluginContainer.class).get(); final String name = StringUtils.isNotEmpty(this.name) ? this.name : this.id; - return (Trigger) new SpongeTrigger((Class) this.configType, (Function) this.constructor, + return (Trigger) new SpongeTrigger(this.configType, (Function) this.constructor, new ResourceLocation(plugin.getMetadata().getId(), this.id), (Consumer) this.eventHandler, name); } @Override - public Trigger.Builder from(Trigger value) { + public Trigger.Builder from(final Trigger value) { this.id = value.getKey().getValue(); this.configType = value.getConfigurationType(); if (value instanceof SpongeTrigger) { diff --git a/src/main/java/org/spongepowered/common/adventure/SpongeAdventure.java b/src/main/java/org/spongepowered/common/adventure/SpongeAdventure.java index 28947924a7a..b3427500c49 100644 --- a/src/main/java/org/spongepowered/common/adventure/SpongeAdventure.java +++ b/src/main/java/org/spongepowered/common/adventure/SpongeAdventure.java @@ -31,7 +31,7 @@ import net.kyori.adventure.bossbar.BossBar; import net.kyori.adventure.key.Key; import net.kyori.adventure.nbt.api.BinaryTagHolder; -import net.kyori.adventure.serializer.configurate3.ConfigurateComponentSerializer; +import net.kyori.adventure.serializer.configurate4.ConfigurateComponentSerializer; import net.kyori.adventure.sound.Sound; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.event.ClickEvent; diff --git a/src/main/java/org/spongepowered/common/command/brigadier/context/SpongeCommandContextBuilder.java b/src/main/java/org/spongepowered/common/command/brigadier/context/SpongeCommandContextBuilder.java index f42b9b34165..3022abd036a 100644 --- a/src/main/java/org/spongepowered/common/command/brigadier/context/SpongeCommandContextBuilder.java +++ b/src/main/java/org/spongepowered/common/command/brigadier/context/SpongeCommandContextBuilder.java @@ -26,7 +26,6 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; -import com.google.common.reflect.TypeToken; import com.mojang.brigadier.Command; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.RedirectModifier; @@ -227,7 +226,7 @@ public SpongeCommandContextBuilder withArgumentInternal(final String name, f } if (addToSpongeMap) { - final Parameter.Key objectKey = new SpongeParameterKey<>(name, TypeToken.of((Class) argument.getResult().getClass())); + final Parameter.Key objectKey = new SpongeParameterKey<>(name, argument.getResult().getClass()); this.addToArgumentMap(objectKey, argument.getResult()); } super.withArgument(name, argument); // for getArguments and any mods that use this. diff --git a/src/main/java/org/spongepowered/common/command/manager/SpongeCommandManager.java b/src/main/java/org/spongepowered/common/command/manager/SpongeCommandManager.java index 6b1dcae7d25..a8fa34f5725 100644 --- a/src/main/java/org/spongepowered/common/command/manager/SpongeCommandManager.java +++ b/src/main/java/org/spongepowered/common/command/manager/SpongeCommandManager.java @@ -27,7 +27,7 @@ import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; diff --git a/src/main/java/org/spongepowered/common/command/parameter/SpongeParameterKey.java b/src/main/java/org/spongepowered/common/command/parameter/SpongeParameterKey.java index 773152b2e03..d4ddbc13738 100644 --- a/src/main/java/org/spongepowered/common/command/parameter/SpongeParameterKey.java +++ b/src/main/java/org/spongepowered/common/command/parameter/SpongeParameterKey.java @@ -24,10 +24,11 @@ */ package org.spongepowered.common.command.parameter; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.GenericTypeReflector; import org.checkerframework.checker.nullness.qual.NonNull; import org.spongepowered.api.command.parameter.Parameter; +import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import java.util.Objects; @@ -37,7 +38,7 @@ public final class SpongeParameterKey implements Parameter.Key { private final static Map, SpongeParameterKey> keyCache = new HashMap<>(); private final String key; - private final TypeToken typeToken; + private final Type type; @SuppressWarnings("unchecked") public static SpongeParameterKey getSpongeKey(final Parameter.@NonNull Key key) { @@ -49,12 +50,13 @@ public static SpongeParameterKey getSpongeKey(final Parameter.@NonNull Ke } private SpongeParameterKey(final Parameter.@NonNull Key parameterKey) { - this(parameterKey.key(), parameterKey.getTypeToken()); + this.key = parameterKey.key(); + this.type = parameterKey.getType(); } - public SpongeParameterKey(@NonNull final String key, @NonNull final TypeToken typeToken) { + public SpongeParameterKey(final @NonNull String key, final @NonNull Type type) { this.key = key; - this.typeToken = typeToken; + this.type = type; } @Override @@ -65,8 +67,19 @@ public String key() { @Override @NonNull - public TypeToken getTypeToken() { - return this.typeToken; + public Type getType() { + return this.type; + } + + @Override + public boolean isInstance(final Object value) { + return value != null && GenericTypeReflector.erase(this.type).isInstance(value); + } + + @SuppressWarnings("unchecked") + @Override + public T cast(final Object value) { + return (T) value; } @Override @@ -78,17 +91,17 @@ public boolean equals(final Object o) { return false; } final SpongeParameterKey that = (SpongeParameterKey) o; - return this.key.equals(that.key) && this.typeToken.equals(that.typeToken); + return this.key.equals(that.key) && this.type.equals(that.type); } @Override public int hashCode() { - return Objects.hash(this.key, this.typeToken); + return Objects.hash(this.key, this.type); } @Override public String toString() { - return "Key: " + this.key + ", Class " + this.typeToken.getType().getTypeName(); + return "Key: " + this.key + ", Class " + this.type.getTypeName(); } } diff --git a/src/main/java/org/spongepowered/common/command/parameter/SpongeParameterKeyBuilder.java b/src/main/java/org/spongepowered/common/command/parameter/SpongeParameterKeyBuilder.java index 891f9cf17bf..97fe88f1b7c 100644 --- a/src/main/java/org/spongepowered/common/command/parameter/SpongeParameterKeyBuilder.java +++ b/src/main/java/org/spongepowered/common/command/parameter/SpongeParameterKeyBuilder.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.command.parameter; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import org.checkerframework.checker.nullness.qual.NonNull; import org.spongepowered.api.command.parameter.Parameter; @@ -32,7 +32,12 @@ public class SpongeParameterKeyBuilder implements Parameter.Key.Builder { @Override public Parameter.@NonNull Key build(@NonNull final String key, @NonNull final TypeToken typeToken) { - return new SpongeParameterKey<>(key, typeToken); + return new SpongeParameterKey<>(key, typeToken.getType()); + } + + @Override + public Parameter.@NonNull Key build(@NonNull final String key, @NonNull final Class type) { + return new SpongeParameterKey<>(key, type); } @Override diff --git a/src/main/java/org/spongepowered/common/command/parameter/SpongeParameterValueBuilder.java b/src/main/java/org/spongepowered/common/command/parameter/SpongeParameterValueBuilder.java index e44d1055771..d90aecd05ed 100644 --- a/src/main/java/org/spongepowered/common/command/parameter/SpongeParameterValueBuilder.java +++ b/src/main/java/org/spongepowered/common/command/parameter/SpongeParameterValueBuilder.java @@ -26,7 +26,6 @@ import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; -import com.google.common.reflect.TypeToken; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.command.CommandCause; @@ -35,6 +34,7 @@ import org.spongepowered.api.command.parameter.managed.ValueParser; import org.spongepowered.api.command.parameter.managed.ValueUsage; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -46,7 +46,7 @@ public final class SpongeParameterValueBuilder implements Parameter.Value.Bui private static final ValueCompleter EMPTY_COMPLETER = (context, currentInput) -> ImmutableList.of(); - private final TypeToken typeToken; + private final Type typeToken; private final List> parsers = new ArrayList<>(); private Parameter.@Nullable Key key; @Nullable private ValueCompleter completer; @@ -57,7 +57,7 @@ public final class SpongeParameterValueBuilder implements Parameter.Value.Bui private boolean isOptional; private boolean terminal; - public SpongeParameterValueBuilder(@NonNull final TypeToken token) { + public SpongeParameterValueBuilder(@NonNull final Type token) { this.typeToken = token; } diff --git a/src/main/java/org/spongepowered/common/command/parameter/SpongeParameterValueFactory.java b/src/main/java/org/spongepowered/common/command/parameter/SpongeParameterValueFactory.java index 740def69d6b..a217a4eb064 100644 --- a/src/main/java/org/spongepowered/common/command/parameter/SpongeParameterValueFactory.java +++ b/src/main/java/org/spongepowered/common/command/parameter/SpongeParameterValueFactory.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.command.parameter; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import org.checkerframework.checker.nullness.qual.NonNull; import org.spongepowered.api.command.parameter.Parameter; @@ -38,6 +38,10 @@ private SpongeParameterValueFactory() { @Override public Parameter.Value.@NonNull Builder createParameterBuilder(@NonNull final TypeToken parameterClass) { + return new SpongeParameterValueBuilder<>(parameterClass.getType()); + } + + @Override public Parameter.Value.Builder createParameterBuilder(final Class parameterClass) { return new SpongeParameterValueBuilder<>(parameterClass); } diff --git a/src/main/java/org/spongepowered/common/command/registrar/BrigadierCommandRegistrar.java b/src/main/java/org/spongepowered/common/command/registrar/BrigadierCommandRegistrar.java index c2c67861ee4..1588e63fb68 100644 --- a/src/main/java/org/spongepowered/common/command/registrar/BrigadierCommandRegistrar.java +++ b/src/main/java/org/spongepowered/common/command/registrar/BrigadierCommandRegistrar.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.command.registrar; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.suggestion.Suggestion; diff --git a/src/main/java/org/spongepowered/common/command/registrar/SpongeParameterizedCommandRegistrar.java b/src/main/java/org/spongepowered/common/command/registrar/SpongeParameterizedCommandRegistrar.java index 66f866e2037..f2dcf12bdaf 100644 --- a/src/main/java/org/spongepowered/common/command/registrar/SpongeParameterizedCommandRegistrar.java +++ b/src/main/java/org/spongepowered/common/command/registrar/SpongeParameterizedCommandRegistrar.java @@ -26,7 +26,7 @@ import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.suggestion.Suggestion; @@ -60,7 +60,7 @@ public final class SpongeParameterizedCommandRegistrar implements BrigadierBasedRegistrar, CommandRegistrar { private final Map commandMap = new HashMap<>(); - private static final TypeToken COMMAND_TYPE = TypeToken.of(Command.Parameterized.class); + private static final TypeToken COMMAND_TYPE = TypeToken.get(Command.Parameterized.class); public static final ResourceKey CATALOG_KEY = ResourceKey.sponge("managed"); public static final SpongeParameterizedCommandRegistrar INSTANCE = new SpongeParameterizedCommandRegistrar(); diff --git a/src/main/java/org/spongepowered/common/command/registrar/SpongeRawCommandRegistrar.java b/src/main/java/org/spongepowered/common/command/registrar/SpongeRawCommandRegistrar.java index 57a9edfe11e..97a59aef4b3 100644 --- a/src/main/java/org/spongepowered/common/command/registrar/SpongeRawCommandRegistrar.java +++ b/src/main/java/org/spongepowered/common/command/registrar/SpongeRawCommandRegistrar.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.command.registrar; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import net.kyori.adventure.text.Component; import org.checkerframework.checker.nullness.qual.NonNull; import org.spongepowered.api.ResourceKey; @@ -49,7 +49,7 @@ */ public final class SpongeRawCommandRegistrar implements CommandRegistrar { - private static final TypeToken COMMAND_TYPE = TypeToken.of(Command.Raw.class); + private static final TypeToken COMMAND_TYPE = TypeToken.get(Command.Raw.class); private static final ResourceKey CATALOG_KEY = ResourceKey.sponge("raw"); public static final SpongeRawCommandRegistrar INSTANCE = new SpongeRawCommandRegistrar(); diff --git a/src/main/java/org/spongepowered/common/command/sponge/SpongeCommand.java b/src/main/java/org/spongepowered/common/command/sponge/SpongeCommand.java index 5e4a238cd8a..8c49fb85203 100644 --- a/src/main/java/org/spongepowered/common/command/sponge/SpongeCommand.java +++ b/src/main/java/org/spongepowered/common/command/sponge/SpongeCommand.java @@ -76,9 +76,9 @@ public class SpongeCommand { protected static final Component LONG_INDENT_COMPONENT = Component.text(SpongeCommand.LONG_INDENT); protected static final DecimalFormat THREE_DECIMAL_DIGITS_FORMATTER = new DecimalFormat("########0.000"); - private final Parameter.Key pluginContainerKey = Parameter.key("plugin", TypeTokens.PLUGIN_CONTAINER_TOKEN); - private final Parameter.Key commandMappingKey = Parameter.key("command", TypeTokens.COMMAND_MAPPING); - private final Parameter.Key worldPropertiesKey = Parameter.key("world", TypeTokens.WORLD_PROPERTIES_TOKEN); + private final Parameter.Key pluginContainerKey = Parameter.key("plugin", PluginContainer.class); + private final Parameter.Key commandMappingKey = Parameter.key("command", CommandMapping.class); + private final Parameter.Key worldPropertiesKey = Parameter.key("world", WorldProperties.class); @Nullable private Component versionText = null; @@ -244,7 +244,7 @@ private Command.Parameterized chunksSubcommand() { return CommandResult.success(); }) .build(); - final Parameter.Key dumpAllKey = Parameter.key("dumpAll", TypeTokens.BOOLEAN_TOKEN); + final Parameter.Key dumpAllKey = Parameter.key("dumpAll", Boolean.class); final Command.Parameterized dumpCommand = Command.builder() .parameter(Parameter.literal(Boolean.class, true, "all").optional().setKey(dumpAllKey).build()) .setExecutor(context -> { diff --git a/src/main/java/org/spongepowered/common/config/CatalogTypeTypeSerializer.java b/src/main/java/org/spongepowered/common/config/CatalogTypeTypeSerializer.java index 52971bf64b6..ec59b380cc4 100644 --- a/src/main/java/org/spongepowered/common/config/CatalogTypeTypeSerializer.java +++ b/src/main/java/org/spongepowered/common/config/CatalogTypeTypeSerializer.java @@ -24,38 +24,49 @@ */ package org.spongepowered.common.config; -import com.google.common.reflect.TypeToken; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; -import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer; +import io.leangen.geantyref.GenericTypeReflector; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.spongepowered.api.registry.GameRegistry; +import org.spongepowered.configurate.ConfigurationNode; +import org.spongepowered.configurate.serialize.SerializationException; +import org.spongepowered.configurate.serialize.TypeSerializer; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.CatalogType; -import org.spongepowered.common.SpongeCommon; +import java.lang.reflect.Type; import java.util.Optional; +import javax.inject.Inject; + /** * A {@link TypeSerializer} implementation that allows CatalogType values to be used in object-mapped classes. */ public final class CatalogTypeTypeSerializer implements TypeSerializer { - public static final TypeToken TYPE = TypeToken.of(CatalogType.class); - public static final CatalogTypeTypeSerializer INSTANCE = new CatalogTypeTypeSerializer(); + public static final Class TYPE = CatalogType.class; + + private final GameRegistry registry; - private CatalogTypeTypeSerializer() { + @Inject + CatalogTypeTypeSerializer(final GameRegistry registry) { + this.registry = registry; } @Override - public CatalogType deserialize(final TypeToken type, final ConfigurationNode value) throws ObjectMappingException { - final Optional ret = SpongeCommon.getRegistry().getCatalogRegistry() - .get(type.getRawType().asSubclass(CatalogType.class), ResourceKey.resolve(value.getString())); + public CatalogType deserialize(final Type type, final ConfigurationNode value) throws SerializationException { + final Optional ret = this.registry.getCatalogRegistry() + .get(GenericTypeReflector.erase(type).asSubclass(CatalogType.class), ResourceKey.resolve(value.getString())); if (!ret.isPresent()) { - throw new ObjectMappingException("Input '" + value.getValue() + "' was not a valid value for type " + type); + throw new SerializationException("Input '" + value.raw() + "' was not a valid value for type " + type); } return ret.get(); } @Override - public void serialize(final TypeToken type, final CatalogType obj, final ConfigurationNode value) { - value.setValue(obj.getKey().getFormatted()); + public void serialize(final Type type, final @Nullable CatalogType obj, final ConfigurationNode value) throws SerializationException { + if (obj == null) { + value.set(null); + } else { + value.set(obj.getKey().getFormatted()); + } } } diff --git a/src/main/java/org/spongepowered/common/config/DataSerializableTypeSerializer.java b/src/main/java/org/spongepowered/common/config/DataSerializableTypeSerializer.java index 0b210d2b01b..99303291f9f 100644 --- a/src/main/java/org/spongepowered/common/config/DataSerializableTypeSerializer.java +++ b/src/main/java/org/spongepowered/common/config/DataSerializableTypeSerializer.java @@ -24,43 +24,53 @@ */ package org.spongepowered.common.config; -import com.google.common.reflect.TypeToken; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.objectmapping.ObjectMapper; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; -import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer; +import io.leangen.geantyref.GenericTypeReflector; +import org.spongepowered.api.data.DataManager; +import org.spongepowered.configurate.ConfigurationNode; +import org.spongepowered.configurate.objectmapping.ObjectMapper; +import org.spongepowered.configurate.serialize.SerializationException; +import org.spongepowered.configurate.serialize.TypeSerializer; import org.spongepowered.api.CatalogType; import org.spongepowered.api.Sponge; import org.spongepowered.api.data.persistence.DataSerializable; -import org.spongepowered.api.data.persistence.DataTranslators; import org.spongepowered.common.data.persistence.ConfigurateTranslator; +import java.lang.reflect.Type; +import java.util.function.Predicate; + +import javax.inject.Inject; + /** * An implementation of {@link TypeSerializer} so that DataSerializables can be * provided in {@link ObjectMapper}-using classes. */ public final class DataSerializableTypeSerializer implements TypeSerializer { - public static final TypeToken TYPE = TypeToken.of(DataSerializable.class); - public static final DataSerializableTypeSerializer INSTANCE = new DataSerializableTypeSerializer(); + private static final Class TYPE = DataSerializable.class; + + public static Predicate predicate() { + return x -> GenericTypeReflector.isSuperType(DataSerializableTypeSerializer.TYPE, x) + && !GenericTypeReflector.isSuperType(CatalogTypeTypeSerializer.TYPE, x); + } + + private final DataManager dataManager; - private DataSerializableTypeSerializer() { + @Inject + DataSerializableTypeSerializer(final DataManager dataManager) { + this.dataManager = dataManager; } @Override - public DataSerializable deserialize(TypeToken type, ConfigurationNode value) throws ObjectMappingException { - if (type.getRawType().isAssignableFrom(CatalogType.class)) { - return (DataSerializable) CatalogTypeTypeSerializer.INSTANCE.deserialize(type, value); - } - Class clazz = type.getRawType(); - return Sponge.getDataManager() + public DataSerializable deserialize(final Type type, final ConfigurationNode value) throws SerializationException { + final Class clazz = GenericTypeReflector.erase(type); + return this.dataManager .deserialize(clazz.asSubclass(DataSerializable.class), ConfigurateTranslator.instance().translate(value)) - .orElseThrow(() -> new ObjectMappingException("Could not translate DataSerializable of type: " + clazz.getName())); + .orElseThrow(() -> new SerializationException("Could not translate DataSerializable of type: " + clazz.getName())); } @Override - public void serialize(TypeToken type, DataSerializable obj, ConfigurationNode value) throws ObjectMappingException { - if (obj instanceof CatalogType) { - CatalogTypeTypeSerializer.INSTANCE.serialize(type, (CatalogType) obj, value); + public void serialize(final Type type, final DataSerializable obj, final ConfigurationNode value) throws SerializationException { + if (obj == null) { + value.raw(null); } else { ConfigurateTranslator.instance().translateDataToNode(value, obj.toContainer()); } diff --git a/src/main/java/org/spongepowered/common/config/PluginConfigManager.java b/src/main/java/org/spongepowered/common/config/PluginConfigManager.java index 92ef8bb9398..45b89a3c0f7 100644 --- a/src/main/java/org/spongepowered/common/config/PluginConfigManager.java +++ b/src/main/java/org/spongepowered/common/config/PluginConfigManager.java @@ -24,51 +24,78 @@ */ package org.spongepowered.common.config; -import com.google.inject.Injector; +import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.inject.Singleton; -import ninja.leaping.configurate.objectmapping.DefaultObjectMapperFactory; -import ninja.leaping.configurate.objectmapping.GuiceObjectMapperFactory; -import ninja.leaping.configurate.objectmapping.ObjectMapperFactory; +import org.spongepowered.api.CatalogType; +import org.spongepowered.common.adventure.SpongeAdventure; import org.spongepowered.api.config.ConfigManager; import org.spongepowered.api.config.ConfigRoot; import org.spongepowered.common.SpongeCommon; -import org.spongepowered.common.plugin.PluginContainerExtension; +import org.spongepowered.configurate.ConfigurationOptions; +import org.spongepowered.configurate.reference.WatchServiceListener; +import org.spongepowered.configurate.serialize.TypeSerializerCollection; import org.spongepowered.plugin.PluginContainer; +import java.io.IOException; + +import javax.inject.Inject; + /** * Implementation of service to manage configurations. */ @Singleton public final class PluginConfigManager implements ConfigManager { + private final TypeSerializerCollection serializers; + private final WatchServiceListener listener; + + @Inject + PluginConfigManager(final CatalogTypeTypeSerializer catalogSerializer, final DataSerializableTypeSerializer dataSerializableSerializer) throws IOException { + // TODO: Move this onto the async scheduler, rather than shared FJ pool? + this.listener = WatchServiceListener.builder() + .threadFactory(new ThreadFactoryBuilder().setDaemon(true).setNameFormat("SpongeCommon-WatchService-%d").build()) + .build(); + + this.serializers = TypeSerializerCollection.defaults().childBuilder() + .register(CatalogType.class, catalogSerializer) + // We have a separate type serializer for CatalogTypes, so we explicitly discount them here. + // See https://github.com/SpongePowered/SpongeCommon/issues/1348 + .register(DataSerializableTypeSerializer.predicate(), dataSerializableSerializer) + // TODO: register DataTranslators? + .registerAll(SpongeAdventure.CONFIGURATE.serializers()) + .build(); + } + @Override - public ConfigRoot getSharedConfig(PluginContainer container) { - return new PluginConfigRoot(getMapperFactory(container), container.getMetadata().getId().toLowerCase(), SpongeCommon.getPluginConfigDirectory()); + public ConfigRoot getSharedConfig(final PluginContainer container) { + return new PluginConfigRoot(this.serializers, container.getMetadata().getId().toLowerCase(), + SpongeCommon.getPluginConfigDirectory()); } @Override - public ConfigRoot getPluginConfig(PluginContainer container) { - return new PluginConfigRoot(getMapperFactory(container), container.getMetadata().getId().toLowerCase(), SpongeCommon - .getPluginConfigDirectory().resolve(container.getMetadata().getId().toLowerCase())); + public ConfigRoot getPluginConfig(final PluginContainer container) { + return new PluginConfigRoot(this.serializers, container.getMetadata().getId().toLowerCase(), + SpongeCommon.getPluginConfigDirectory().resolve(container.getMetadata().getId().toLowerCase())); } - public static ConfigRoot getSharedRoot(PluginContainer container) { - final String name = container.getMetadata().getId(); - return new PluginConfigRoot(getMapperFactory(container), name, SpongeCommon.getPluginConfigDirectory()); + @Override + public TypeSerializerCollection getSerializers() { + return this.serializers; + } + + @Override + public WatchServiceListener getWatchServiceListener() { + return this.listener; } - public static ConfigRoot getPrivateRoot(PluginContainer container) { - final String name = container.getMetadata().getId(); - return new PluginConfigRoot(getMapperFactory(container), name, SpongeCommon.getPluginConfigDirectory().resolve(name)); + public static ConfigurationOptions getOptions(final TypeSerializerCollection serializers) { + return ConfigurationOptions.defaults() + .implicitInitialization(true) + .shouldCopyDefaults(true) + .serializers(serializers); } - private static ObjectMapperFactory getMapperFactory(PluginContainer container) { - if (container instanceof PluginContainerExtension) { - Injector injector = ((PluginContainerExtension) container).getInjector(); - if (injector != null) { - return injector.getInstance(GuiceObjectMapperFactory.class); - } - } - return DefaultObjectMapperFactory.getInstance(); + public void close() throws IOException { + this.listener.close(); } } diff --git a/src/main/java/org/spongepowered/common/config/PluginConfigRoot.java b/src/main/java/org/spongepowered/common/config/PluginConfigRoot.java index c2c550df3a0..bac36412f3a 100644 --- a/src/main/java/org/spongepowered/common/config/PluginConfigRoot.java +++ b/src/main/java/org/spongepowered/common/config/PluginConfigRoot.java @@ -24,39 +24,38 @@ */ package org.spongepowered.common.config; -import ninja.leaping.configurate.ConfigurationOptions; -import ninja.leaping.configurate.commented.CommentedConfigurationNode; -import ninja.leaping.configurate.hocon.HoconConfigurationLoader; -import ninja.leaping.configurate.loader.ConfigurationLoader; -import ninja.leaping.configurate.objectmapping.ObjectMapperFactory; +import org.spongepowered.configurate.ConfigurationOptions; +import org.spongepowered.configurate.CommentedConfigurationNode; +import org.spongepowered.configurate.hocon.HoconConfigurationLoader; +import org.spongepowered.configurate.loader.ConfigurationLoader; import org.spongepowered.api.config.ConfigRoot; import org.spongepowered.common.SpongeCommon; -import org.spongepowered.common.adventure.SpongeAdventure; +import org.spongepowered.configurate.serialize.TypeSerializerCollection; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; /** - * Root for sponge configurations. + * Root for plugin configurations. */ public class PluginConfigRoot implements ConfigRoot { - private final ObjectMapperFactory mapperFactory; + private final TypeSerializerCollection serializers; private final String pluginName; private final Path baseDir; - PluginConfigRoot(ObjectMapperFactory mapperFactory, String pluginName, Path baseDir) { - this.mapperFactory = mapperFactory; + PluginConfigRoot(final TypeSerializerCollection serializers, final String pluginName, final Path baseDir) { + this.serializers = serializers; this.pluginName = pluginName; this.baseDir = baseDir; } @Override public Path getConfigPath() { - Path configFile = this.baseDir.resolve(this.pluginName + ".conf"); + final Path configFile = this.baseDir.resolve(this.pluginName + ".conf"); try { Files.createDirectories(this.baseDir); - } catch (IOException e) { + } catch (final IOException e) { SpongeCommon.getLogger().error("Failed to create plugin dir for {} at {}", this.pluginName, this.baseDir, e); } return configFile; @@ -64,11 +63,14 @@ public Path getConfigPath() { @Override public ConfigurationLoader getConfig() { + return this.getConfig(PluginConfigManager.getOptions(this.serializers)); + } + + @Override + public ConfigurationLoader getConfig(final ConfigurationOptions options) { return HoconConfigurationLoader.builder() - .setPath(this.getConfigPath()) - .setDefaultOptions(ConfigurationOptions.defaults() - .withObjectMapperFactory(this.mapperFactory) - .withSerializers(coll -> SpongeAdventure.CONFIGURATE.addSerializersTo(coll))) + .path(this.getConfigPath()) + .defaultOptions(options) .build(); } diff --git a/src/main/java/org/spongepowered/common/config/SpongeGameConfigs.java b/src/main/java/org/spongepowered/common/config/SpongeGameConfigs.java index f6eb4e21dfe..dcad60d6955 100644 --- a/src/main/java/org/spongepowered/common/config/SpongeGameConfigs.java +++ b/src/main/java/org/spongepowered/common/config/SpongeGameConfigs.java @@ -24,9 +24,8 @@ */ package org.spongepowered.common.config; -import com.google.common.reflect.TypeToken; -import ninja.leaping.configurate.commented.CommentedConfigurationNode; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; +import io.leangen.geantyref.TypeToken; +import org.spongepowered.configurate.CommentedConfigurationNode; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.checkerframework.checker.nullness.qual.Nullable; @@ -42,6 +41,7 @@ import org.spongepowered.common.applaunch.config.inheritable.WorldConfig; import org.spongepowered.common.config.tracker.TrackerConfig; import org.spongepowered.common.world.server.SpongeWorldManager; +import org.spongepowered.configurate.ConfigurateException; import java.io.IOException; import java.nio.file.DirectoryStream; @@ -119,7 +119,7 @@ public static InheritableConfigHandle createWorld(final @Nullable D SpongeConfigs.getGlobalInheritable()); config.load(); return config; - } catch (final IOException | ObjectMappingException ex) { + } catch (final ConfigurateException ex) { LOGGER.error("Unable to load configuration for world {}. Sponge will use a " + "fallback configuration with default values that will not save.", world, ex); return SpongeConfigs.createDetached(); diff --git a/src/main/java/org/spongepowered/common/config/customdata/CustomDataConfig.java b/src/main/java/org/spongepowered/common/config/customdata/CustomDataConfig.java index 94c5c682873..2337bf48eb8 100644 --- a/src/main/java/org/spongepowered/common/config/customdata/CustomDataConfig.java +++ b/src/main/java/org/spongepowered/common/config/customdata/CustomDataConfig.java @@ -24,21 +24,21 @@ */ package org.spongepowered.common.config.customdata; -import ninja.leaping.configurate.objectmapping.Setting; import org.spongepowered.common.applaunch.config.core.Config; +import org.spongepowered.configurate.objectmapping.meta.Setting; public final class CustomDataConfig implements Config { public static final String FILE_NAME = "custom_data.conf"; - @Setting(value = "data-registration") - private CustomDataRegistrationCategory datalists = new CustomDataRegistrationCategory(); + @Setting + private CustomDataRegistrationCategory dataRegistration = new CustomDataRegistrationCategory(); public CustomDataConfig() { } public CustomDataRegistrationCategory getDataRegistrationConfig() { - return this.datalists; + return this.dataRegistration; } } diff --git a/src/main/java/org/spongepowered/common/config/customdata/CustomDataRegistrationCategory.java b/src/main/java/org/spongepowered/common/config/customdata/CustomDataRegistrationCategory.java index 49f2ebac332..b26d8d93f50 100644 --- a/src/main/java/org/spongepowered/common/config/customdata/CustomDataRegistrationCategory.java +++ b/src/main/java/org/spongepowered/common/config/customdata/CustomDataRegistrationCategory.java @@ -24,13 +24,14 @@ */ package org.spongepowered.common.config.customdata; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; import org.spongepowered.api.data.DataRegistration; import org.spongepowered.api.data.persistence.DataView; import org.spongepowered.api.data.persistence.InvalidDataException; import org.spongepowered.common.util.PrettyPrinter; import org.spongepowered.common.data.persistence.SerializedDataTransaction; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; import java.util.Collection; import java.util.Set; @@ -47,16 +48,17 @@ public class CustomDataRegistrationCategory { * * This should be populated after the default registrations are done. */ - @Setting(value = "registered-data", comment = "An auto generated list, by Sponge, to provide a list of \n" - + "registered custom data manipulators by plugins. Since \n" - + "the list is generated AFTER the game starts, modifying \n" - + "this list will not affect Sponge's system in any way. \n" - + "However, it is advisable to view what registered datas \n" - + "exist on a server instance, such that when Sponge completes \n" - + "startup, it will be verified that all existing registrations \n" - + "are accounted for. A warning will be emitted for any existing \n" - + "registrations that were not registered, and moved to the \n" - + "'failed-data-list'.") + @Setting(value = "registered-data") + @Comment("An auto generated list, by Sponge, to provide a list of \n" + + "registered custom data manipulators by plugins. Since \n" + + "the list is generated AFTER the game starts, modifying \n" + + "this list will not affect Sponge's system in any way. \n" + + "However, it is advisable to view what registered datas \n" + + "exist on a server instance, such that when Sponge completes \n" + + "startup, it will be verified that all existing registrations \n" + + "are accounted for. A warning will be emitted for any existing \n" + + "registrations that were not registered, and moved to the \n" + + "'failed-data-list'.") private Set registeredDataIds = new ConcurrentSkipListSet<>(); /** @@ -64,30 +66,33 @@ public class CustomDataRegistrationCategory { * read from file, except after startup, to specify which id's can * be "saved". */ - @Setting(value = "failed-data-list", comment = "An auto generated list, by Sponge, to discover and list \n" - + "all failed custom data deserializations at runtime due \n" - + "to a lack of the registrations being made by a plugin. \n" - + "Not to be confused by failed deserialization due to bad data. \n" - + "Modifying the list will result in no effect as Sponge auto \n" - + "generates this list. This is merely for user configuration.") + @Setting(value = "failed-data-list") + @Comment("An auto generated list, by Sponge, to discover and list \n" + + "all failed custom data deserializations at runtime due \n" + + "to a lack of the registrations being made by a plugin. \n" + + "Not to be confused by failed deserialization due to bad data. \n" + + "Modifying the list will result in no effect as Sponge auto \n" + + "generates this list. This is merely for user configuration.") private Set discoveredFailedDatas = new ConcurrentSkipListSet<>(); /** * This is a configurable list of id's that are to be "purged" on * discovery. */ - @Setting(value = "data-to-purge", comment = "A configurable list of registration ids that are to be removed \n" - + "when discovered for deserialization. This can be controlled by \n" - + "commands in sponge. It is adviseable to refer to the lists made \n" - + "available through 'failed-data-list', as using any id's from \n" - + "'registered-data' will result in custom data being deleted at \n" - + "every load.") + @Setting(value = "data-to-purge") + @Comment("A configurable list of registration ids that are to be removed \n" + + "when discovered for deserialization. This can be controlled by \n" + + "commands in sponge. It is adviseable to refer to the lists made \n" + + "available through 'failed-data-list', as using any id's from \n" + + "'registered-data' will result in custom data being deleted at \n" + + "every load.") private Set purgeDatas = new ConcurrentSkipListSet<>(); - @Setting(value = "print-on-discovery", comment = "In the cases where there is already previously discovered data \n" - + "we don't want to spam the log on each discovery in certain \n" - + "contexts. If it is required, we still can emit the log warning \n" - + "when necessary.") + @Setting(value = "print-on-discovery") + @Comment("In the cases where there is already previously discovered data \n" + + "we don't want to spam the log on each discovery in certain \n" + + "contexts. If it is required, we still can emit the log warning \n" + + "when necessary.") private boolean printFailedDataOnDiscovery = false; diff --git a/src/main/java/org/spongepowered/common/config/metrics/MetricsConfiguration.java b/src/main/java/org/spongepowered/common/config/metrics/MetricsConfiguration.java index 3b8a24b7e34..113d0c4e51c 100644 --- a/src/main/java/org/spongepowered/common/config/metrics/MetricsConfiguration.java +++ b/src/main/java/org/spongepowered/common/config/metrics/MetricsConfiguration.java @@ -24,12 +24,14 @@ */ package org.spongepowered.common.config.metrics; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; -import ninja.leaping.configurate.transformation.ConfigurationTransformation; +import org.spongepowered.configurate.ScopedConfigurationNode; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; import org.spongepowered.api.util.Tristate; import org.spongepowered.common.applaunch.config.core.Config; import org.spongepowered.common.applaunch.config.core.SpongeConfigs; +import org.spongepowered.configurate.transformation.ConfigurationTransformation; +import org.spongepowered.configurate.transformation.NodePath; import org.spongepowered.plugin.PluginContainer; import java.util.Collections; @@ -41,18 +43,18 @@ public class MetricsConfiguration implements Config { public static String FILE_NAME = SpongeConfigs.METRICS_NAME; - @Setting(value = "global-state", comment = "The global collection state that should be respected by all plugins that have no specified " - + "collection state. If undefined then it is treated as disabled.") + @Comment("The global collection state that should be respected by all plugins that have no specified " + + "collection state. If undefined then it is treated as disabled.") private Tristate globalState = Tristate.UNDEFINED; - @Setting(value = "plugin-states", comment = "Plugin-specific collection states that override the global collection state.") + @Comment("Plugin-specific collection states that override the global collection state.") private final Map pluginStates = new HashMap<>(); public Tristate getGlobalCollectionState() { return this.globalState; } - public Tristate getCollectionState(PluginContainer container) { + public Tristate getCollectionState(final PluginContainer container) { final Tristate pluginState = this.pluginStates.get(container.getMetadata().getId()); return pluginState == null ? Tristate.UNDEFINED : pluginState; } @@ -62,11 +64,10 @@ public Map getCollectionStates() { } @Override - public ConfigurationTransformation getTransformation() { - return ConfigurationTransformation.versionedBuilder() - .addVersion(1, ConfigurationTransformation.builder() - .addAction(Config.path("metrics"), (path, value) -> new Object[0]) - .build()) + public > ConfigurationTransformation getTransformation() { + return ConfigurationTransformation.versionedBuilder() + .makeVersion(1, b -> + b.addAction(NodePath.path("metrics"), (path, value) -> new Object[0])) .build(); } } diff --git a/src/main/java/org/spongepowered/common/config/tracker/BlockEntityTrackerCategory.java b/src/main/java/org/spongepowered/common/config/tracker/BlockEntityTrackerCategory.java index a56026278ff..c14eb26de11 100644 --- a/src/main/java/org/spongepowered/common/config/tracker/BlockEntityTrackerCategory.java +++ b/src/main/java/org/spongepowered/common/config/tracker/BlockEntityTrackerCategory.java @@ -24,8 +24,9 @@ */ package org.spongepowered.common.config.tracker; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; import java.util.HashMap; import java.util.Map; @@ -33,10 +34,11 @@ @ConfigSerializable public class BlockEntityTrackerCategory { - @Setting(value = "auto-populate", comment = "If 'true', newly discovered tileentities will be added to this config with default settings.") + @Comment("If 'true', newly discovered tileentities will be added to this config with default settings.") private boolean autoPopulate = false; - @Setting(value = "mods", comment = "Per-mod tileentity id mappings for controlling tracking behavior") + @Setting("mods") + @Comment("Per-mod tileentity id mappings for controlling tracking behavior") private Map modMapping = new HashMap<>(); public Map getModMappings() { diff --git a/src/main/java/org/spongepowered/common/config/tracker/BlockEntityTrackerModCategory.java b/src/main/java/org/spongepowered/common/config/tracker/BlockEntityTrackerModCategory.java index ee8177db26c..df994405e0f 100644 --- a/src/main/java/org/spongepowered/common/config/tracker/BlockEntityTrackerModCategory.java +++ b/src/main/java/org/spongepowered/common/config/tracker/BlockEntityTrackerModCategory.java @@ -24,8 +24,9 @@ */ package org.spongepowered.common.config.tracker; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; import java.util.HashMap; import java.util.Map; @@ -33,19 +34,27 @@ @ConfigSerializable public class BlockEntityTrackerModCategory { - @Setting(value = "enabled", comment = "If 'false', all tracking for this mod will be disabled.") - private boolean isEnabled = true; - @Setting(value = TrackerConfig.BLOCK_BULK_CAPTURE, comment = "Set to true to perform block bulk capturing during block entity ticks. (Default: true)") + @Setting @Comment("If 'false', all tracking for this mod will be disabled.") + private boolean enabled = true; + + @Setting(TrackerConfig.BLOCK_BULK_CAPTURE) + @Comment("Set to true to perform block bulk capturing during block entity ticks. (Default: true)") private Map blockBulkCaptureMap = new HashMap<>(); - @Setting(value = TrackerConfig.BLOCK_EVENT_CREATION, comment = "Set to true to create and fire block events during block entity ticks. (Default: true)") + + @Setting(TrackerConfig.BLOCK_EVENT_CREATION) + @Comment("Set to true to create and fire block events during block entity ticks. (Default: true)") private Map blockEventCreationMap = new HashMap<>(); - @Setting(value = TrackerConfig.ENTITY_BULK_CAPTURE, comment = "Set to true to perform entity bulk capturing during block entity ticks. (Default: true)") + + @Setting(TrackerConfig.ENTITY_BULK_CAPTURE) + @Comment("Set to true to perform entity bulk capturing during block entity ticks. (Default: true)") private Map entityBulkCaptureMap = new HashMap<>(); - @Setting(value = TrackerConfig.ENTITY_EVENT_CREATION, comment = "Set to true to create and fire entity events during block entity ticks. (Default: true)") + + @Setting(TrackerConfig.ENTITY_EVENT_CREATION) + @Comment("Set to true to create and fire entity events during block entity ticks. (Default: true)") private Map entityEventCreationMap = new HashMap<>(); public boolean isEnabled() { - return this.isEnabled; + return this.enabled; } public Map getBlockBulkCaptureMap() { diff --git a/src/main/java/org/spongepowered/common/config/tracker/BlockTrackerCategory.java b/src/main/java/org/spongepowered/common/config/tracker/BlockTrackerCategory.java index 268d2d4083b..58539aa20db 100644 --- a/src/main/java/org/spongepowered/common/config/tracker/BlockTrackerCategory.java +++ b/src/main/java/org/spongepowered/common/config/tracker/BlockTrackerCategory.java @@ -24,8 +24,10 @@ */ package org.spongepowered.common.config.tracker; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; + +import org.spongepowered.configurate.objectmapping.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; import java.util.HashMap; import java.util.Map; @@ -33,10 +35,12 @@ @ConfigSerializable public class BlockTrackerCategory { - @Setting(value = "auto-populate", comment = "If 'true', newly discovered blocks will be added to this config with default settings.") + @Setting + @Comment("If 'true', newly discovered blocks will be added to this config with default settings.") private boolean autoPopulate = false; - @Setting(value = "mods", comment = "Per-mod block id mappings for controlling tracking behavior") + @Setting(value = "mods") + @Comment("Per-mod block id mappings for controlling tracking behavior") private Map modMapping = new HashMap<>(); public BlockTrackerCategory() { diff --git a/src/main/java/org/spongepowered/common/config/tracker/BlockTrackerModCategory.java b/src/main/java/org/spongepowered/common/config/tracker/BlockTrackerModCategory.java index 40d895f6f64..7979bd2ed4b 100644 --- a/src/main/java/org/spongepowered/common/config/tracker/BlockTrackerModCategory.java +++ b/src/main/java/org/spongepowered/common/config/tracker/BlockTrackerModCategory.java @@ -24,8 +24,9 @@ */ package org.spongepowered.common.config.tracker; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; import java.util.HashMap; import java.util.Map; @@ -33,21 +34,27 @@ @ConfigSerializable public class BlockTrackerModCategory { - @Setting(value = "enabled", comment = "If 'false', all tracking for this mod will be ignored.") + @Setting("enabled") + @Comment("If 'false', all tracking for this mod will be ignored.") private boolean isEnabled = true; - @Setting(value = TrackerConfig.BLOCK_BULK_CAPTURE, comment = "Set to true to perform block bulk capturing during block ticks. (Default: true)") + + @Setting(TrackerConfig.BLOCK_BULK_CAPTURE) + @Comment("Set to true to perform block bulk capturing during block ticks. (Default: true)") private Map blockBulkCaptureMap = new HashMap<>(); - @Setting(value = TrackerConfig.ENTITY_BULK_CAPTURE, comment = "Set to true to perform entity bulk capturing during block ticks. (Default: true)") + @Setting(TrackerConfig.ENTITY_BULK_CAPTURE) + @Comment("Set to true to perform entity bulk capturing during block ticks. (Default: true)") private Map entityBulkCaptureMap = new HashMap<>(); - @Setting(value = TrackerConfig.BLOCK_EVENT_CREATION, comment = "Set to true to create and fire block events during block ticks. (Default: true)") + @Setting(TrackerConfig.BLOCK_EVENT_CREATION) + @Comment("Set to true to create and fire block events during block ticks. (Default: true)") private Map blockEventCreationMap = new HashMap<>(); - @Setting(value = TrackerConfig.ENTITY_EVENT_CREATION, comment = "Set to true to create and fire entity events during block ticks. (Default: true)") + @Setting(TrackerConfig.ENTITY_EVENT_CREATION) + @Comment("Set to true to create and fire entity events during block ticks. (Default: true)") private Map entityEventCreationMap = new HashMap<>(); public BlockTrackerModCategory() { } - public BlockTrackerModCategory(String modId) { + public BlockTrackerModCategory(final String modId) { } public boolean isEnabled() { diff --git a/src/main/java/org/spongepowered/common/config/tracker/EntityTrackerCategory.java b/src/main/java/org/spongepowered/common/config/tracker/EntityTrackerCategory.java index 2fed9f72c60..89c55bc5ab6 100644 --- a/src/main/java/org/spongepowered/common/config/tracker/EntityTrackerCategory.java +++ b/src/main/java/org/spongepowered/common/config/tracker/EntityTrackerCategory.java @@ -24,8 +24,9 @@ */ package org.spongepowered.common.config.tracker; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; import java.util.HashMap; import java.util.Map; @@ -33,10 +34,12 @@ @ConfigSerializable public class EntityTrackerCategory { - @Setting(value = "auto-populate", comment = "If 'true', newly discovered entities will be added to this config with default settings.") + @Setting + @Comment("If 'true', newly discovered entities will be added to this config with default settings.") private boolean autoPopulate = false; - @Setting(value = "mods", comment = "Per-mod entity id mappings for controlling tracking behavior") + @Setting("mods") + @Comment("Per-mod entity id mappings for controlling tracking behavior") private Map modMapping = new HashMap<>(); public Map getModMappings() { diff --git a/src/main/java/org/spongepowered/common/config/tracker/EntityTrackerModCategory.java b/src/main/java/org/spongepowered/common/config/tracker/EntityTrackerModCategory.java index af3fb74ec7a..f55c39f2f23 100644 --- a/src/main/java/org/spongepowered/common/config/tracker/EntityTrackerModCategory.java +++ b/src/main/java/org/spongepowered/common/config/tracker/EntityTrackerModCategory.java @@ -24,8 +24,9 @@ */ package org.spongepowered.common.config.tracker; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; import java.util.HashMap; import java.util.Map; @@ -33,15 +34,24 @@ @ConfigSerializable public class EntityTrackerModCategory { - @Setting(value = "enabled", comment = "If 'false', all tracking for this mod will be ignored.") - private boolean isEnabled = true; - @Setting(value = TrackerConfig.BLOCK_BULK_CAPTURE, comment = "Set to true to perform block bulk capturing during entity ticks. (Default: true)") + @Setting + @Comment("If 'false', all tracking for this mod will be ignored.") + private boolean enabled = true; + + @Setting(TrackerConfig.BLOCK_BULK_CAPTURE) + @Comment("Set to true to perform block bulk capturing during entity ticks. (Default: true)") private Map blockBulkCaptureMap = new HashMap<>(); - @Setting(value = TrackerConfig.BLOCK_EVENT_CREATION, comment = "Set to true to create and fire block events during entity ticks. (Default: true)") + + @Setting(TrackerConfig.BLOCK_EVENT_CREATION) + @Comment("Set to true to create and fire block events during entity ticks. (Default: true)") private Map blockEventCreationMap = new HashMap<>(); - @Setting(value = TrackerConfig.ENTITY_BULK_CAPTURE, comment = "Set to true to perform entity bulk capturing during entity ticks. (Default: true)") + + @Setting(TrackerConfig.ENTITY_BULK_CAPTURE) + @Comment("Set to true to perform entity bulk capturing during entity ticks. (Default: true)") private Map entityBulkCaptureMap = new HashMap<>(); - @Setting(value = TrackerConfig.ENTITY_EVENT_CREATION, comment = "Set to true to create and fire entity events during entity ticks. (Default: true)") + + @Setting(TrackerConfig.ENTITY_EVENT_CREATION) + @Comment("Set to true to create and fire entity events during entity ticks. (Default: true)") private Map entityEventCreationMap = new HashMap<>(); public EntityTrackerModCategory() { @@ -62,7 +72,7 @@ public EntityTrackerModCategory(String name) { } public boolean isEnabled() { - return this.isEnabled; + return this.enabled; } public Map getBlockBulkCaptureMap() { diff --git a/src/main/java/org/spongepowered/common/config/tracker/TrackerConfig.java b/src/main/java/org/spongepowered/common/config/tracker/TrackerConfig.java index 42692b19df0..311a591e97b 100644 --- a/src/main/java/org/spongepowered/common/config/tracker/TrackerConfig.java +++ b/src/main/java/org/spongepowered/common/config/tracker/TrackerConfig.java @@ -24,10 +24,10 @@ */ package org.spongepowered.common.config.tracker; -import ninja.leaping.configurate.objectmapping.Setting; import org.spongepowered.common.applaunch.config.core.Config; import org.spongepowered.common.event.tracking.IPhaseState; import org.spongepowered.common.event.tracking.PhaseContext; +import org.spongepowered.configurate.objectmapping.meta.Setting; public class TrackerConfig implements Config { diff --git a/src/main/java/org/spongepowered/common/data/SpongeDataManager.java b/src/main/java/org/spongepowered/common/data/SpongeDataManager.java index 1cb17119495..8a3953abebf 100644 --- a/src/main/java/org/spongepowered/common/data/SpongeDataManager.java +++ b/src/main/java/org/spongepowered/common/data/SpongeDataManager.java @@ -27,7 +27,7 @@ import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.MapMaker; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import com.google.inject.Inject; import com.google.inject.Singleton; import com.mojang.datafixers.DataFixer; @@ -37,9 +37,7 @@ import net.minecraft.nbt.ListNBT; import net.minecraft.util.Util; import net.minecraft.util.registry.Registry; -import ninja.leaping.configurate.objectmapping.serialize.TypeSerializerCollection; -import ninja.leaping.configurate.objectmapping.serialize.TypeSerializers; -import org.spongepowered.api.CatalogType; +import org.spongepowered.configurate.serialize.TypeSerializerCollection; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.Sponge; import org.spongepowered.api.data.DataHolder; @@ -91,20 +89,6 @@ public final class SpongeDataManager implements DataManager { private static final SpongeDataManager INSTANCE = new SpongeDataManager(); - private static final TypeToken catalogTypeToken = TypeToken.of(CatalogType.class); - private static final TypeToken dataSerializableTypeToken = TypeToken.of(DataSerializable.class); - - static { - TypeSerializerCollection.defaults().register( - // We have a separate type serializer for CatalogTypes, so we explicitly discount them here. - // See https://github.com/SpongePowered/SpongeCommon/issues/1348 - x -> DataSerializableTypeSerializer.TYPE.isSupertypeOf(x) - && !CatalogTypeTypeSerializer.TYPE.isSupertypeOf(x), - DataSerializableTypeSerializer.INSTANCE - ); - } - - public static final DataFixer spongeDataFixer = addFixers(new DataFixerBuilder(Constants.Sponge.SPONGE_DATA_VERSION)).build(Util.getServerExecutor()); static DataFixerBuilder addFixers(DataFixerBuilder builder) { @@ -350,7 +334,7 @@ public void serializeCustomData(CompoundNBT compound, Object object) { manipulator.getKeys().stream().map(this::getDataRegistration) .filter(Optional::isPresent).map(Optional::get).distinct().forEach(registration -> { // For each registration attempt to serialize using the datastore for the dataholder - registration.getDataStore(TypeToken.of(dataHolder.getClass())).ifPresent(dataStore -> { + registration.getDataStore(dataHolder.getClass()).ifPresent(dataStore -> { final DataView serialized = dataStore.serialize(manipulator); if (!serialized.isEmpty()) { // Omit if the datastore did not serialize anything final DataContainer container = DataContainer.createNew(); @@ -406,7 +390,7 @@ public void deserializeCustomData(CompoundNBT compound, Object object) { final Optional registration = dataContainer.getString(Constants.Sponge.DATA_ID) .flatMap(registrationId -> catalogRegistry.get(DataRegistration.class, ResourceKey.resolve(registrationId))); // Find and attempt to deserialize with the datastore for this dataholder - final Optional dataStore = registration.flatMap(r -> r.getDataStore(TypeToken.of(dataHolder.getClass()))); + final Optional dataStore = registration.flatMap(r -> r.getDataStore(dataHolder.getClass())); if (dataStore.isPresent()) { final DataView internalData = dataContainer.getView(Constants.Sponge.INTERNAL_DATA).orElse(DataContainer.createNew()); final Mutable mutable = dataStore.get().deserialize(internalData); diff --git a/src/main/java/org/spongepowered/common/data/SpongeDataRegistration.java b/src/main/java/org/spongepowered/common/data/SpongeDataRegistration.java index 138d9439889..4b5f4ce2f28 100644 --- a/src/main/java/org/spongepowered/common/data/SpongeDataRegistration.java +++ b/src/main/java/org/spongepowered/common/data/SpongeDataRegistration.java @@ -24,7 +24,8 @@ */ package org.spongepowered.common.data; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.GenericTypeReflector; +import io.leangen.geantyref.TypeToken; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.data.DataHolder; import org.spongepowered.api.data.DataProvider; @@ -35,6 +36,7 @@ import org.spongepowered.api.data.value.Value; import org.spongepowered.plugin.PluginContainer; +import java.lang.reflect.Type; import java.util.List; import java.util.Map; import java.util.Optional; @@ -43,7 +45,7 @@ public final class SpongeDataRegistration implements DataRegistration { final ResourceKey key; final List> keys; - final Map dataStoreMap; + final Map dataStoreMap; final Map dataProviderMap; final PluginContainer plugin; @@ -56,20 +58,29 @@ public final class SpongeDataRegistration implements DataRegistration { } @Override - public , E> Optional> getProviderFor(Key key) throws UnregisteredKeyException { + public , E> Optional> getProviderFor(final Key key) throws UnregisteredKeyException { return Optional.ofNullable(this.dataProviderMap.get(key)); } @Override - public Optional getDataStore(TypeToken token) { - DataStore dataStore = this.dataStoreMap.get(token); + public Optional getDataStore(final TypeToken token) { + return getDataStore0(token.getType()); + } + + @Override + public Optional getDataStore(final Class token) { + return getDataStore0(token); + } + + private Optional getDataStore0(final Type type) { + DataStore dataStore = this.dataStoreMap.get(type); if (dataStore != null) { return Optional.of(dataStore); } - for (Map.Entry entry : this.dataStoreMap.entrySet()) { - if (entry.getKey().isSupertypeOf(token)) { + for (final Map.Entry entry : this.dataStoreMap.entrySet()) { + if (GenericTypeReflector.isSuperType(entry.getKey(), type)) { dataStore = entry.getValue(); - this.dataStoreMap.put(token, dataStore); + this.dataStoreMap.put(type, dataStore); return Optional.of(dataStore); } } diff --git a/src/main/java/org/spongepowered/common/data/SpongeDataRegistrationBuilder.java b/src/main/java/org/spongepowered/common/data/SpongeDataRegistrationBuilder.java index 6f8a1de9295..efed19045a6 100644 --- a/src/main/java/org/spongepowered/common/data/SpongeDataRegistrationBuilder.java +++ b/src/main/java/org/spongepowered/common/data/SpongeDataRegistrationBuilder.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.data; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.data.DataHolder; import org.spongepowered.api.data.DataProvider; @@ -36,6 +36,7 @@ import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.util.SpongeCatalogBuilder; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -46,12 +47,12 @@ public final class SpongeDataRegistrationBuilder extends SpongeCatalogBuilder implements DataRegistration.Builder{ Map dataProviderMap = new HashMap<>(); - Map dataStoreMap = new IdentityHashMap<>(); + Map dataStoreMap = new IdentityHashMap<>(); List> keys = new ArrayList<>(); @Override - public DataRegistration.Builder store(DataStore store) throws DuplicateDataStoreException { - for (TypeToken holderType : store.getSupportedTokens()) { + public DataRegistration.Builder store(final DataStore store) throws DuplicateDataStoreException { + for (final Type holderType : store.getSupportedTypes()) { this.dataStoreMap.put(holderType, store); } return this; diff --git a/src/main/java/org/spongepowered/common/data/SpongeKeyValueMatcherBuilder.java b/src/main/java/org/spongepowered/common/data/SpongeKeyValueMatcherBuilder.java index afa0f39e3bf..89f7ba92860 100644 --- a/src/main/java/org/spongepowered/common/data/SpongeKeyValueMatcherBuilder.java +++ b/src/main/java/org/spongepowered/common/data/SpongeKeyValueMatcherBuilder.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.data; +import io.leangen.geantyref.GenericTypeReflector; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.data.Key; import org.spongepowered.api.data.KeyValueMatcher; @@ -101,8 +102,8 @@ public Optional> build(final DataView container) throws Inval if (!operator.isPresent()) { return Optional.empty(); } - final Optional value = container.getObject( - Constants.KeyValueMatcher.VALUE, key.get().getElementToken().getRawType()); + final Optional value = container.getObject(Constants.KeyValueMatcher.VALUE, + GenericTypeReflector.erase(key.get().getElementType())); if (!value.isPresent()) { return Optional.empty(); } diff --git a/src/main/java/org/spongepowered/common/data/key/SpongeKey.java b/src/main/java/org/spongepowered/common/data/key/SpongeKey.java index 0fd232f633e..3d1e2526327 100644 --- a/src/main/java/org/spongepowered/common/data/key/SpongeKey.java +++ b/src/main/java/org/spongepowered/common/data/key/SpongeKey.java @@ -25,7 +25,6 @@ package org.spongepowered.common.data.key; import com.google.common.base.MoreObjects; -import com.google.common.reflect.TypeToken; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.data.DataHolder; import org.spongepowered.api.data.Key; @@ -39,26 +38,27 @@ import org.spongepowered.common.data.value.ValueConstructorFactory; import org.spongepowered.plugin.PluginContainer; +import java.lang.reflect.Type; import java.util.Comparator; import java.util.function.BiPredicate; import java.util.function.Supplier; public final class SpongeKey, E> extends SpongeCatalogType implements Key { - private final TypeToken valueToken; - private final TypeToken elementToken; + private final Type valueType; + private final Type elementType; private final Comparator elementComparator; private final BiPredicate elementIncludesTester; private final ValueConstructor valueConstructor; private final Supplier defaultValueSupplier; private final EmptyDataProvider emptyDataProvider; - public SpongeKey(final ResourceKey key, final TypeToken valueToken, final TypeToken elementToken, + public SpongeKey(final ResourceKey key, final Type valueType, final Type elementType, final Comparator elementComparator, final BiPredicate elementIncludesTester, final Supplier defaultValueSupplier) { super(key); - this.valueToken = valueToken; - this.elementToken = elementToken; + this.valueType = valueType; + this.elementType = elementType; this.elementComparator = elementComparator; this.elementIncludesTester = elementIncludesTester; this.defaultValueSupplier = defaultValueSupplier; @@ -67,13 +67,13 @@ public SpongeKey(final ResourceKey key, final TypeToken valueToken, final Typ } @Override - public TypeToken getValueToken() { - return this.valueToken; + public Type getValueType() { + return this.valueType; } @Override - public TypeToken getElementToken() { - return this.elementToken; + public Type getElementType() { + return this.elementType; } @Override @@ -96,7 +96,7 @@ public void registerEvent(final PluginContainer plugin, f protected MoreObjects.ToStringHelper toStringHelper() { return MoreObjects.toStringHelper(this) .add("resourceKey", this.getKey()) - .add("valueToken", this.valueToken); + .add("valueToken", this.valueType); } public ValueConstructor getValueConstructor() { diff --git a/src/main/java/org/spongepowered/common/data/key/SpongeKeyBuilder.java b/src/main/java/org/spongepowered/common/data/key/SpongeKeyBuilder.java index 6c08e55191e..a865ec50ea3 100644 --- a/src/main/java/org/spongepowered/common/data/key/SpongeKeyBuilder.java +++ b/src/main/java/org/spongepowered/common/data/key/SpongeKeyBuilder.java @@ -25,7 +25,9 @@ package org.spongepowered.common.data.key; import com.google.common.base.Preconditions; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.GenericTypeReflector; +import io.leangen.geantyref.TypeFactory; +import io.leangen.geantyref.TypeToken; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.data.Key; @@ -36,29 +38,42 @@ import org.spongepowered.api.util.weighted.WeightedTable; import org.spongepowered.common.util.SpongeCatalogBuilder; -import java.lang.reflect.TypeVariable; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Comparator; import java.util.HashSet; +import java.util.Objects; import java.util.function.BiPredicate; import java.util.function.Supplier; @SuppressWarnings({"unchecked", "rawtypes"}) public final class SpongeKeyBuilder> extends SpongeCatalogBuilder, Key.Builder> implements Key.Builder { - private static final TypeVariable valueElementParameter = Value.class.getTypeParameters()[0]; - - @Nullable private TypeToken valueToken; + private @Nullable Type valueType; + private @Nullable Type elementType; @Nullable private Comparator comparator; @Nullable private BiPredicate includesTester; @Override public > SpongeKeyBuilder type(final TypeToken token) { - Preconditions.checkNotNull(token); - this.valueToken = (TypeToken) token; + Objects.requireNonNull(token); + this.valueType = token.getType(); + final Type valueTypeAsSuper = GenericTypeReflector.getExactSuperType(this.valueType, Value.class); + if (!(valueTypeAsSuper instanceof ParameterizedType)) { + throw new IllegalArgumentException("Raw type " + this.valueType + " provided when registering Key " + key); + } + this.elementType = ((ParameterizedType) valueTypeAsSuper).getActualTypeArguments()[0]; return (SpongeKeyBuilder) this; } + @Override public Key.Builder> elementType(final Class type) { + Objects.requireNonNull(type, "type"); + this.valueType = TypeFactory.parameterizedClass(Value.class, type); + this.elementType = type; + return (SpongeKeyBuilder>) this; + } + @Override public SpongeKeyBuilder comparator(final Comparator comparator) { Preconditions.checkNotNull(comparator); @@ -81,9 +96,9 @@ public SpongeKeyBuilder key(final ResourceKey key) { @Override protected Key build(final ResourceKey key) { - Preconditions.checkNotNull(this.valueToken, "The value token must be set"); + Objects.requireNonNull(this.valueType, "The value type must be set"); + Objects.requireNonNull(this.elementType, "The element type must be set"); - final TypeToken elementToken = (TypeToken) this.valueToken.resolveType(valueElementParameter); BiPredicate includesTester = this.includesTester; if (includesTester == null) { @@ -92,7 +107,7 @@ protected Key build(final ResourceKey key) { Comparator comparator = this.comparator; if (comparator == null) { - if (Comparable.class.isAssignableFrom(elementToken.getRawType())) { + if (Comparable.class.isAssignableFrom(GenericTypeReflector.erase(this.elementType))) { //noinspection unchecked comparator = Comparator.comparing(o -> ((Comparable) o)); } else { @@ -108,20 +123,21 @@ protected Key build(final ResourceKey key) { } Supplier defaultValueSupplier = () -> null; - if (ListValue.class.isAssignableFrom(this.valueToken.getRawType())) { + final Class rawType = GenericTypeReflector.erase(this.valueType); + if (ListValue.class.isAssignableFrom(rawType)) { defaultValueSupplier = () -> (E) new ArrayList(); - } else if (SetValue.class.isAssignableFrom(this.valueToken.getRawType())) { + } else if (SetValue.class.isAssignableFrom(rawType)) { defaultValueSupplier = () -> (E) new HashSet(); - } else if (WeightedCollectionValue.class.isAssignableFrom(this.valueToken.getRawType())) { + } else if (WeightedCollectionValue.class.isAssignableFrom(rawType)) { defaultValueSupplier = () -> (E) new WeightedTable(); } - return new SpongeKey<>(key, this.valueToken, elementToken, comparator, includesTester, defaultValueSupplier); + return new SpongeKey<>(key, this.valueType, this.elementType, comparator, includesTester, defaultValueSupplier); } @Override public Key.Builder reset() { - this.valueToken = null; + this.valueType = null; this.includesTester = null; this.comparator = null; return super.reset(); diff --git a/src/main/java/org/spongepowered/common/data/persistence/ConfigurateTranslator.java b/src/main/java/org/spongepowered/common/data/persistence/ConfigurateTranslator.java index 136139dc3e3..35596f1aabe 100644 --- a/src/main/java/org/spongepowered/common/data/persistence/ConfigurateTranslator.java +++ b/src/main/java/org/spongepowered/common/data/persistence/ConfigurateTranslator.java @@ -27,12 +27,13 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; -import com.google.common.reflect.TypeToken; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.ConfigurationOptions; -import ninja.leaping.configurate.ConfigurationVisitor; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; -import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer; +import io.leangen.geantyref.TypeToken; +import org.spongepowered.configurate.BasicConfigurationNode; +import org.spongepowered.configurate.ConfigurationNode; +import org.spongepowered.configurate.ConfigurationOptions; +import org.spongepowered.configurate.ConfigurationVisitor; +import org.spongepowered.configurate.serialize.SerializationException; +import org.spongepowered.configurate.serialize.TypeSerializer; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.data.persistence.DataContainer; @@ -42,7 +43,6 @@ import org.spongepowered.api.data.persistence.InvalidDataException; import org.spongepowered.common.adventure.SpongeAdventure; -import java.util.Arrays; import java.util.Collection; import java.util.Deque; import java.util.HashSet; @@ -59,9 +59,10 @@ public final class ConfigurateTranslator implements DataTranslator TOKEN = TypeToken.of(ConfigurationNode.class); + private static final TypeToken TOKEN = TypeToken.get(ConfigurationNode.class); private static final ConfigurationOptions DEFAULT_OPTS = ConfigurationOptions.defaults() - .withNativeTypes(ImmutableSet.of(Map.class, + .nativeTypes(ImmutableSet.of( + Map.class, List.class, Double.class, Long.class, @@ -70,7 +71,7 @@ public final class ConfigurateTranslator implements DataTranslator SpongeAdventure.CONFIGURATE.addSerializersTo(coll)); + .serializers(coll -> coll.registerAll(SpongeAdventure.CONFIGURATE.serializers())); /** * Get the instance of this translator. @@ -106,15 +107,15 @@ public void translateDataToNode(final ConfigurationNode node, final DataView vie Objects.requireNonNull(node, "node"); Objects.requireNonNull(view, "container"); - final Map originalMap = node.getChildrenMap(); + final Map originalMap = node.childrenMap(); if (originalMap.isEmpty()) { - node.setValue(ImmutableMap.of()); + node.raw(ImmutableMap.of()); } // Unvisited hijinks to preserve any comments that may be present final Set unvisitedKeys = new HashSet<>(originalMap.keySet()); for (final DataQuery key : view.getKeys(false)) { - this.valueToNode(node.getNode(key.getParts()), view.get(key).orElse(null)); + this.valueToNode(node.node(key), view.get(key).orElse(null)); unvisitedKeys.remove(key.getParts().get(0)); } @@ -138,27 +139,26 @@ private void valueToNode(final ConfigurationNode node, final @Nullable Object va if (value instanceof DataView) { this.translateDataToNode(node, (DataView) value); } else if (value instanceof Collection) { - node.setValue(ImmutableList.of()); + node.raw(ImmutableList.of()); for (final Object child : ((Collection) value)) { this.valueToNode(node.appendListNode(), child); } } else if (value == null) { - node.setValue(null); + node.raw(null); } else { final Class vClazz = value.getClass(); - if (node.getOptions().acceptsType(vClazz)) { - node.setValue(value); + if (node.options().acceptsType(vClazz)) { + node.raw(value); } else { - final TypeToken token = TypeToken.of(vClazz); // hey let's guess at a type - final @Nullable TypeSerializer serial = node.getOptions().getSerializers().get(token); + final @Nullable TypeSerializer serial = node.options().serializers().get(vClazz); if (serial != null) { try { - serial.serialize(token, value, node); - } catch (final ObjectMappingException e) { + serial.serialize(vClazz, value, node); + } catch (final SerializationException e) { throw new IllegalArgumentException(e); } } else { - throw new IllegalArgumentException("DataView value type of " + token + " is not supported by the provided ConfigurationNode"); + throw new IllegalArgumentException("DataView value type of " + vClazz + " is not supported by the provided ConfigurationNode"); } } } @@ -166,7 +166,7 @@ private void valueToNode(final ConfigurationNode node, final @Nullable Object va @Override public ConfigurationNode translate(final DataView view) throws InvalidDataException { - final ConfigurationNode node = ConfigurationNode.root(ConfigurateTranslator.DEFAULT_OPTS); + final BasicConfigurationNode node = BasicConfigurationNode.root(ConfigurateTranslator.DEFAULT_OPTS); this.translateDataToNode(node, view); return node; } @@ -202,9 +202,9 @@ private ToDataView() { } private DataQuery queryFrom(final ConfigurationNode node) { - final Object key = node.getKey(); + final Object key = node.key(); if (key == null) { - throw new IllegalArgumentException("Null keys are not supported in data views (at " + Arrays.toString(node.getPath()) + ")"); + throw new IllegalArgumentException("Null keys are not supported in data views (at " + node.path() + ")"); } return DataQuery.of(key.toString()); } @@ -218,7 +218,7 @@ public VisitState newState() { @Override public void beginVisit(final ConfigurationNode node, final VisitState state) { - if (!node.isEmpty() && !node.isMap()) { + if (!node.empty() && !node.isMap()) { throw new IllegalArgumentException("Only mapping nodes can be represented in DataViews"); } state.start = node; @@ -254,7 +254,7 @@ public void enterListNode(final ConfigurationNode node, final VisitState state) @Override public void enterScalarNode(final ConfigurationNode node, final VisitState state) { - this.addToFirst(state, node, node.getValue()); + this.addToFirst(state, node, node.raw()); } @Override diff --git a/src/main/java/org/spongepowered/common/data/persistence/DataSerializers.java b/src/main/java/org/spongepowered/common/data/persistence/DataSerializers.java index 57c694ebcea..df2a50ab250 100644 --- a/src/main/java/org/spongepowered/common/data/persistence/DataSerializers.java +++ b/src/main/java/org/spongepowered/common/data/persistence/DataSerializers.java @@ -24,10 +24,9 @@ */ package org.spongepowered.common.data.persistence; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import net.kyori.adventure.text.Component; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; +import org.spongepowered.configurate.ConfigurationNode; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.data.persistence.DataContainer; import org.spongepowered.api.data.persistence.DataQuery; @@ -38,6 +37,7 @@ import org.spongepowered.api.util.Tuple; import org.spongepowered.common.adventure.SpongeAdventure; import org.spongepowered.common.util.Constants; +import org.spongepowered.configurate.serialize.SerializationException; import org.spongepowered.math.imaginary.Complexd; import org.spongepowered.math.imaginary.Complexf; import org.spongepowered.math.imaginary.Quaterniond; @@ -98,7 +98,7 @@ public final class DataSerializers { static { COMPONENT_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("component"); - final TypeToken token = TypeToken.of(Component.class); + final TypeToken token = TypeToken.get(Component.class); @Override public ResourceKey getKey() { @@ -116,8 +116,8 @@ public TypeToken getToken() { public Component translate(final DataView view) throws InvalidDataException { final ConfigurationNode node = ConfigurateTranslator.instance().translate(view); try { - return node.getValue(this.token); - } catch (final ObjectMappingException e) { + return node.get(this.token); + } catch (final SerializationException e) { throw new InvalidDataException(e); } } @@ -131,7 +131,7 @@ public DataContainer translate(final Component obj) throws InvalidDataException UUID_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("uuid"); - final TypeToken token = TypeToken.of(UUID.class); + final TypeToken token = TypeToken.get(UUID.class); @Override public TypeToken getToken() { @@ -167,7 +167,7 @@ public ResourceKey getKey() { VECTOR_2_D_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("vector_2_d"); - final TypeToken token = TypeToken.of(Vector2d.class); + final TypeToken token = TypeToken.get(Vector2d.class); @Override public TypeToken getToken() { @@ -202,7 +202,7 @@ public ResourceKey getKey() { VECTOR_2_F_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("vector_2_f"); - final TypeToken token = TypeToken.of(Vector2f.class); + final TypeToken token = TypeToken.get(Vector2f.class); @Override public TypeToken getToken() { @@ -237,7 +237,7 @@ public ResourceKey getKey() { VECTOR_2_I_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("vector_2_i"); - final TypeToken token = TypeToken.of(Vector2i.class); + final TypeToken token = TypeToken.get(Vector2i.class); @Override public TypeToken getToken() { @@ -272,7 +272,7 @@ public ResourceKey getKey() { }; VECTOR_2_L_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("vector_2_l"); - final TypeToken token = TypeToken.of(Vector2l.class); + final TypeToken token = TypeToken.get(Vector2l.class); @Override public TypeToken getToken() { @@ -306,7 +306,7 @@ public ResourceKey getKey() { }; VECTOR_3_D_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("vector_3_d"); - final TypeToken token = TypeToken.of(Vector3d.class); + final TypeToken token = TypeToken.get(Vector3d.class); @Override public TypeToken getToken() { @@ -344,7 +344,7 @@ public ResourceKey getKey() { }; VECTOR_3_F_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("vector_3_f"); - final TypeToken token = TypeToken.of(Vector3f.class); + final TypeToken token = TypeToken.get(Vector3f.class); @Override public TypeToken getToken() { @@ -382,7 +382,7 @@ public ResourceKey getKey() { }; VECTOR_3_I_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("vector_3_i"); - final TypeToken token = TypeToken.of(Vector3i.class); + final TypeToken token = TypeToken.get(Vector3i.class); @Override public TypeToken getToken() { @@ -420,7 +420,7 @@ public ResourceKey getKey() { }; VECTOR_3_L_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("vector_3_l"); - final TypeToken token = TypeToken.of(Vector3l.class); + final TypeToken token = TypeToken.get(Vector3l.class); @Override public TypeToken getToken() { @@ -458,7 +458,7 @@ public ResourceKey getKey() { }; VECTOR_4_F_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("vector_4_f"); - final TypeToken token = TypeToken.of(Vector4f.class); + final TypeToken token = TypeToken.get(Vector4f.class); @Override public TypeToken getToken() { @@ -499,7 +499,7 @@ public ResourceKey getKey() { }; VECTOR_4_I_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("vector_4_i"); - final TypeToken token = TypeToken.of(Vector4i.class); + final TypeToken token = TypeToken.get(Vector4i.class); @Override public TypeToken getToken() { @@ -540,7 +540,7 @@ public ResourceKey getKey() { }; VECTOR_4_L_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("vector_4_l"); - final TypeToken token = TypeToken.of(Vector4l.class); + final TypeToken token = TypeToken.get(Vector4l.class); @Override public TypeToken getToken() { @@ -581,7 +581,7 @@ public ResourceKey getKey() { }; VECTOR_4_D_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("vector_4_d"); - final TypeToken token = TypeToken.of(Vector4d.class); + final TypeToken token = TypeToken.get(Vector4d.class); @Override public TypeToken getToken() { @@ -622,7 +622,7 @@ public ResourceKey getKey() { }; COMPLEXD_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("complexd"); - final TypeToken token = TypeToken.of(Complexd.class); + final TypeToken token = TypeToken.get(Complexd.class); @Override public TypeToken getToken() { @@ -657,7 +657,7 @@ public ResourceKey getKey() { }; COMPLEXF_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("complexf"); - final TypeToken token = TypeToken.of(Complexf.class); + final TypeToken token = TypeToken.get(Complexf.class); @Override public TypeToken getToken() { @@ -691,7 +691,7 @@ public ResourceKey getKey() { }; QUATERNIOND_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("quaterniond"); - final TypeToken token = TypeToken.of(Quaterniond.class); + final TypeToken token = TypeToken.get(Quaterniond.class); @Override public TypeToken getToken() { @@ -731,7 +731,7 @@ public ResourceKey getKey() { }; QUATERNIONF_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("quaternionf"); - final TypeToken token = TypeToken.of(Quaternionf.class); + final TypeToken token = TypeToken.get(Quaternionf.class); @Override public TypeToken getToken() { @@ -771,7 +771,7 @@ public ResourceKey getKey() { }; LOCAL_TIME_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("local_time"); - final TypeToken token = TypeToken.of(LocalTime.class); + final TypeToken token = TypeToken.get(LocalTime.class); @Override public TypeToken getToken() { @@ -825,7 +825,7 @@ public ResourceKey getKey() { }; LOCAL_DATE_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("local_date"); - final TypeToken token = TypeToken.of(LocalDate.class); + final TypeToken token = TypeToken.get(LocalDate.class); @Override public TypeToken getToken() { @@ -871,7 +871,7 @@ public ResourceKey getKey() { }; LOCAL_DATE_TIME_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("local_date_time"); - final TypeToken token = TypeToken.of(LocalDateTime.class); + final TypeToken token = TypeToken.get(LocalDateTime.class); @Override public TypeToken getToken() { @@ -943,7 +943,7 @@ public ResourceKey getKey() { }; ZONED_DATE_TIME_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("zoned_date_time"); - final TypeToken token = TypeToken.of(ZonedDateTime.class); + final TypeToken token = TypeToken.get(ZonedDateTime.class); @Override public TypeToken getToken() { @@ -1022,7 +1022,7 @@ public ResourceKey getKey() { }; INSTANT_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("instant"); - final TypeToken token = TypeToken.of(Instant.class); + final TypeToken token = TypeToken.get(Instant.class); @Override public TypeToken getToken() { @@ -1096,7 +1096,7 @@ public ResourceKey getKey() { }; MONTH_DATA_SERIALIZER = new DataTranslator() { final ResourceKey key = ResourceKey.sponge("month"); - final TypeToken token = TypeToken.of(Month.class); + final TypeToken token = TypeToken.get(Month.class); @Override public TypeToken getToken() { diff --git a/src/main/java/org/spongepowered/common/data/persistence/DataTranslatorTypeSerializer.java b/src/main/java/org/spongepowered/common/data/persistence/DataTranslatorTypeSerializer.java index d36a09ba2ac..9d765f819a7 100644 --- a/src/main/java/org/spongepowered/common/data/persistence/DataTranslatorTypeSerializer.java +++ b/src/main/java/org/spongepowered/common/data/persistence/DataTranslatorTypeSerializer.java @@ -24,49 +24,49 @@ */ package org.spongepowered.common.data.persistence; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.common.reflect.TypeToken; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; -import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer; +import org.spongepowered.configurate.ConfigurationNode; +import org.spongepowered.configurate.serialize.SerializationException; +import org.spongepowered.configurate.serialize.TypeSerializer; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.data.persistence.DataTranslator; import org.spongepowered.api.data.persistence.InvalidDataException; +import java.lang.reflect.Type; +import java.util.Objects; + public class DataTranslatorTypeSerializer implements TypeSerializer { private final DataTranslator dataTranslator; - private DataTranslatorTypeSerializer(DataTranslator dataTranslator) { - this.dataTranslator = checkNotNull(dataTranslator, "dataTranslator"); + private DataTranslatorTypeSerializer(final DataTranslator dataTranslator) { + this.dataTranslator = Objects.requireNonNull(dataTranslator, "dataTranslator"); } @Override - public T deserialize(final TypeToken type, final ConfigurationNode value) throws ObjectMappingException { + public T deserialize(final Type type, final ConfigurationNode value) throws SerializationException { try { return this.dataTranslator.translate(ConfigurateTranslator.instance().translate(value)); } catch (final InvalidDataException e) { // Since the value in the config node might be null, return null if an error occurs. - throw new ObjectMappingException(e); + throw new SerializationException(e); } } @Override - public void serialize(final TypeToken type, final @Nullable T obj, final ConfigurationNode value) throws ObjectMappingException { + public void serialize(final Type type, final @Nullable T obj, final ConfigurationNode value) throws SerializationException { if (obj == null) { - value.setValue(null); + value.set(null); } try { ConfigurateTranslator.instance().translateDataToNode(value, this.dataTranslator.translate(obj)); } catch (final InvalidDataException e) { - throw new ObjectMappingException("Could not serialize. Data was invalid.", e); + throw new SerializationException(value, type, "Could not serialize. Data was invalid.", e); } } - public static DataTranslatorTypeSerializer from(DataTranslator dataTranslator) { + public static DataTranslatorTypeSerializer from(final DataTranslator dataTranslator) { return new DataTranslatorTypeSerializer<>(dataTranslator); } diff --git a/src/main/java/org/spongepowered/common/data/persistence/HoconDataFormat.java b/src/main/java/org/spongepowered/common/data/persistence/HoconDataFormat.java index 56fa3571b03..4ae3523644b 100644 --- a/src/main/java/org/spongepowered/common/data/persistence/HoconDataFormat.java +++ b/src/main/java/org/spongepowered/common/data/persistence/HoconDataFormat.java @@ -24,9 +24,10 @@ */ package org.spongepowered.common.data.persistence; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.commented.CommentedConfigurationNode; -import ninja.leaping.configurate.hocon.HoconConfigurationLoader; +import org.spongepowered.configurate.ConfigurateException; +import org.spongepowered.configurate.ConfigurationNode; +import org.spongepowered.configurate.CommentedConfigurationNode; +import org.spongepowered.configurate.hocon.HoconConfigurationLoader; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.data.persistence.DataContainer; import org.spongepowered.api.data.persistence.DataView; @@ -70,12 +71,16 @@ public DataContainer readFrom(final InputStream input) throws InvalidDataFormatE return HoconDataFormat.readFrom(() -> new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8))); } - private static DataContainer readFrom(final Callable source) throws IOException { + private static DataContainer readFrom(final Callable source) throws InvalidDataFormatException { final HoconConfigurationLoader loader = HoconConfigurationLoader.builder() - .setSource(source) + .source(source) .build(); - final CommentedConfigurationNode node = loader.load(); - return ConfigurateTranslator.instance().translate(node); + try { + final CommentedConfigurationNode node = loader.load(); + return ConfigurateTranslator.instance().translate(node); + } catch (final ConfigurateException ex) { + throw new InvalidDataFormatException(ex); + } } @Override @@ -97,11 +102,15 @@ public void writeTo(final OutputStream output, final DataView data) throws IOExc private static void writeTo(final Callable sink, final DataView data) throws IOException { final HoconConfigurationLoader loader = HoconConfigurationLoader.builder() - .setSink(sink) + .sink(sink) .build(); - final ConfigurationNode node = loader.createEmptyNode(); + final ConfigurationNode node = loader.createNode(); ConfigurateTranslator.instance().translateDataToNode(node, data); - loader.save(node); + try { + loader.save(node); + } catch (final ConfigurateException ex) { + throw new IOException(ex); + } } private static BufferedReader createBufferedReader(final Reader reader) { diff --git a/src/main/java/org/spongepowered/common/data/persistence/NbtTranslator.java b/src/main/java/org/spongepowered/common/data/persistence/NbtTranslator.java index 9ce1fa60cd8..990403b30d8 100644 --- a/src/main/java/org/spongepowered/common/data/persistence/NbtTranslator.java +++ b/src/main/java/org/spongepowered/common/data/persistence/NbtTranslator.java @@ -29,7 +29,7 @@ import static org.spongepowered.api.data.persistence.DataQuery.of; import com.google.common.collect.Lists; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import net.minecraft.nbt.ByteArrayNBT; import net.minecraft.nbt.ByteNBT; import net.minecraft.nbt.CompoundNBT; @@ -60,7 +60,7 @@ public final class NbtTranslator extends SpongeCatalogType implements DataTranslator { private static final NbtTranslator instance = new NbtTranslator(); - private static final TypeToken TOKEN = TypeToken.of(CompoundNBT.class); + private static final TypeToken TOKEN = TypeToken.get(CompoundNBT.class); public static final String BOOLEAN_IDENTIFIER = "$Boolean"; public static NbtTranslator getInstance() { diff --git a/src/main/java/org/spongepowered/common/data/persistence/SpongeDataStore.java b/src/main/java/org/spongepowered/common/data/persistence/SpongeDataStore.java index 6de81a59b97..2814def9f86 100644 --- a/src/main/java/org/spongepowered/common/data/persistence/SpongeDataStore.java +++ b/src/main/java/org/spongepowered/common/data/persistence/SpongeDataStore.java @@ -24,14 +24,13 @@ */ package org.spongepowered.common.data.persistence; -import com.google.common.reflect.TypeToken; -import org.spongepowered.api.data.DataHolder; import org.spongepowered.api.data.DataManipulator; import org.spongepowered.api.data.Key; import org.spongepowered.api.data.persistence.DataStore; import org.spongepowered.api.data.persistence.DataView; import org.spongepowered.api.util.Tuple; +import java.lang.reflect.Type; import java.util.Collection; import java.util.Map; import java.util.Optional; @@ -41,15 +40,16 @@ public final class SpongeDataStore implements DataStore { private Map, Tuple, Function>>> queriesByKey; - private Collection> tokens; + private Collection tokens; - public SpongeDataStore(Map, Tuple, Function>>> queriesByKey, Collection> token) { + public SpongeDataStore(final Map, Tuple, Function>>> queriesByKey, + final Collection tokens) { this.queriesByKey = queriesByKey; - this.tokens = token; + this.tokens = tokens; } @Override - public Collection> getSupportedTokens() { + public Collection getSupportedTypes() { return this.tokens; } diff --git a/src/main/java/org/spongepowered/common/data/persistence/SpongeDataStoreBuilder.java b/src/main/java/org/spongepowered/common/data/persistence/SpongeDataStoreBuilder.java index 32c1cd1dda4..df206e8537b 100644 --- a/src/main/java/org/spongepowered/common/data/persistence/SpongeDataStoreBuilder.java +++ b/src/main/java/org/spongepowered/common/data/persistence/SpongeDataStoreBuilder.java @@ -24,7 +24,10 @@ */ package org.spongepowered.common.data.persistence; -import com.google.common.reflect.TypeToken; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import io.leangen.geantyref.GenericTypeReflector; +import io.leangen.geantyref.TypeToken; import org.spongepowered.api.CatalogType; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.Sponge; @@ -37,14 +40,13 @@ import org.spongepowered.api.data.value.Value; import org.spongepowered.api.util.Tuple; import org.spongepowered.common.data.SpongeDataManager; +import org.spongepowered.configurate.util.Types; import java.lang.reflect.Array; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; @@ -59,47 +61,45 @@ public class SpongeDataStoreBuilder implements DataStore.Builder { private Map, Tuple, Function>>> serializers = new IdentityHashMap<>(); - private List> dataHolderTypes = new ArrayList<>(); + private List dataHolderTypes = new ArrayList<>(); @Override - @SuppressWarnings("unchecked") - public DataStore.Builder key(Key> key, DataQuery dataQuery) { - final TypeToken elementToken = key.getElementToken(); - final BiFunction> deserializer = this.getDeserializer(elementToken); + public DataStore.Builder key(final Key> key, final DataQuery dataQuery) { + final BiFunction> deserializer = this.getDeserializer(key.getElementType()); return this.key(key, (view, value) -> view.set(dataQuery, value), v -> deserializer.apply(v, dataQuery)); } @SuppressWarnings({"rawtypes", "unchecked"}) - public BiFunction> getDeserializer(TypeToken elementToken) { - Class rawType = elementToken.getRawType(); + public BiFunction> getDeserializer(final Type elementType) { + final Class rawType = GenericTypeReflector.erase(elementType); final BiFunction> deserializer; - if (elementToken.isSubtypeOf(DataView.class)) { + if (DataView.class.isAssignableFrom(rawType)) { deserializer = (view, dataQuery) -> (Optional) view.getView(dataQuery); - } else if (elementToken.isSubtypeOf(DataSerializable.class)) { + } else if (DataSerializable.class.isAssignableFrom(rawType)) { deserializer = (view, dataQuery) -> (Optional) view.getSerializable(dataQuery, (Class) rawType); - } else if (elementToken.isSubtypeOf(CatalogType.class)) { + } else if (CatalogType.class.isAssignableFrom(rawType)) { deserializer = (view, dataQuery) -> (Optional) view.getCatalogType(dataQuery, ((Class) rawType)); } else if (SpongeDataManager.getInstance().getTranslator(rawType).isPresent()) { deserializer = (view, dataQuery) -> (Optional) view.getObject(dataQuery, rawType); - } else if (elementToken.isSubtypeOf(Set.class)) { - final Type listType = ((ParameterizedType) elementToken.getType()).getActualTypeArguments()[0]; + } else if (Set.class.isAssignableFrom(rawType)) { + final Type listType = ((ParameterizedType) elementType).getActualTypeArguments()[0]; deserializer = (view, dataQuery) -> (Optional) SpongeDataStoreBuilder.deserializeList((Class) listType, view, dataQuery).map(list -> new HashSet(list)); - } else if (elementToken.isSubtypeOf(List.class)) { - final Type listType = ((ParameterizedType) elementToken.getType()).getActualTypeArguments()[0]; + } else if (List.class.isAssignableFrom(rawType)) { + final Type listType = ((ParameterizedType) elementType).getActualTypeArguments()[0]; deserializer = (view, dataQuery) -> (Optional) SpongeDataStoreBuilder.deserializeList((Class) listType, view, dataQuery); - } else if (elementToken.isSubtypeOf(Collection.class)) { + } else if (Collection.class.isAssignableFrom(rawType)) { throw new UnsupportedOperationException("Collection deserialization is not supported. Provide the deserializer for it."); - } else if (elementToken.isArray()) { - final Class arrayType = elementToken.getComponentType().getRawType(); + } else if (Types.isArray(elementType)) { + final Class arrayType = GenericTypeReflector.erase(GenericTypeReflector.getArrayComponentType(elementType)); deserializer = (view, dataQuery) -> (Optional) SpongeDataStoreBuilder.deserializeList((Class) arrayType, view, dataQuery).map(list -> listToArray(arrayType, list)); - } else if (elementToken.isSubtypeOf(Map.class)) { - final Type[] parameterTypes = ((ParameterizedType) elementToken.getType()).getActualTypeArguments(); + } else if (Map.class.isAssignableFrom(rawType)) { + final Type[] parameterTypes = ((ParameterizedType) elementType).getActualTypeArguments(); final Type keyType = parameterTypes[0]; final Type valueType = parameterTypes[1]; if (!(keyType instanceof Class)) { throw new UnsupportedOperationException("Unsupported map-key type " + keyType); } - Function> keyDeserializer; + final Function> keyDeserializer; if (((Class) keyType).isAssignableFrom(CatalogType.class)) { keyDeserializer = key -> Sponge.getRegistry().getCatalogRegistry() .get(((Class) keyType), ResourceKey.resolve(key.toString())); @@ -108,12 +108,12 @@ public BiFunction> getDeserializer(TypeToke } else { throw new UnsupportedOperationException("Unsupported map-key type " + keyType); } - final TypeToken valueTypeToken = TypeToken.of(valueType); - final BiFunction> valueDeserializer = this.getDeserializer(valueTypeToken); + final BiFunction> valueDeserializer = this.getDeserializer(valueType); deserializer = (view, dataQuery) -> (Optional) view.getView(dataQuery).map(mapView -> { final Map resultMap = new HashMap<>(); - for (DataQuery key : mapView.getKeys(false)) { - Object mapKey = keyDeserializer.apply(key).orElseThrow(() -> new UnsupportedOperationException("Key not found " + key + " as " + keyType)); + for (final DataQuery key : mapView.getKeys(false)) { + final Object mapKey = keyDeserializer.apply(key) + .orElseThrow(() -> new UnsupportedOperationException("Key not found " + key + " as " + keyType)); final Optional mapValue = valueDeserializer.apply(mapView, key); resultMap.put(mapKey, mapValue.get()); } @@ -161,13 +161,23 @@ public DataStore.Builder reset() { } @Override - public DataStore.Builder holder(TypeToken... typeTokens) { - this.dataHolderTypes.addAll(Arrays.asList(typeTokens)); + public DataStore.Builder holder(final TypeToken... typeTokens) { + for (final TypeToken token : typeTokens) { + this.dataHolderTypes.add(token.getType()); + } + return this; + } + + @Override + public DataStore.Builder holder(final Class... classes) { + for (final Class clazz : classes) { + this.dataHolderTypes.add(Types.requireCompleteParameters(clazz)); + } return this; } @Override public DataStore build() { - return new SpongeDataStore(Collections.unmodifiableMap(this.serializers), this.dataHolderTypes); + return new SpongeDataStore(ImmutableMap.copyOf(this.serializers), ImmutableList.copyOf(this.dataHolderTypes)); } } diff --git a/src/main/java/org/spongepowered/common/data/provider/DataProviderRegistrator.java b/src/main/java/org/spongepowered/common/data/provider/DataProviderRegistrator.java index 4912bd5c050..ef7553638cb 100644 --- a/src/main/java/org/spongepowered/common/data/provider/DataProviderRegistrator.java +++ b/src/main/java/org/spongepowered/common/data/provider/DataProviderRegistrator.java @@ -24,7 +24,8 @@ */ package org.spongepowered.common.data.provider; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.GenericTypeReflector; +import io.leangen.geantyref.TypeToken; import org.spongepowered.api.data.DataHolder; import org.spongepowered.api.data.DataProvider; import org.spongepowered.api.data.DataTransactionResult; @@ -34,7 +35,9 @@ import org.spongepowered.api.data.value.Value; import org.spongepowered.api.util.OptBool; import org.spongepowered.common.data.copy.CopyHelper; +import org.spongepowered.common.util.TypeTokenHelper; +import java.lang.reflect.Type; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.BiFunction; @@ -224,7 +227,7 @@ public R supports(final Function supports) { public DataProvider build(Class target) { final MutableRegistrationBase registration = this; return new GenericMutableDataProvider(registration.key, target) { - final boolean isBooleanKey = registration.key.getElementToken().getRawType() == Boolean.class; + final boolean isBooleanKey = registration.key.getElementType() == Boolean.class; @Override protected Value constructValue(final H dataHolder, final E element) { @@ -370,10 +373,10 @@ public R supports(final Function supports) { return (R) this; } - public DataProvider build(Class target) { + public DataProvider build(final Class target) { final ImmutableRegistrationBase registration = this; return new GenericImmutableDataProvider(registration.key, target) { - final boolean isBooleanKey = registration.key.getElementToken().getRawType() == Boolean.class; + final boolean isBooleanKey = GenericTypeReflector.erase(registration.key.getElementType())== Boolean.class; @Override protected Value constructValue(final H dataHolder, final E element) { @@ -448,7 +451,7 @@ public ImmutableRegistrator asImmutable(final Class target) { public static class SpongeImmutableDataProviderBuilder, E, R extends ImmutableRegistrationBase> implements ImmutableDataProviderBuilder { private ImmutableRegistrationBase registration; - private TypeToken holder; + private Type holder; @Override public , NE> ImmutableDataProviderBuilder key(Key key) { @@ -457,8 +460,14 @@ public , NE> ImmutableDataProviderBuilder key(Ke } @Override - public ImmutableDataProviderBuilder dataHolder(TypeToken holder) { - this.holder = (TypeToken) holder; + public ImmutableDataProviderBuilder dataHolder(TypeToken holder) { + this.holder = holder.getType(); + return (SpongeImmutableDataProviderBuilder) this; + } + + @Override + public ImmutableDataProviderBuilder dataHolder(final Class holder) { + this.holder = TypeTokenHelper.requireCompleteGenerics(holder); return (SpongeImmutableDataProviderBuilder) this; } @@ -488,14 +497,14 @@ public ImmutableDataProviderBuilder reset() { @Override public DataProvider, E> build() { - return this.registration.build((Class) this.holder.getRawType()); + return this.registration.build((Class) GenericTypeReflector.erase(this.holder)); } } public static class SpongeMutableDataProviderBuilder, E, R extends MutableRegistrationBase> implements MutableDataProviderBuilder { private MutableRegistrationBase registration; - private TypeToken holder; + private Type holder; @Override public , NE> MutableDataProviderBuilder key(Key key) { @@ -504,8 +513,14 @@ public , NE> MutableDataProviderBuilder key(Key< } @Override - public MutableDataProviderBuilder dataHolder(TypeToken holder) { - this.holder = (TypeToken) holder; + public MutableDataProviderBuilder dataHolder(final TypeToken holder) { + this.holder = holder.getType(); + return (SpongeMutableDataProviderBuilder) this; + } + + @Override + public MutableDataProviderBuilder dataHolder(final Class holder) { + this.holder = TypeTokenHelper.requireCompleteGenerics(holder); return (SpongeMutableDataProviderBuilder) this; } @@ -577,7 +592,7 @@ public MutableDataProviderBuilder reset() { @Override public DataProvider build() { - return this.registration.build((Class) this.holder.getRawType()); + return this.registration.build((Class) GenericTypeReflector.erase(this.holder)); } } diff --git a/src/main/java/org/spongepowered/common/data/provider/GenericImmutableDataProviderBase.java b/src/main/java/org/spongepowered/common/data/provider/GenericImmutableDataProviderBase.java index 6f06e9b07a0..bb4e474e57c 100644 --- a/src/main/java/org/spongepowered/common/data/provider/GenericImmutableDataProviderBase.java +++ b/src/main/java/org/spongepowered/common/data/provider/GenericImmutableDataProviderBase.java @@ -24,19 +24,18 @@ */ package org.spongepowered.common.data.provider; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.GenericTypeReflector; import org.spongepowered.api.data.DataHolder; import org.spongepowered.api.data.Key; import org.spongepowered.api.data.value.Value; +import org.spongepowered.common.util.TypeTokenHelper; -import java.lang.reflect.TypeVariable; import java.util.Optional; @SuppressWarnings("unchecked") public abstract class GenericImmutableDataProviderBase, E> extends ImmutableDataProvider implements AbstractDataProvider.KnownHolderType { - private static final TypeVariable holderTypeParameter = GenericImmutableDataProviderBase.class.getTypeParameters()[0]; private final Class holderType; GenericImmutableDataProviderBase(final Key key, final Class holderType) { @@ -46,7 +45,8 @@ public abstract class GenericImmutableDataProviderBase, E> GenericImmutableDataProviderBase(final Key key) { super(key); - this.holderType = (Class) TypeToken.of(this.getClass()).resolveType(holderTypeParameter).getRawType(); + this.holderType = (Class) GenericTypeReflector.erase( + TypeTokenHelper.typeArgumentFromSupertype(this.getClass(), GenericImmutableDataProviderBase.class, 0)); } private boolean isTypeAllowed(final DataHolder dataHolder) { diff --git a/src/main/java/org/spongepowered/common/data/provider/GenericMutableDataProviderBase.java b/src/main/java/org/spongepowered/common/data/provider/GenericMutableDataProviderBase.java index 07340845678..a2d326c7cb6 100644 --- a/src/main/java/org/spongepowered/common/data/provider/GenericMutableDataProviderBase.java +++ b/src/main/java/org/spongepowered/common/data/provider/GenericMutableDataProviderBase.java @@ -24,14 +24,14 @@ */ package org.spongepowered.common.data.provider; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.GenericTypeReflector; import org.spongepowered.api.data.DataHolder; import org.spongepowered.api.data.DataTransactionResult; import org.spongepowered.api.data.Key; import org.spongepowered.api.data.value.Value; import org.spongepowered.common.SpongeCommon; +import org.spongepowered.common.util.TypeTokenHelper; -import java.lang.reflect.TypeVariable; import java.util.Optional; import java.util.function.Supplier; @@ -39,7 +39,6 @@ public abstract class GenericMutableDataProviderBase, E> extends MutableDataProvider implements AbstractDataProvider.KnownHolderType { - private static final TypeVariable holderTypeParameter = GenericMutableDataProviderBase.class.getTypeParameters()[0]; private final Class holderType; protected GenericMutableDataProviderBase(final Supplier> key, final Class holderType) { @@ -57,7 +56,8 @@ protected GenericMutableDataProviderBase(final Supplier> key) { protected GenericMutableDataProviderBase(final Key key) { super(key); - this.holderType = (Class) TypeToken.of(this.getClass()).resolveType(holderTypeParameter).getRawType(); + this.holderType = (Class) GenericTypeReflector.erase( + TypeTokenHelper.typeArgumentFromSupertype(this.getClass(), GenericMutableDataProviderBase.class, 0)); } private boolean isTypeAllowed(final DataHolder dataHolder) { diff --git a/src/main/java/org/spongepowered/common/data/value/ValueConstructorFactory.java b/src/main/java/org/spongepowered/common/data/value/ValueConstructorFactory.java index d2f769b39e8..41be2567715 100644 --- a/src/main/java/org/spongepowered/common/data/value/ValueConstructorFactory.java +++ b/src/main/java/org/spongepowered/common/data/value/ValueConstructorFactory.java @@ -24,6 +24,7 @@ */ package org.spongepowered.common.data.value; +import io.leangen.geantyref.GenericTypeReflector; import org.spongepowered.api.data.Key; import org.spongepowered.api.data.value.ListValue; import org.spongepowered.api.data.value.MapValue; @@ -40,8 +41,8 @@ @SuppressWarnings({"unchecked", "rawtypes"}) public final class ValueConstructorFactory { - public static , E> ValueConstructor getConstructor(SpongeKey key) { - final Class valueType = key.getValueToken().getRawType(); + public static , E> ValueConstructor getConstructor(final SpongeKey key) { + final Class valueType = GenericTypeReflector.erase(key.getValueType()); ValueConstructor valueConstructor; if (ListValue.class.isAssignableFrom(valueType)) { valueConstructor = new SimpleValueConstructor(key, @@ -65,7 +66,7 @@ public static , E> ValueConstructor getConstructor(Spon valueConstructor = new SimpleValueConstructor(key, (key1, value) -> new MutableSpongeValue((Key) key1, value), (key1, value) -> new ImmutableSpongeValue((Key) key1, value)); - final Class elementType = key.getElementToken().getRawType(); + final Class elementType = GenericTypeReflector.erase(key.getElementType()); if (Enum.class.isAssignableFrom(elementType)) { valueConstructor = new CachedEnumValueConstructor(valueConstructor, elementType); } else if (elementType == Boolean.class) { diff --git a/src/main/java/org/spongepowered/common/event/EventType.java b/src/main/java/org/spongepowered/common/event/EventType.java index 44da1593a46..b30a6e51e88 100644 --- a/src/main/java/org/spongepowered/common/event/EventType.java +++ b/src/main/java/org/spongepowered/common/event/EventType.java @@ -24,26 +24,26 @@ */ package org.spongepowered.common.event; -import com.google.common.reflect.TypeToken; +import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.event.Event; +import java.lang.reflect.Type; import java.util.Objects; -import javax.annotation.Nullable; public final class EventType { private final Class eventType; - @Nullable private final TypeToken genericType; + private final @Nullable Type genericType; private int hashCode; - EventType(Class eventType, @Nullable TypeToken genericType) { + EventType(final Class eventType, final @Nullable Type genericType) { this.genericType = genericType; this.eventType = eventType; } - public EventType(Class eventType) { + public EventType(final Class eventType) { this(eventType, null); } @@ -51,8 +51,7 @@ public Class getType() { return this.eventType; } - @Nullable - public TypeToken getGenericType() { + public @Nullable Type getGenericType() { return this.genericType; } @@ -67,7 +66,7 @@ public String toString() { @SuppressWarnings("rawtypes") @Override - public boolean equals(@Nullable Object o) { + public boolean equals(final @Nullable Object o) { if (!(o instanceof EventType)) { return false; } diff --git a/src/main/java/org/spongepowered/common/event/ListenerChecker.java b/src/main/java/org/spongepowered/common/event/ListenerChecker.java index 1e002c2864c..814fcc73231 100644 --- a/src/main/java/org/spongepowered/common/event/ListenerChecker.java +++ b/src/main/java/org/spongepowered/common/event/ListenerChecker.java @@ -25,10 +25,11 @@ package org.spongepowered.common.event; import com.google.common.base.CaseFormat; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.GenericTypeReflector; import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet; import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.common.SpongeCommon; +import org.spongepowered.configurate.util.Types; import java.lang.reflect.Field; import java.lang.reflect.Method; @@ -88,20 +89,25 @@ public void unregisterListenerFor(Class eventClass) { this.updateFields(eventClass, false); } - private Class getClassForField(Field field) { - String name = field.getName(); + private Class getClassForField(final Field field) { + final String name = field.getName(); final Method[] methods = SpongeEventFactory.class.getMethods(); - for (Method eventMethod : methods) { + for (final Method eventMethod : methods) { // Not all fields will directly correspond to an event in SpongeEventFactory. // For example, SpongeEventFactory has no method to create a ChangeBlockEvent, // (only methods for its subtypes), but ShouldFire.CHANGE_BLOCK_EVENT exists, and is valid // Therefore, we check all superinterfaces of each listed event. - for (TypeToken eventType: TypeToken.of(eventMethod.getReturnType()).getTypes()) { - String eventMethodName = getName(eventType.getRawType()); - if (name.equals(eventMethodName)) { - return eventType.getRawType(); - } + final Class possibleType = Types.allSuperTypesAndInterfaces(eventMethod.getGenericReturnType()) + .map(GenericTypeReflector::erase) + .filter(eventType -> { + final String eventMethodName = getName(eventType); + return name.equals(eventMethodName); + }) + .findFirst().orElse(null); + + if (possibleType != null) { + return possibleType; } } throw new IllegalStateException(String.format("ShouldFire field %s does not correspond to any SpongeAPI event! Check that the field is written in UPPER_CASE_UNDERSCORE format.", field)); @@ -128,9 +134,13 @@ public void updateFields(Class eventClass, boolean registering) { // to be set to 'true'. This allows the implementation to check the most-specific flag for its particular event, // while ensuring that all plugins listening for an event will recieve it - Set> superTypes = TypeToken.of(eventClass).getTypes().rawTypes().stream().filter(c -> c != eventClass).collect(Collectors.toCollection(ReferenceOpenHashSet::new)); + @SuppressWarnings("unchecked") + final Set> superTypes = Types.allSuperTypesAndInterfaces(eventClass) + .map(t -> (Class) GenericTypeReflector.erase(t)) + .filter(c -> c != eventClass) + .collect(Collectors.toCollection(ReferenceOpenHashSet::new)); - for (Map.Entry, FieldData> entry: this.fieldClassMap.entrySet()) { + for (final Map.Entry, FieldData> entry: this.fieldClassMap.entrySet()) { // We check for two things: diff --git a/src/main/java/org/spongepowered/common/event/SpongeEventContextKey.java b/src/main/java/org/spongepowered/common/event/SpongeEventContextKey.java index 0ba466267f8..daa4f93360d 100644 --- a/src/main/java/org/spongepowered/common/event/SpongeEventContextKey.java +++ b/src/main/java/org/spongepowered/common/event/SpongeEventContextKey.java @@ -27,26 +27,32 @@ import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.MoreObjects; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.GenericTypeReflector; +import io.leangen.geantyref.TypeToken; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.event.EventContextKey; -@SuppressWarnings("UnstableApiUsage") +import java.lang.reflect.Type; + public final class SpongeEventContextKey implements EventContextKey { private final ResourceKey key; - private final TypeToken allowed; + private final Type allowed; - SpongeEventContextKey(SpongeEventContextKeyBuilder builder) { + SpongeEventContextKey(final SpongeEventContextKeyBuilder builder) { this.key = builder.key; this.allowed = builder.typeClass; } - public SpongeEventContextKey(ResourceKey key, TypeToken allowed) { + public SpongeEventContextKey(final ResourceKey key, final TypeToken allowed) { this.key = checkNotNull(key, "key"); - this.allowed = checkNotNull(allowed, "Allowed"); + this.allowed = checkNotNull(allowed, "allowed").getType(); } + public SpongeEventContextKey(final ResourceKey key, final Class allowed) { + this.key = checkNotNull(key, "key"); + this.allowed = checkNotNull(allowed, "allowed"); + } @Override public ResourceKey getKey() { @@ -54,10 +60,22 @@ public ResourceKey getKey() { } @Override - public TypeToken getAllowedType() { + public Type getAllowedType() { return this.allowed; } + @Override + public boolean isInstance(final Object value) { + return value != null && GenericTypeReflector.erase(this.allowed).isInstance(value); + } + + @SuppressWarnings("unchecked") + @Override + public T cast(final Object value) { + return (T) value; + } + + @Override public String toString() { return MoreObjects.toStringHelper(this) diff --git a/src/main/java/org/spongepowered/common/event/SpongeEventContextKeyBuilder.java b/src/main/java/org/spongepowered/common/event/SpongeEventContextKeyBuilder.java index 0bde33a2b98..c3a63e99762 100644 --- a/src/main/java/org/spongepowered/common/event/SpongeEventContextKeyBuilder.java +++ b/src/main/java/org/spongepowered/common/event/SpongeEventContextKeyBuilder.java @@ -27,23 +27,34 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.event.EventContextKey; +import org.spongepowered.common.util.TypeTokenHelper; + +import java.lang.reflect.Type; import javax.annotation.Nullable; @SuppressWarnings("UnstableApiUsage") public final class SpongeEventContextKeyBuilder implements EventContextKey.Builder { - @Nullable TypeToken typeClass; + @Nullable Type typeClass; @Nullable ResourceKey key; @SuppressWarnings("unchecked") @Override - public SpongeEventContextKeyBuilder type(TypeToken aClass) { + public SpongeEventContextKeyBuilder type(final TypeToken aClass) { + checkArgument(aClass != null, "Class cannot be null!"); + this.typeClass = aClass.getType(); + return (SpongeEventContextKeyBuilder) this; + } + + @SuppressWarnings("unchecked") + @Override + public SpongeEventContextKeyBuilder type(final Class aClass) { checkArgument(aClass != null, "Class cannot be null!"); - this.typeClass = (TypeToken) aClass; + this.typeClass = TypeTokenHelper.requireCompleteGenerics(aClass); return (SpongeEventContextKeyBuilder) this; } diff --git a/src/main/java/org/spongepowered/common/event/SpongeEventManager.java b/src/main/java/org/spongepowered/common/event/SpongeEventManager.java index b95a2f3cfd0..e898db24705 100644 --- a/src/main/java/org/spongepowered/common/event/SpongeEventManager.java +++ b/src/main/java/org/spongepowered/common/event/SpongeEventManager.java @@ -32,7 +32,8 @@ import com.github.benmanes.caffeine.cache.LoadingCache; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.GenericTypeReflector; +import io.leangen.geantyref.TypeToken; import com.google.inject.Inject; import com.google.inject.Singleton; import org.apache.logging.log4j.Logger; @@ -59,12 +60,14 @@ import org.spongepowered.common.relocate.co.aikar.timings.TimingsManager; import org.spongepowered.common.util.EngineUtil; import org.spongepowered.common.util.TypeTokenHelper; +import org.spongepowered.configurate.util.Types; import org.spongepowered.plugin.PluginContainer; import javax.annotation.Nullable; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; +import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.ArrayList; import java.util.Collection; @@ -75,10 +78,12 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Predicate; import java.util.stream.Collectors; +import java.util.stream.Stream; @Singleton public final class SpongeEventManager implements EventManager { @@ -135,29 +140,28 @@ public SpongeEventManager(final Logger logger) { } } - RegisteredListener.Cache bakeHandlers(EventType eventType) { + RegisteredListener.Cache bakeHandlers(final EventType eventType) { final List> handlers = new ArrayList<>(); - final Set> types = TypeToken.of(eventType.getType()).getTypes().rawTypes(); + final Stream> types = Types.allSuperTypesAndInterfaces(eventType.getType()) + .map(GenericTypeReflector::erase) + .filter(Event.class::isAssignableFrom); // TODO: Move @Includes and @Excludes from filters to the baking process, this simplifies the generated // filter code and makes the filter baking target more specific handlers. synchronized (this.lock) { - for (final Class type : types) { - if (Event.class.isAssignableFrom(type)) { - final Collection> listeners = this.handlersByEvent.get(type); - if (GenericEvent.class.isAssignableFrom(type)) { - final TypeToken genericType = eventType.getGenericType(); - checkNotNull(genericType); - for (final RegisteredListener listener : listeners) { - final TypeToken genericType1 = listener.getEventType().getGenericType(); - checkNotNull(genericType1); - if (TypeTokenHelper.isAssignable(genericType, genericType1)) { - handlers.add(listener); - } + for (final Iterator> it = types.iterator(); it.hasNext();) { + final Class type = it.next(); + final Collection> listeners = this.handlersByEvent.get(type); + if (GenericEvent.class.isAssignableFrom(type)) { + final Type genericType = Objects.requireNonNull(eventType.getGenericType()); + for (final RegisteredListener listener : listeners) { + final Type genericType1 = Objects.requireNonNull(listener.getEventType().getGenericType()); + if (TypeTokenHelper.isAssignable(genericType, genericType1)) { + handlers.add(listener); } - } else { - handlers.addAll(listeners); } + } else { + handlers.addAll(listeners); } } } @@ -217,7 +221,6 @@ private void register(final List> handlers) } } - @SuppressWarnings("unchecked") private void registerListener(PluginContainer plugin, Object listenerObject) { checkNotNull(plugin, "plugin"); checkNotNull(listenerObject, "listener"); @@ -248,12 +251,11 @@ private void registerListener(PluginContainer plugin, Object listenerObject) { if (listener != null) { final String error = getHandlerErrorOrNull(method); if (error == null) { - @SuppressWarnings("rawtypes") - final TypeToken eventType = TypeToken.of(method.getGenericParameterTypes()[0]); + final Type eventType = method.getGenericParameterTypes()[0]; final AnnotatedEventListener handler; try { handler = handlerFactory.create(listenerObject, method); - } catch (Exception e) { + } catch (final Exception e) { this.logger.error("Failed to create handler for {} on {}", method, handle, e); continue; } @@ -287,19 +289,20 @@ private void registerListener(PluginContainer plugin, Object listenerObject) { this.register(handlers); } - private static RegisteredListener createRegistration(final PluginContainer plugin, final TypeToken eventClass, + private static RegisteredListener createRegistration(final PluginContainer plugin, final Type eventClass, final Listener listener, final EventListener handler) { return createRegistration(plugin, eventClass, listener.order(), listener.beforeModifications(), handler); } @SuppressWarnings({"unchecked", "rawtypes"}) - private static RegisteredListener createRegistration(final PluginContainer plugin, final TypeToken eventType, + private static RegisteredListener createRegistration(final PluginContainer plugin, final Type eventType, final Order order, final boolean beforeModifications, final EventListener handler) { - TypeToken genericType = null; - if (GenericEvent.class.isAssignableFrom(eventType.getRawType())) { - genericType = eventType.resolveType(GENERIC_EVENT_TYPE); + Type genericType = null; + final Class erased = GenericTypeReflector.erase(eventType); + if (GenericEvent.class.isAssignableFrom(erased)) { + genericType = TypeTokenHelper.typeArgumentFromSupertype(eventType, GenericEvent.class, 0); } - return new RegisteredListener(plugin, new EventType(eventType.getRawType(), genericType), order, handler, beforeModifications); + return new RegisteredListener(plugin, new EventType(erased, genericType), order, handler, beforeModifications); } @Override @@ -333,13 +336,13 @@ public void registerListener(final PluginContainer plugin, fin @Override public void registerListener(final PluginContainer plugin, final Class eventClass, final Order order, final boolean beforeModifications, final EventListener listener) { - this.registerListener(plugin, TypeToken.of(eventClass), Order.DEFAULT, false, listener); + this.registerListener(plugin, eventClass, Order.DEFAULT, false, listener); } @Override public void registerListener(final PluginContainer plugin, final TypeToken eventType, final Order order, final boolean beforeModifications, final EventListener listener) { - this.register(createRegistration(plugin, eventType, order, beforeModifications, listener)); + this.register(createRegistration(plugin, eventType.getType(), order, beforeModifications, listener)); } private void unregister(final Predicate> unregister) { @@ -382,7 +385,7 @@ protected RegisteredListener.Cache getHandlerCache(final Event event) { final Class eventClass = event.getClass(); final EventType eventType; if (event instanceof GenericEvent) { - eventType = new EventType(eventClass, checkNotNull(((GenericEvent) event).getGenericType())); + eventType = new EventType(eventClass, checkNotNull(((GenericEvent) event).getGenericType().getType())); } else { eventType = new EventType(eventClass, null); } diff --git a/src/main/java/org/spongepowered/common/event/lifecycle/AbstractEngineLifecycleEvent.java b/src/main/java/org/spongepowered/common/event/lifecycle/AbstractEngineLifecycleEvent.java index ae8e7e59652..9b85a06adcc 100644 --- a/src/main/java/org/spongepowered/common/event/lifecycle/AbstractEngineLifecycleEvent.java +++ b/src/main/java/org/spongepowered/common/event/lifecycle/AbstractEngineLifecycleEvent.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.event.lifecycle; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import org.spongepowered.api.Engine; import org.spongepowered.api.Game; import org.spongepowered.api.event.Cause; diff --git a/src/main/java/org/spongepowered/common/event/lifecycle/ProvideEngineServiceEventImpl.java b/src/main/java/org/spongepowered/common/event/lifecycle/ProvideEngineServiceEventImpl.java index 807436c1bb6..7242677a935 100644 --- a/src/main/java/org/spongepowered/common/event/lifecycle/ProvideEngineServiceEventImpl.java +++ b/src/main/java/org/spongepowered/common/event/lifecycle/ProvideEngineServiceEventImpl.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.event.lifecycle; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.Engine; diff --git a/src/main/java/org/spongepowered/common/event/lifecycle/ProvideServiceEventImpl.java b/src/main/java/org/spongepowered/common/event/lifecycle/ProvideServiceEventImpl.java index 06170a4b348..8d56f8cb442 100644 --- a/src/main/java/org/spongepowered/common/event/lifecycle/ProvideServiceEventImpl.java +++ b/src/main/java/org/spongepowered/common/event/lifecycle/ProvideServiceEventImpl.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.event.lifecycle; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.Game; diff --git a/src/main/java/org/spongepowered/common/event/lifecycle/RegisterCatalogEventImpl.java b/src/main/java/org/spongepowered/common/event/lifecycle/RegisterCatalogEventImpl.java index 3ad95b19245..1fd81160beb 100644 --- a/src/main/java/org/spongepowered/common/event/lifecycle/RegisterCatalogEventImpl.java +++ b/src/main/java/org/spongepowered/common/event/lifecycle/RegisterCatalogEventImpl.java @@ -25,7 +25,7 @@ package org.spongepowered.common.event.lifecycle; import com.google.common.base.Preconditions; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import org.spongepowered.api.CatalogType; import org.spongepowered.api.Game; import org.spongepowered.api.Sponge; diff --git a/src/main/java/org/spongepowered/common/event/lifecycle/RegisterCommandEventImpl.java b/src/main/java/org/spongepowered/common/event/lifecycle/RegisterCommandEventImpl.java index 833993d1cf3..bad274ef2d5 100644 --- a/src/main/java/org/spongepowered/common/event/lifecycle/RegisterCommandEventImpl.java +++ b/src/main/java/org/spongepowered/common/event/lifecycle/RegisterCommandEventImpl.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.event.lifecycle; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import org.spongepowered.api.Game; import org.spongepowered.api.command.manager.CommandFailedRegistrationException; import org.spongepowered.api.command.manager.CommandMapping; diff --git a/src/main/java/org/spongepowered/common/event/lifecycle/StartedEngineEventImpl.java b/src/main/java/org/spongepowered/common/event/lifecycle/StartedEngineEventImpl.java index 5c11c402133..8f039b7fc2e 100644 --- a/src/main/java/org/spongepowered/common/event/lifecycle/StartedEngineEventImpl.java +++ b/src/main/java/org/spongepowered/common/event/lifecycle/StartedEngineEventImpl.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.event.lifecycle; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import org.spongepowered.api.Engine; import org.spongepowered.api.Game; import org.spongepowered.api.event.Cause; diff --git a/src/main/java/org/spongepowered/common/event/lifecycle/StartingEngineEventImpl.java b/src/main/java/org/spongepowered/common/event/lifecycle/StartingEngineEventImpl.java index 6778ee388e1..65d4d796900 100644 --- a/src/main/java/org/spongepowered/common/event/lifecycle/StartingEngineEventImpl.java +++ b/src/main/java/org/spongepowered/common/event/lifecycle/StartingEngineEventImpl.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.event.lifecycle; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import org.spongepowered.api.Engine; import org.spongepowered.api.Game; import org.spongepowered.api.event.Cause; diff --git a/src/main/java/org/spongepowered/common/event/lifecycle/StoppingEngineEventImpl.java b/src/main/java/org/spongepowered/common/event/lifecycle/StoppingEngineEventImpl.java index 8c5bf226cae..ecc9bb66a0f 100644 --- a/src/main/java/org/spongepowered/common/event/lifecycle/StoppingEngineEventImpl.java +++ b/src/main/java/org/spongepowered/common/event/lifecycle/StoppingEngineEventImpl.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.event.lifecycle; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import org.spongepowered.api.Engine; import org.spongepowered.api.Game; import org.spongepowered.api.event.Cause; diff --git a/src/main/java/org/spongepowered/common/inject/InjectionPointProvider.java b/src/main/java/org/spongepowered/common/inject/InjectionPointProvider.java index 7f702d9f51c..3eead84f2d1 100644 --- a/src/main/java/org/spongepowered/common/inject/InjectionPointProvider.java +++ b/src/main/java/org/spongepowered/common/inject/InjectionPointProvider.java @@ -24,7 +24,6 @@ */ package org.spongepowered.common.inject; -import com.google.common.reflect.TypeToken; import com.google.inject.Binder; import com.google.inject.Binding; import com.google.inject.Module; @@ -86,17 +85,17 @@ private static SpongeInjectionPoint findInjectionPoint(List } final com.google.inject.spi.InjectionPoint spiInjectionPoint = dependency.getInjectionPoint(); if (spiInjectionPoint != null) { - final TypeToken source = TypeToken.of(spiInjectionPoint.getDeclaringType().getType()); + final Type source = spiInjectionPoint.getDeclaringType().getType(); final Member member = spiInjectionPoint.getMember(); if (member instanceof Field) { final Field field = (Field) member; - return new SpongeInjectionPoint(source, TypeToken.of(field.getGenericType()), field.getAnnotations()); + return new SpongeInjectionPoint(source, field.getGenericType(), field.getAnnotations()); } else if (member instanceof Executable) { final Executable executable = (Executable) member; final Annotation[][] parameterAnnotations = executable.getParameterAnnotations(); final Type[] parameterTypes = executable.getGenericParameterTypes(); final int index = dependency.getParameterIndex(); - return new SpongeInjectionPoint(source, TypeToken.of(parameterTypes[index]), parameterAnnotations[index]); + return new SpongeInjectionPoint(source, parameterTypes[index], parameterAnnotations[index]); } else { throw new IllegalStateException("Unsupported Member type: " + member.getClass().getName()); } diff --git a/src/main/java/org/spongepowered/common/inject/SpongeCommonModule.java b/src/main/java/org/spongepowered/common/inject/SpongeCommonModule.java index e86004d5460..446c79e24ee 100644 --- a/src/main/java/org/spongepowered/common/inject/SpongeCommonModule.java +++ b/src/main/java/org/spongepowered/common/inject/SpongeCommonModule.java @@ -54,7 +54,6 @@ import org.spongepowered.common.network.channel.ChannelBufferAllocator; import org.spongepowered.common.network.channel.SpongeChannelRegistry; import org.spongepowered.common.registry.SpongeGameRegistry; -import org.spongepowered.common.service.SpongeServiceProvider; import org.spongepowered.common.service.game.SpongeGameScopedServiceProvider; import org.spongepowered.common.sql.SpongeSqlManager; import org.spongepowered.common.util.SpongeMetricsConfigManager; diff --git a/src/main/java/org/spongepowered/common/inject/SpongeInjectionPoint.java b/src/main/java/org/spongepowered/common/inject/SpongeInjectionPoint.java index ad844519488..8b21a3bf56f 100644 --- a/src/main/java/org/spongepowered/common/inject/SpongeInjectionPoint.java +++ b/src/main/java/org/spongepowered/common/inject/SpongeInjectionPoint.java @@ -25,30 +25,30 @@ package org.spongepowered.common.inject; import com.google.common.base.MoreObjects; -import com.google.common.reflect.TypeToken; import javax.annotation.Nullable; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; +import java.lang.reflect.Type; import java.util.Arrays; public final class SpongeInjectionPoint implements AnnotatedElement { - private final TypeToken source; - private final TypeToken type; + private final Type source; + private final Type type; private final Annotation[] annotations; - SpongeInjectionPoint(final TypeToken source, final TypeToken type, final Annotation[] annotations) { + SpongeInjectionPoint(final Type source, final Type type, final Annotation[] annotations) { this.annotations = annotations; this.source = source; this.type = type; } - public TypeToken getSource() { + public Type getSource() { return this.source; } - public TypeToken getType() { + public Type getType() { return this.type; } diff --git a/src/main/java/org/spongepowered/common/inject/plugin/PluginModule.java b/src/main/java/org/spongepowered/common/inject/plugin/PluginModule.java index 8a3869fec46..e450ecd9471 100644 --- a/src/main/java/org/spongepowered/common/inject/plugin/PluginModule.java +++ b/src/main/java/org/spongepowered/common/inject/plugin/PluginModule.java @@ -26,6 +26,10 @@ import com.google.inject.AbstractModule; import com.google.inject.Scopes; +import com.google.inject.TypeLiteral; +import com.google.inject.matcher.Matchers; +import com.google.inject.spi.TypeEncounter; +import com.google.inject.spi.TypeListener; import org.apache.logging.log4j.Logger; import org.spongepowered.api.asset.Asset; import org.spongepowered.api.asset.AssetId; diff --git a/src/main/java/org/spongepowered/common/inject/provider/PluginConfigurationModule.java b/src/main/java/org/spongepowered/common/inject/provider/PluginConfigurationModule.java index 97a56229255..7f3f68e7829 100644 --- a/src/main/java/org/spongepowered/common/inject/provider/PluginConfigurationModule.java +++ b/src/main/java/org/spongepowered/common/inject/provider/PluginConfigurationModule.java @@ -26,17 +26,27 @@ import com.google.inject.AbstractModule; import com.google.inject.Inject; +import com.google.inject.Injector; import com.google.inject.Provider; +import com.google.inject.ProvisionException; +import com.google.inject.Scopes; import com.google.inject.TypeLiteral; -import ninja.leaping.configurate.commented.CommentedConfigurationNode; -import ninja.leaping.configurate.loader.ConfigurationLoader; -import org.spongepowered.api.config.ConfigDir; -import org.spongepowered.api.config.DefaultConfig; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.spongepowered.api.config.ConfigRoot; +import org.spongepowered.configurate.CommentedConfigurationNode; +import org.spongepowered.configurate.ConfigurateException; +import org.spongepowered.configurate.ConfigurationNode; +import org.spongepowered.configurate.loader.ConfigurationLoader; import org.spongepowered.common.config.PluginConfigManager; +import org.spongepowered.configurate.objectmapping.ObjectMapper; +import org.spongepowered.configurate.objectmapping.guice.GuiceObjectMapperProvider; +import org.spongepowered.configurate.reference.ConfigurationReference; +import org.spongepowered.configurate.serialize.TypeSerializerCollection; import org.spongepowered.plugin.PluginContainer; -import java.io.File; import java.nio.file.Path; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; /** @@ -45,18 +55,74 @@ public final class PluginConfigurationModule extends AbstractModule { private static final TypeLiteral> COMMENTED_CONFIGURATION_NODE_LOADER = new TypeLiteral>() {}; + private static final TypeLiteral> COMMENTED_CONFIGURATION_NODE_REFERENCE = new TypeLiteral>() {}; @Override protected void configure() { - this.bind(Path.class).annotatedWith(ConfigDirAnnotation.NON_SHARED).toProvider(NonSharedDirAsPath.class); + this.bind(Path.class) + .annotatedWith(ConfigDirAnnotation.NON_SHARED) + .toProvider(NonSharedDirAsPath.class); // Plugin-private directory config file - this.bind(Path.class).annotatedWith(DefaultConfigAnnotation.NON_SHARED).toProvider(NonSharedPathAsPath.class); + this.bind(Path.class) + .annotatedWith(DefaultConfigAnnotation.NON_SHARED) + .toProvider(NonSharedPathAsPath.class); // Shared-directory config file - this.bind(Path.class).annotatedWith(DefaultConfigAnnotation.SHARED).toProvider(SharedDirAsPath.class); + this.bind(Path.class) + .annotatedWith(DefaultConfigAnnotation.SHARED) + .toProvider(SharedDirAsPath.class); + + // Access plugin-specific type serializers + this.bind(TypeSerializerCollection.class) + .toProvider(TypeSerializers.class) + .in(Scopes.SINGLETON); + // Loader for shared-directory config file - this.bind(COMMENTED_CONFIGURATION_NODE_LOADER).annotatedWith(DefaultConfigAnnotation.SHARED).toProvider(SharedCommentedConfigurationNode.class); + this.bind(COMMENTED_CONFIGURATION_NODE_LOADER) + .annotatedWith(DefaultConfigAnnotation.SHARED) + .toProvider(SharedCommentedConfigurationNode.class); + // Loader for plugin-private directory config file - this.bind(COMMENTED_CONFIGURATION_NODE_LOADER).annotatedWith(DefaultConfigAnnotation.NON_SHARED).toProvider(PrivateCommentedConfigurationNode.class); + this.bind(COMMENTED_CONFIGURATION_NODE_LOADER) + .annotatedWith(DefaultConfigAnnotation.NON_SHARED) + .toProvider(PrivateCommentedConfigurationNode.class); + + // Auto-reloading reference for shared-directory config files + this.bind(COMMENTED_CONFIGURATION_NODE_REFERENCE) + .annotatedWith(DefaultConfigAnnotation.SHARED) + .toProvider(SharedCommentedConfigurationNodeReference.class); + + // Auto-reloading reference for plugin-private directory config files + this.bind(COMMENTED_CONFIGURATION_NODE_REFERENCE) + .annotatedWith(DefaultConfigAnnotation.NON_SHARED) + .toProvider(PrivateCommentedConfigurationNodeReference.class); + + this.requestStaticInjection(IHateGuiceInjectorProvider.class); + } + + /** + * So... we need a way to get the final Injector used to create the plugin + * instance, but Guice doesn't want to give us that in the provider for the + * TypeSerializerCollection. + * + * Instead, we request static injection of this class, which collects the + * necessary information right as the Injector is created, but before it + * has been passed to the plugin loader to create the plugin instance. + * + * Please, please try to find something nicer. I give up. + */ + static final class IHateGuiceInjectorProvider { + + private static final Map injectors = new ConcurrentHashMap<>(); + + @Inject + static void acceptRegistration(final PluginContainer container, final Injector injector) { + IHateGuiceInjectorProvider.injectors.put(container, injector); + } + + public static @Nullable Injector get(final PluginContainer container) { + return IHateGuiceInjectorProvider.injectors.get(container); + } + } /** @@ -64,13 +130,20 @@ protected void configure() { * * {@literal @}ConfigDir(sharedRoot = false) Path configDir; */ - public static class NonSharedDirAsPath implements Provider { + static final class NonSharedDirAsPath implements Provider { - @Inject private PluginContainer container; + private final PluginContainer container; + private final PluginConfigManager mgr; + + @Inject + NonSharedDirAsPath(final PluginContainer container, final PluginConfigManager mgr) { + this.container = container; + this.mgr = mgr; + } @Override public Path get() { - return PluginConfigManager.getPrivateRoot(this.container).getDirectory(); + return this.mgr.getPluginConfig(this.container).getDirectory(); } } @@ -80,13 +153,20 @@ public Path get() { * * {@literal @}DefaultConfig(sharedRoot = false) Path configPath; */ - public static class NonSharedPathAsPath implements Provider { + static final class NonSharedPathAsPath implements Provider { - @Inject private PluginContainer container; + private final PluginContainer container; + private final PluginConfigManager mgr; + + @Inject + NonSharedPathAsPath(final PluginContainer container, final PluginConfigManager mgr) { + this.container = container; + this.mgr = mgr; + } @Override public Path get() { - return PluginConfigManager.getPrivateRoot(this.container).getConfigPath(); + return this.mgr.getPluginConfig(this.container).getConfigPath(); } } @@ -96,40 +176,171 @@ public Path get() { * * {@literal @}DefaultConfig(sharedRoot = true) Path configFile; */ - static class SharedDirAsPath implements Provider { + static final class SharedDirAsPath implements Provider { - @Inject private PluginContainer container; + private final PluginContainer container; + private final PluginConfigManager mgr; + + @Inject + SharedDirAsPath(final PluginContainer container, final PluginConfigManager mgr) { + this.container = container; + this.mgr = mgr; + } @Override public Path get() { - return PluginConfigManager.getSharedRoot(this.container).getConfigPath(); + return this.mgr.getSharedConfig(this.container).getConfigPath(); } } - static abstract class CommentedConfigurationNodeProvider implements Provider> { + abstract static class CommentedConfigurationNodeProvider implements Provider> { - @Inject protected PluginContainer container; + protected final PluginContainer container; + protected final PluginConfigManager mgr; + protected final Provider serializers; - CommentedConfigurationNodeProvider() { + @Inject + CommentedConfigurationNodeProvider(final PluginContainer container, final PluginConfigManager mgr, + final Provider serializers) { + this.container = container; + this.mgr = mgr; + this.serializers = serializers; } } - static class SharedCommentedConfigurationNode extends CommentedConfigurationNodeProvider { + static final class SharedCommentedConfigurationNode extends CommentedConfigurationNodeProvider { + + @Inject + SharedCommentedConfigurationNode(final PluginContainer container, final PluginConfigManager mgr, + final Provider serializers) { + super(container, mgr, serializers); + } @Override public ConfigurationLoader get() { - return PluginConfigManager.getSharedRoot(this.container).getConfig(); + return this.mgr.getSharedConfig(this.container).getConfig(PluginConfigManager.getOptions(this.serializers.get())); } } - static class PrivateCommentedConfigurationNode extends CommentedConfigurationNodeProvider { + static final class PrivateCommentedConfigurationNode extends CommentedConfigurationNodeProvider { + + @Inject + PrivateCommentedConfigurationNode(final PluginContainer container, final PluginConfigManager mgr, + final Provider serializers) { + super(container, mgr, serializers); + } @Override public ConfigurationLoader get() { - return PluginConfigManager.getPrivateRoot(this.container).getConfig(); + return this.mgr.getPluginConfig(this.container).getConfig(PluginConfigManager.getOptions(this.serializers.get())); + } + + } + + abstract static class CommentedConfigurationNodeReferenceProvider implements Provider> { + + protected final PluginContainer container; + protected final PluginConfigManager mgr; + protected final Provider serializers; + + @Inject + CommentedConfigurationNodeReferenceProvider(final PluginContainer container, final PluginConfigManager mgr, + final Provider serializers) { + this.container = container; + this.mgr = mgr; + this.serializers = serializers; + } + + /** + * Set up error logging for the created reference in the plugin's logger. + * + * @param file File loaded from + * @param reference Configuration reference to configure + * @param node type + * @return input {@code reference} + */ + protected ConfigurationReference configureLogging(final Path file, + final ConfigurationReference reference) { + reference.errors().subscribe(error -> { + final ConfigurationReference.ErrorPhase phase = error.getKey(); + final Throwable cause = error.getValue(); + this.container.getLogger().error("Failed to perform a {} in the configuration for {} at {}:", + phase, this.container.getMetadata().getId(), file, cause); + }); + return reference; + } + + } + + static final class SharedCommentedConfigurationNodeReference extends CommentedConfigurationNodeReferenceProvider { + + @Inject + SharedCommentedConfigurationNodeReference(final PluginContainer container, final PluginConfigManager mgr, + final Provider serializers) { + super(container, mgr, serializers); + } + + @Override + public ConfigurationReference get() { + final ConfigRoot shared = this.mgr.getSharedConfig(this.container); + try { + return this.configureLogging(shared.getConfigPath(), this.mgr.getWatchServiceListener() + .listenToConfiguration(path -> shared.getConfig(PluginConfigManager.getOptions(this.serializers.get())), shared.getConfigPath())); + } catch (final ConfigurateException ex) { + throw new ProvisionException("Unable to load configuration reference", ex); + } + } + + } + + static final class PrivateCommentedConfigurationNodeReference extends CommentedConfigurationNodeReferenceProvider { + + @Inject + PrivateCommentedConfigurationNodeReference(final PluginContainer container, final PluginConfigManager mgr, + final Provider serializers) { + super(container, mgr, serializers); + } + + @Override + public ConfigurationReference get() { + final ConfigRoot privateRoot = this.mgr.getPluginConfig(this.container); + try { + return this.configureLogging(privateRoot.getConfigPath(), this.mgr.getWatchServiceListener() + .listenToConfiguration(path -> privateRoot.getConfig(PluginConfigManager.getOptions(this.serializers.get())), + privateRoot.getConfigPath())); + } catch (final ConfigurateException ex) { + throw new ProvisionException("Unable to load configuration reference", ex); + } + } + + } + + static final class TypeSerializers implements Provider { + + private final PluginContainer container; + private final PluginConfigManager mgr; + + @Inject + TypeSerializers(final PluginContainer container, final PluginConfigManager mgr) { + this.container = container; + this.mgr = mgr; + } + + @Override + public TypeSerializerCollection get() { + final @Nullable Injector injector = IHateGuiceInjectorProvider.get(this.container); + if (injector == null) { + return this.mgr.getSerializers(); + } else { + return this.mgr.getSerializers().childBuilder() + .registerAnnotatedObjects(ObjectMapper.factoryBuilder() + .addDiscoverer(GuiceObjectMapperProvider.injectedObjectDiscoverer(injector)) + .build()) + .build(); + } } } diff --git a/src/main/java/org/spongepowered/common/plugin/PluginContainerExtension.java b/src/main/java/org/spongepowered/common/plugin/PluginContainerExtension.java deleted file mode 100644 index c33276bd92f..00000000000 --- a/src/main/java/org/spongepowered/common/plugin/PluginContainerExtension.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * 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. - */ -package org.spongepowered.common.plugin; - -import com.google.inject.Injector; - -public interface PluginContainerExtension { - - Injector getInjector(); - -} diff --git a/src/main/java/org/spongepowered/common/registry/SpongeCatalogRegistry.java b/src/main/java/org/spongepowered/common/registry/SpongeCatalogRegistry.java index f6da097603e..e6aed5d618c 100644 --- a/src/main/java/org/spongepowered/common/registry/SpongeCatalogRegistry.java +++ b/src/main/java/org/spongepowered/common/registry/SpongeCatalogRegistry.java @@ -25,7 +25,8 @@ package org.spongepowered.common.registry; import com.google.common.collect.ImmutableSet; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.GenericTypeReflector; +import io.leangen.geantyref.TypeToken; import com.google.inject.Singleton; import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; @@ -490,7 +491,7 @@ private SpongeCatalogRegistry registerMappedRegistry( public C registerCatalog(final TypeToken catalog, final C catalogType) { Objects.requireNonNull(catalogType); - final Registry registry = (Registry) this.registriesByType.get(catalog.getRawType()); + final Registry registry = (Registry) this.registriesByType.get(GenericTypeReflector.erase(catalog.getType())); if (registry == null) { throw new UnknownTypeException(String.format("Catalog '%s' with id '%s' has no registry registered!", catalogType.getClass(), catalogType.getKey())); } @@ -508,7 +509,7 @@ public void callDataPackRegisterCatalogEvents(Cause cause, Game game) { private void callRegisterCatalogEvents(final Cause cause, final Game game, List> catalogs) { for (final Class dynamicCatalog : catalogs) { - final TypeToken token = TypeToken.of(dynamicCatalog); + final TypeToken token = TypeToken.get(dynamicCatalog); game.getEventManager().post(new RegisterCatalogEventImpl<>(cause, game, (TypeToken) token)); } } diff --git a/src/main/java/org/spongepowered/common/registry/builtin/sponge/EventContextKeyStreamGenerator.java b/src/main/java/org/spongepowered/common/registry/builtin/sponge/EventContextKeyStreamGenerator.java index e00d97b2302..c9d246f3cd2 100644 --- a/src/main/java/org/spongepowered/common/registry/builtin/sponge/EventContextKeyStreamGenerator.java +++ b/src/main/java/org/spongepowered/common/registry/builtin/sponge/EventContextKeyStreamGenerator.java @@ -24,10 +24,31 @@ */ package org.spongepowered.common.registry.builtin.sponge; +import net.kyori.adventure.audience.Audience; import org.spongepowered.api.ResourceKey; +import org.spongepowered.api.block.BlockSnapshot; +import org.spongepowered.api.data.type.HandType; +import org.spongepowered.api.entity.Entity; +import org.spongepowered.api.entity.living.Living; +import org.spongepowered.api.entity.living.player.Player; +import org.spongepowered.api.entity.living.player.User; import org.spongepowered.api.event.EventContextKey; -import org.spongepowered.api.util.TypeTokens; +import org.spongepowered.api.event.block.ChangeBlockEvent; +import org.spongepowered.api.event.cause.entity.DismountType; +import org.spongepowered.api.event.cause.entity.MovementType; +import org.spongepowered.api.event.cause.entity.SpawnType; +import org.spongepowered.api.event.cause.entity.damage.DamageType; +import org.spongepowered.api.event.cause.entity.damage.source.DamageSource; +import org.spongepowered.api.item.inventory.ItemStackSnapshot; +import org.spongepowered.api.profile.GameProfile; +import org.spongepowered.api.projectile.source.ProjectileSource; +import org.spongepowered.api.service.permission.Subject; +import org.spongepowered.api.world.LocatableBlock; +import org.spongepowered.api.world.ServerLocation; +import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.common.event.SpongeEventContextKey; +import org.spongepowered.math.vector.Vector3d; +import org.spongepowered.plugin.PluginContainer; import java.util.stream.Stream; @@ -36,48 +57,48 @@ public final class EventContextKeyStreamGenerator { public static Stream> stream() { // @formatter:off return Stream.of( - new SpongeEventContextKey<>(ResourceKey.sponge("audience"), TypeTokens.AUDIENCE), - new SpongeEventContextKey<>(ResourceKey.sponge("block_event_process"), TypeTokens.LOCATABLE_BLOCK_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("block_event_queue"), TypeTokens.LOCATABLE_BLOCK_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("block_hit"), TypeTokens.BLOCK_SNAPSHOT_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("block_target"), TypeTokens.BLOCK_SNAPSHOT_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("break_event"), TypeTokens.CHANGE_BLOCK_EVENT_BREAK_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("command"), TypeTokens.STRING_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("creator"), TypeTokens.USER_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("damage_type"), TypeTokens.DAMAGE_TYPE_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("decay_event"), TypeTokens.CHANGE_BLOCK_EVENT_DECAY_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("dismount_type"), TypeTokens.DISMOUNT_TYPE_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("entity_hit"), TypeTokens.ENTITY_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("fake_player"), TypeTokens.PLAYER_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("fire_spread"), TypeTokens.SERVER_WORLD_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("growth_origin"), TypeTokens.BLOCK_SNAPSHOT_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("grow_event"), TypeTokens.CHANGE_BLOCK_EVENT_GROW_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("igniter"), TypeTokens.LIVING_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("last_damage_source"), TypeTokens.DAMAGE_SOURCE_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("leaves_decay"), TypeTokens.SERVER_WORLD_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("liquid_break"), TypeTokens.SERVER_WORLD_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("liquid_flow"), TypeTokens.SERVER_WORLD_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("liquid_mix"), TypeTokens.SERVER_WORLD_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("location"), TypeTokens.SERVER_LOCATION_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("modify_event"), TypeTokens.CHANGE_BLOCK_EVENT_MODIFY_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("movement_type"), TypeTokens.MOVEMENT_TYPE_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("neighbor_notify_source"), TypeTokens.BLOCK_SNAPSHOT_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("notifier"), TypeTokens.USER_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("piston_extend"), TypeTokens.SERVER_WORLD_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("piston_retract"), TypeTokens.SERVER_WORLD_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("place_event"), TypeTokens.CHANGE_BLOCK_EVENT_PLACE_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("player"), TypeTokens.PLAYER_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("player_break"), TypeTokens.SERVER_WORLD_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("player_place"), TypeTokens.SERVER_WORLD_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("plugin"), TypeTokens.PLUGIN_CONTAINER_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("projectile_source"), TypeTokens.PROJECTILE_SOURCE_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("rotation"), TypeTokens.VECTOR_3D_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("simulated_player"), TypeTokens.GAME_PROFILE_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("spawn_type"), TypeTokens.SPAWN_TYPE_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("subject"), TypeTokens.SUBJECT_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("used_hand"), TypeTokens.HAND_TYPE_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("used_item"), TypeTokens.ITEM_STACK_SNAPSHOT_TOKEN), - new SpongeEventContextKey<>(ResourceKey.sponge("weapon"), TypeTokens.ITEM_STACK_SNAPSHOT_TOKEN) + new SpongeEventContextKey<>(ResourceKey.sponge("audience"), Audience.class), + new SpongeEventContextKey<>(ResourceKey.sponge("block_event_process"), LocatableBlock.class), + new SpongeEventContextKey<>(ResourceKey.sponge("block_event_queue"), LocatableBlock.class), + new SpongeEventContextKey<>(ResourceKey.sponge("block_hit"), BlockSnapshot.class), + new SpongeEventContextKey<>(ResourceKey.sponge("block_target"), BlockSnapshot.class), + new SpongeEventContextKey<>(ResourceKey.sponge("break_event"), ChangeBlockEvent.Break.class), + new SpongeEventContextKey<>(ResourceKey.sponge("command"), String.class), + new SpongeEventContextKey<>(ResourceKey.sponge("creator"), User.class), + new SpongeEventContextKey<>(ResourceKey.sponge("damage_type"), DamageType.class), + new SpongeEventContextKey<>(ResourceKey.sponge("decay_event"), ChangeBlockEvent.Decay.class), + new SpongeEventContextKey<>(ResourceKey.sponge("dismount_type"), DismountType.class), + new SpongeEventContextKey<>(ResourceKey.sponge("entity_hit"), Entity.class), + new SpongeEventContextKey<>(ResourceKey.sponge("fake_player"), Player.class), + new SpongeEventContextKey<>(ResourceKey.sponge("fire_spread"), ServerWorld.class), + new SpongeEventContextKey<>(ResourceKey.sponge("growth_origin"), BlockSnapshot.class), + new SpongeEventContextKey<>(ResourceKey.sponge("grow_event"), ChangeBlockEvent.Grow.class), + new SpongeEventContextKey<>(ResourceKey.sponge("igniter"), Living.class), + new SpongeEventContextKey<>(ResourceKey.sponge("last_damage_source"), DamageSource.class), + new SpongeEventContextKey<>(ResourceKey.sponge("leaves_decay"), ServerWorld.class), + new SpongeEventContextKey<>(ResourceKey.sponge("liquid_break"), ServerWorld.class), + new SpongeEventContextKey<>(ResourceKey.sponge("liquid_flow"), ServerWorld.class), + new SpongeEventContextKey<>(ResourceKey.sponge("liquid_mix"), ServerWorld.class), + new SpongeEventContextKey<>(ResourceKey.sponge("location"), ServerLocation.class), + new SpongeEventContextKey<>(ResourceKey.sponge("modify_event"), ChangeBlockEvent.Modify.class), + new SpongeEventContextKey<>(ResourceKey.sponge("movement_type"), MovementType.class), + new SpongeEventContextKey<>(ResourceKey.sponge("neighbor_notify_source"), BlockSnapshot.class), + new SpongeEventContextKey<>(ResourceKey.sponge("notifier"), User.class), + new SpongeEventContextKey<>(ResourceKey.sponge("piston_extend"), ServerWorld.class), + new SpongeEventContextKey<>(ResourceKey.sponge("piston_retract"), ServerWorld.class), + new SpongeEventContextKey<>(ResourceKey.sponge("place_event"), ChangeBlockEvent.Place.class), + new SpongeEventContextKey<>(ResourceKey.sponge("player"), Player.class), + new SpongeEventContextKey<>(ResourceKey.sponge("player_break"), ServerWorld.class), + new SpongeEventContextKey<>(ResourceKey.sponge("player_place"), ServerWorld.class), + new SpongeEventContextKey<>(ResourceKey.sponge("plugin"), PluginContainer.class), + new SpongeEventContextKey<>(ResourceKey.sponge("projectile_source"), ProjectileSource.class), + new SpongeEventContextKey<>(ResourceKey.sponge("rotation"), Vector3d.class), + new SpongeEventContextKey<>(ResourceKey.sponge("simulated_player"), GameProfile.class), + new SpongeEventContextKey<>(ResourceKey.sponge("spawn_type"), SpawnType.class), + new SpongeEventContextKey<>(ResourceKey.sponge("subject"), Subject.class), + new SpongeEventContextKey<>(ResourceKey.sponge("used_hand"), HandType.class), + new SpongeEventContextKey<>(ResourceKey.sponge("used_item"), ItemStackSnapshot.class), + new SpongeEventContextKey<>(ResourceKey.sponge("weapon"), ItemStackSnapshot.class) ); // @formatter:on } diff --git a/src/main/java/org/spongepowered/common/registry/builtin/sponge/KeyStreamGenerator.java b/src/main/java/org/spongepowered/common/registry/builtin/sponge/KeyStreamGenerator.java index 47c2a902661..9e924d16170 100644 --- a/src/main/java/org/spongepowered/common/registry/builtin/sponge/KeyStreamGenerator.java +++ b/src/main/java/org/spongepowered/common/registry/builtin/sponge/KeyStreamGenerator.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.registry.builtin.sponge; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.data.Key; import org.spongepowered.api.data.value.Value; diff --git a/src/main/java/org/spongepowered/common/relocate/co/aikar/timings/TimingsExport.java b/src/main/java/org/spongepowered/common/relocate/co/aikar/timings/TimingsExport.java index 82799f4534c..d4ed530a8bc 100644 --- a/src/main/java/org/spongepowered/common/relocate/co/aikar/timings/TimingsExport.java +++ b/src/main/java/org/spongepowered/common/relocate/co/aikar/timings/TimingsExport.java @@ -36,7 +36,7 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.event.ClickEvent; import net.kyori.adventure.text.format.NamedTextColor; -import ninja.leaping.configurate.ConfigurationNode; +import org.spongepowered.configurate.ConfigurationNode; import org.spongepowered.api.Platform; import org.spongepowered.api.Sponge; import org.spongepowered.api.block.entity.BlockEntityType; @@ -236,11 +236,11 @@ static long getCost() { return timingsCost; } - private static JsonElement serializeConfigNode(ConfigurationNode node) { + private static JsonElement serializeConfigNode(final ConfigurationNode node) { if (node.isMap()) { - JsonObject object = new JsonObject(); - for (Entry entry : node.getChildrenMap().entrySet()) { - String fullPath = CONFIG_PATH_JOINER.join(entry.getValue().getPath()); + final JsonObject object = new JsonObject(); + for (final Entry entry : node.childrenMap().entrySet()) { + final String fullPath = CONFIG_PATH_JOINER.join(entry.getValue().path()); if (fullPath.equals("sponge.sql") || TimingsManager.hiddenConfigs.contains(fullPath)) { continue; } @@ -249,13 +249,13 @@ private static JsonElement serializeConfigNode(ConfigurationNode node) { return object; } if (node.isList()) { - JsonArray array = new JsonArray(); - for (ConfigurationNode child : node.getChildrenList()) { + final JsonArray array = new JsonArray(); + for (final ConfigurationNode child : node.childrenList()) { array.add(serializeConfigNode(child)); } return array; } - return JSONUtil.toJsonElement(node.getValue()); + return JSONUtil.toJsonElement(node.raw()); } @Override diff --git a/src/main/java/org/spongepowered/common/service/SpongeServiceProvider.java b/src/main/java/org/spongepowered/common/service/SpongeServiceProvider.java index f8b1ad3a46e..8c8fea79419 100644 --- a/src/main/java/org/spongepowered/common/service/SpongeServiceProvider.java +++ b/src/main/java/org/spongepowered/common/service/SpongeServiceProvider.java @@ -25,7 +25,7 @@ package org.spongepowered.common.service; import com.google.common.base.Preconditions; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import com.google.inject.Inject; import com.google.inject.Injector; import org.apache.logging.log4j.Level; diff --git a/src/main/java/org/spongepowered/common/service/game/SpongeGameScopedServiceProvider.java b/src/main/java/org/spongepowered/common/service/game/SpongeGameScopedServiceProvider.java index 81e6933c895..d4080c7c680 100644 --- a/src/main/java/org/spongepowered/common/service/game/SpongeGameScopedServiceProvider.java +++ b/src/main/java/org/spongepowered/common/service/game/SpongeGameScopedServiceProvider.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.service.game; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; @@ -63,7 +63,7 @@ protected List> servicesToSelect() { protected final ProvideServiceEventImpl createEvent(final PluginContainer container, final Service service) { return new ProvideServiceEventImpl(Cause.of(EventContext.empty(), this.getGame()), this.getGame(), - TypeToken.of(service.getServiceClass())); + TypeToken.get(service.getServiceClass())); } @Override diff --git a/src/main/java/org/spongepowered/common/service/game/pagination/PaginationCalculator.java b/src/main/java/org/spongepowered/common/service/game/pagination/PaginationCalculator.java index a1dda4d1fd5..2c6a2da728a 100644 --- a/src/main/java/org/spongepowered/common/service/game/pagination/PaginationCalculator.java +++ b/src/main/java/org/spongepowered/common/service/game/pagination/PaginationCalculator.java @@ -30,17 +30,15 @@ import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TranslationTextComponent; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.commented.CommentedConfigurationNode; -import ninja.leaping.configurate.hocon.HoconConfigurationLoader; -import ninja.leaping.configurate.loader.ConfigurationLoader; -import ninja.leaping.configurate.loader.HeaderMode; +import org.apache.commons.lang3.ArrayUtils; +import org.spongepowered.configurate.ConfigurateException; +import org.spongepowered.configurate.CommentedConfigurationNode; +import org.spongepowered.configurate.hocon.HoconConfigurationLoader; +import org.spongepowered.configurate.loader.ConfigurationLoader; import org.spongepowered.common.adventure.SpongeAdventure; import org.spongepowered.math.GenericMath; -import java.io.IOException; import java.util.Collections; -import java.util.List; import java.util.PrimitiveIterator; /** @@ -67,26 +65,14 @@ final class PaginationCalculator { static { final ConfigurationLoader loader = HoconConfigurationLoader.builder() - .setURL(PaginationCalculator.class.getResource("font-sizes.json")) - .setHeaderMode(HeaderMode.NONE) + .url(PaginationCalculator.class.getResource("font-sizes.json")) .build(); try { - final ConfigurationNode node = loader.load(); - NON_UNICODE_CHARS = node.getNode("non-unicode").getString(); - final List charWidths = node.getNode("char-widths").getChildrenList(); - final int[] nonUnicodeCharWidths = new int[charWidths.size()]; - for (int i = 0; i < nonUnicodeCharWidths.length; ++i) { - nonUnicodeCharWidths[i] = charWidths.get(i).getInt(); - } - NON_UNICODE_CHAR_WIDTHS = nonUnicodeCharWidths; - - final List glyphWidths = node.getNode("glyph-widths").getChildrenList(); - final byte[] unicodeCharWidths = new byte[glyphWidths.size()]; - for (int i = 0; i < unicodeCharWidths.length; ++i) { - unicodeCharWidths[i] = (byte) glyphWidths.get(i).getInt(); - } - UNICODE_CHAR_WIDTHS = unicodeCharWidths; - } catch (final IOException e) { + final CommentedConfigurationNode node = loader.load(); + NON_UNICODE_CHARS = node.node("non-unicode").getString(); + NON_UNICODE_CHAR_WIDTHS = node.node("char-widths").get(int[].class, ArrayUtils.EMPTY_INT_ARRAY); + UNICODE_CHAR_WIDTHS = node.node("glyph-widths").get(byte[].class, ArrayUtils.EMPTY_BYTE_ARRAY); + } catch (final ConfigurateException e) { throw new ExceptionInInitializerError(e); } } diff --git a/src/main/java/org/spongepowered/common/service/server/SpongeServerScopedServiceProvider.java b/src/main/java/org/spongepowered/common/service/server/SpongeServerScopedServiceProvider.java index f8cf26bdcf0..751ae526643 100644 --- a/src/main/java/org/spongepowered/common/service/server/SpongeServerScopedServiceProvider.java +++ b/src/main/java/org/spongepowered/common/service/server/SpongeServerScopedServiceProvider.java @@ -25,7 +25,7 @@ package org.spongepowered.common.service.server; import com.google.common.collect.ImmutableList; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import com.google.inject.Inject; import com.google.inject.Injector; import org.checkerframework.checker.nullness.qual.NonNull; @@ -86,7 +86,7 @@ protected List> servicesToSelect() { protected ProvideServiceEventImpl createEvent(PluginContainer container, Service service) { return new ProvideEngineServiceEventImpl<>(Cause.of(EventContext.empty(), this.getGame()), this.getGame(), - TypeToken.of(service.getServiceClass()), + TypeToken.get(service.getServiceClass()), this.server ); } diff --git a/src/main/java/org/spongepowered/common/statistic/SpongeStatisticCategoryType.java b/src/main/java/org/spongepowered/common/statistic/SpongeStatisticCategoryType.java index e0c5d1fd34f..69dba69d3cb 100644 --- a/src/main/java/org/spongepowered/common/statistic/SpongeStatisticCategoryType.java +++ b/src/main/java/org/spongepowered/common/statistic/SpongeStatisticCategoryType.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.statistic; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import org.spongepowered.api.CatalogType; import org.spongepowered.api.statistic.Statistic; import org.spongepowered.api.statistic.StatisticCategory; diff --git a/src/main/java/org/spongepowered/common/util/IpSet.java b/src/main/java/org/spongepowered/common/util/IpSet.java index 5ac5703fdf6..291e2a5cbff 100644 --- a/src/main/java/org/spongepowered/common/util/IpSet.java +++ b/src/main/java/org/spongepowered/common/util/IpSet.java @@ -27,11 +27,11 @@ import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.Predicate; -import com.google.common.reflect.TypeToken; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; -import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer; +import org.spongepowered.configurate.ConfigurationNode; +import org.spongepowered.configurate.serialize.SerializationException; +import org.spongepowered.configurate.serialize.TypeSerializer; +import java.lang.reflect.Type; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; @@ -129,17 +129,17 @@ public String toString() { public static final class IpSetSerializer implements TypeSerializer { @Override - public IpSet deserialize(final TypeToken type, final ConfigurationNode value) throws ObjectMappingException { + public IpSet deserialize(final Type type, final ConfigurationNode value) throws SerializationException { try { return IpSet.fromCidr(value.getString()); } catch (final IllegalArgumentException e) { - throw new ObjectMappingException(e); + throw new SerializationException(e); } } @Override - public void serialize(final TypeToken type, final IpSet obj, final ConfigurationNode value) throws ObjectMappingException { - value.setValue(obj.toString()); + public void serialize(final Type type, final IpSet obj, final ConfigurationNode value) throws SerializationException { + value.set(obj == null ? null : obj.toString()); } } } diff --git a/src/main/java/org/spongepowered/common/util/SpongeMetricsConfigManager.java b/src/main/java/org/spongepowered/common/util/SpongeMetricsConfigManager.java index b4815e489e8..640c5c05f47 100644 --- a/src/main/java/org/spongepowered/common/util/SpongeMetricsConfigManager.java +++ b/src/main/java/org/spongepowered/common/util/SpongeMetricsConfigManager.java @@ -25,7 +25,7 @@ package org.spongepowered.common.util; import com.google.inject.Singleton; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; +import org.spongepowered.configurate.ConfigurateException; import org.spongepowered.api.util.Tristate; import org.spongepowered.api.util.metric.MetricsConfigManager; import org.spongepowered.common.applaunch.config.core.ConfigHandle; @@ -33,14 +33,12 @@ import org.spongepowered.common.config.metrics.MetricsConfiguration; import org.spongepowered.plugin.PluginContainer; -import java.io.IOException; - @Singleton public class SpongeMetricsConfigManager implements MetricsConfigManager { private final ConfigHandle metrics; - public SpongeMetricsConfigManager() throws IOException, ObjectMappingException { + public SpongeMetricsConfigManager() throws ConfigurateException { // This needs to be loaded after the global-inheritable configuration // is loaded. That load is performed by the sponge non-inheritable // configuration which is loaded way earlier in the lifecycle since it diff --git a/src/main/java/org/spongepowered/common/util/TypeTokenHelper.java b/src/main/java/org/spongepowered/common/util/TypeTokenHelper.java index d1af436e774..68c427c1d3a 100644 --- a/src/main/java/org/spongepowered/common/util/TypeTokenHelper.java +++ b/src/main/java/org/spongepowered/common/util/TypeTokenHelper.java @@ -24,7 +24,8 @@ */ package org.spongepowered.common.util; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.GenericTypeReflector; +import io.leangen.geantyref.TypeToken; import java.lang.reflect.Array; import java.lang.reflect.GenericArrayType; @@ -39,19 +40,56 @@ @SuppressWarnings({"unchecked", "rawtypes", "WeakerAccess"}) public final class TypeTokenHelper { - public static Class getGenericParam(TypeToken token, int typeIndex) { + public static Class getGenericParam(final TypeToken token, final int typeIndex) { return (Class) ((ParameterizedType) token.getType()).getActualTypeArguments()[typeIndex]; } - public static boolean isAssignable(TypeToken type, TypeToken toType) { + /** + * Throw an exception if the passed type is raw + * + * @param input input type + * @return type, passed through + */ + public static Type requireCompleteGenerics(final Type input) { + if (GenericTypeReflector.isMissingTypeParameters(input)) { + throw new IllegalArgumentException("Provided type " + input + " is a raw type, which is not accepted."); + } + return input; + } + + /** + * Given a known declared subtype, determine the value of a specific type parameter in a supertype. + * + * @param sub subtype + * @param superType superclass to resolve + * @param idx Parameter index to resolve + * @return type argument + */ + public static Type typeArgumentFromSupertype(final Type sub, final Class superType, final int idx) { + final Type calculatedSuper = GenericTypeReflector.getExactSuperType(sub, superType); + if (!(calculatedSuper instanceof ParameterizedType)) { + throw new IllegalArgumentException("Calculated supertype " + calculatedSuper + " of original type " + sub + " is not parameterized"); + } + final Type[] parameters = ((ParameterizedType) calculatedSuper).getActualTypeArguments(); + if (parameters.length < idx) { + throw new IllegalArgumentException("Expected calculated supertype " + calculatedSuper + " of type " + sub + " to have at least " + idx + + "parameter(s), but got " + parameters.length); + } + return parameters[idx]; + } + + // Type comparison functions + // Unlike normal GenericTypeReflector#isSupertypeOf, these functions treat generic parameters as covariant. + + public static boolean isAssignable(final TypeToken type, final TypeToken toType) { return isAssignable(type.getType(), toType.getType()); } - public static boolean isAssignable(Type type, Type toType) { + public static boolean isAssignable(final Type type, final Type toType) { return isAssignable(type, toType, null, 0); } - private static boolean isAssignable(Type type, Type toType, @Nullable Type parent, int index) { + private static boolean isAssignable(final Type type, final Type toType, final @Nullable Type parent, final int index) { if (type.equals(toType)) { return true; } @@ -136,7 +174,7 @@ private static boolean isAssignable(Type type, ParameterizedType toType, @Nullab types = otherRaw.getTypeParameters(); } else { // Get the type parameters based on the super class - final ParameterizedType other = (ParameterizedType) TypeToken.of(type).getSupertype((Class) toRaw).getType(); + final ParameterizedType other = (ParameterizedType) GenericTypeReflector.getExactSuperType(type, toRaw); types = other.getActualTypeArguments(); } if (types.length != toTypes.length) { @@ -168,7 +206,7 @@ private static boolean isAssignable(Type type, ParameterizedType toType, @Nullab types = other.getActualTypeArguments(); } else { // Get the type parameters based on the super class - other = (ParameterizedType) TypeToken.of(other).getSupertype((Class) toRaw).getType(); + other = (ParameterizedType) GenericTypeReflector.getExactSuperType(other, toRaw); types = other.getActualTypeArguments(); } final Type[] toTypes = toType.getActualTypeArguments(); @@ -200,16 +238,16 @@ private static boolean isAssignable(Type type, ParameterizedType toType, @Nullab throw new IllegalStateException("Unsupported type: " + type); } - private static boolean isAssignable(Type type, TypeVariable toType, @Nullable Type parent, int index) { + private static boolean isAssignable(final Type type, final TypeVariable toType, final @Nullable Type parent, final int index) { return allAssignable(type, toType.getBounds()); } - private static boolean isAssignable(Type type, WildcardType toType, @Nullable Type parent, int index) { + private static boolean isAssignable(final Type type, final WildcardType toType, final @Nullable Type parent, final int index) { return allWildcardAssignable(type, toType.getUpperBounds(), parent, index) && allSupertypes(type, toType.getLowerBounds()); } - private static boolean isAssignable(Type type, GenericArrayType toType, @Nullable Type parent, int index) { + private static boolean isAssignable(final Type type, final GenericArrayType toType, final @Nullable Type parent, final int index) { if (type instanceof Class) { final Class other = (Class) type; return other.isArray() && isAssignable(other.getComponentType(), toType.getGenericComponentType(), parent, index); diff --git a/src/main/java/org/spongepowered/common/util/UsernameCache.java b/src/main/java/org/spongepowered/common/util/UsernameCache.java index 0ada8e5e2a7..b123e22c52c 100644 --- a/src/main/java/org/spongepowered/common/util/UsernameCache.java +++ b/src/main/java/org/spongepowered/common/util/UsernameCache.java @@ -41,7 +41,7 @@ import org.spongepowered.api.Server; import org.spongepowered.common.SpongeCommon; import com.google.common.base.Charsets; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; diff --git a/src/main/java/org/spongepowered/common/world/server/WorldMigrator.java b/src/main/java/org/spongepowered/common/world/server/WorldMigrator.java index 75ef11be76d..aceac9b8746 100644 --- a/src/main/java/org/spongepowered/common/world/server/WorldMigrator.java +++ b/src/main/java/org/spongepowered/common/world/server/WorldMigrator.java @@ -24,12 +24,13 @@ */ package org.spongepowered.common.world.server; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.yaml.YAMLConfigurationLoader; +import org.spongepowered.configurate.ConfigurateException; +import org.spongepowered.configurate.ConfigurationNode; import org.apache.commons.io.FileUtils; import org.spongepowered.api.Sponge; import org.spongepowered.api.util.file.CopyFileVisitor; import org.spongepowered.common.SpongeCommon; +import org.spongepowered.configurate.yaml.YamlConfigurationLoader; import java.io.IOException; import java.nio.file.DirectoryStream; @@ -59,18 +60,18 @@ public static Path getOldWorldContainer() { if (Files.exists(bukkitYml)) { try { - final ConfigurationNode node = YAMLConfigurationLoader.builder().setPath(bukkitYml).build().load(); - final String containerCandidate = node.getNode("settings", "world-container").getString(""); + final ConfigurationNode node = YamlConfigurationLoader.builder().path(bukkitYml).build().load(); + final String containerCandidate = node.node("settings", "world-container").getString(""); if (!containerCandidate.isEmpty()) { try { - worldContainer = Paths.get(worldContainer.toString()).resolve(containerCandidate); - } catch (InvalidPathException ipe) { + worldContainer = worldContainer.resolve(containerCandidate); + } catch (final InvalidPathException ipe) { SpongeCommon.getLogger().warn("Cannot use path [{}] specified under [world-container] in bukkit" + ".yml. Will use [{}] instead.", containerCandidate, worldContainer, ipe); } } - } catch (IOException ioe) { - SpongeCommon.getLogger().warn("Cannot load bukkit.yml. Will use [{}] instead.", worldContainer, ioe); + } catch (final ConfigurateException ex) { + SpongeCommon.getLogger().warn("Cannot load bukkit.yml. Will use [{}] instead.", worldContainer, ex); } } diff --git a/src/mixins/java/org/spongepowered/common/mixin/core/advancements/ICriterionTrigger_ListenerMixin.java b/src/mixins/java/org/spongepowered/common/mixin/core/advancements/ICriterionTrigger_ListenerMixin.java index 22f8ae93c0f..684616e3beb 100644 --- a/src/mixins/java/org/spongepowered/common/mixin/core/advancements/ICriterionTrigger_ListenerMixin.java +++ b/src/mixins/java/org/spongepowered/common/mixin/core/advancements/ICriterionTrigger_ListenerMixin.java @@ -24,7 +24,7 @@ */ package org.spongepowered.common.mixin.core.advancements; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import net.minecraft.advancements.Advancement; import net.minecraft.advancements.ICriterionInstance; import net.minecraft.advancements.ICriterionTrigger; @@ -78,7 +78,7 @@ public abstract class ICriterionTrigger_ListenerMixin { if (filteredTrigger.getType() instanceof SpongeTrigger) { final Cause cause = PhaseTracker.getCauseStackManager().getCurrentCause(); final ServerPlayer player = ((PlayerAdvancementsBridge) playerAdvancements).bridge$getPlayer(); - final TypeToken typeToken = TypeToken.of(filteredTrigger.getType().getConfigurationType()); + final TypeToken typeToken = TypeToken.get(filteredTrigger.getType().getConfigurationType()); final CriterionEvent.Trigger event = SpongeEventFactory.createCriterionEventTrigger(cause, advancement, advancementCriterion, typeToken, player, filteredTrigger, true); SpongeCommon.postEvent(event); diff --git a/src/test/invalid/common/data/manipulator/ManipulatorTest.java b/src/test/invalid/common/data/manipulator/ManipulatorTest.java index d679825b8b2..889dcb3c391 100644 --- a/src/test/invalid/common/data/manipulator/ManipulatorTest.java +++ b/src/test/invalid/common/data/manipulator/ManipulatorTest.java @@ -30,7 +30,7 @@ import static org.junit.Assert.assertThat; import com.google.common.collect.Lists; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import org.checkerframework.checker.nullness.Opt; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/src/test/invalid/common/util/TypeTokenHelperTest.java b/src/test/invalid/common/util/TypeTokenHelperTest.java deleted file mode 100644 index 4a43a9db548..00000000000 --- a/src/test/invalid/common/util/TypeTokenHelperTest.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * This file is part of Sponge, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * 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. - */ -package org.spongepowered.common.util; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.google.common.reflect.TypeToken; -import org.junit.Test; -import org.spongepowered.api.CatalogType; -import org.spongepowered.api.advancement.Advancement; -import org.spongepowered.api.data.DataRegistration; -import org.spongepowered.api.data.key.Key; -import org.spongepowered.api.data.manipulator.mutable.item.LoreData; -import org.spongepowered.api.data.value.BaseValue; -import org.spongepowered.api.data.value.mutable.Value; -import org.spongepowered.api.entity.living.Living; -import org.spongepowered.api.entity.living.complex.EnderDragon; -import org.spongepowered.api.entity.living.monster.Slime; - -public final class TypeTokenHelperTest { - - @SuppressWarnings("rawtypes") - @Test - public void testA() { - assertTrue(TypeTokenHelper.isAssignable( - new TypeToken>>() { - private static final long serialVersionUID = -2744183853363912523L; - }, - new TypeToken>>() { - private static final long serialVersionUID = 7512706472781562165L; - })); - - assertTrue(TypeTokenHelper.isAssignable( - new TypeToken>() { - private static final long serialVersionUID = -4715432165291356217L; - }, - new TypeToken>>() { - private static final long serialVersionUID = -9141111645139043586L; - })); - - assertFalse(TypeTokenHelper.isAssignable( - new TypeToken>>() { - private static final long serialVersionUID = -5084770058972215952L; - }, - new TypeToken>>() { - private static final long serialVersionUID = 5868333657416959838L; - })); - - assertFalse(TypeTokenHelper.isAssignable( - new TypeToken>>() { - private static final long serialVersionUID = -6063028554691111654L; - }, - new TypeToken>>() { - private static final long serialVersionUID = 6475178912364063462L; - })); - - assertFalse(TypeTokenHelper.isAssignable( - new TypeToken>>() { - private static final long serialVersionUID = 4476319679842566087L; - }, - new TypeToken>>() { - private static final long serialVersionUID = -8991894373263296838L; - })); - - assertFalse(TypeTokenHelper.isAssignable( - new TypeToken>>() { - private static final long serialVersionUID = -9127427898214080482L; - }, - new TypeToken>>() { - private static final long serialVersionUID = 3734740195264045904L; - })); - - assertFalse(TypeTokenHelper.isAssignable( - new TypeToken>>() { - private static final long serialVersionUID = -776294957769877612L; - }, - new TypeToken>>() { - private static final long serialVersionUID = -1080598601240787986L; - })); - - assertTrue(TypeTokenHelper.isAssignable( - new TypeToken>>() { - private static final long serialVersionUID = -1685122921179641087L; - }, - new TypeToken>>() { - private static final long serialVersionUID = -7506005421970616703L; - })); - - assertTrue(TypeTokenHelper.isAssignable( - new TypeToken>>() { - private static final long serialVersionUID = -146766369451278059L; - }, - new TypeToken>>() { - private static final long serialVersionUID = 7172322752250029262L; - })); - - assertTrue(TypeTokenHelper.isAssignable( - new TypeToken>>() { - private static final long serialVersionUID = -7530165981429256750L; - }, - TypeToken.of(Key.class))); - - assertFalse(TypeTokenHelper.isAssignable( - TypeToken.of(Key.class), - new TypeToken>>() { - private static final long serialVersionUID = -1048560465149463858L; - })); - - assertTrue(TypeTokenHelper.isAssignable( - new TypeToken() { - private static final long serialVersionUID = 4490040709077959054L; - }, - new TypeToken>() { - private static final long serialVersionUID = 1966793391819384134L; - })); - - assertFalse(TypeTokenHelper.isAssignable( - TypeToken.of(DataRegistration.class), - new TypeToken>() { - private static final long serialVersionUID = -2471612329609336642L; - })); - - assertFalse(TypeTokenHelper.isAssignable( - new TypeToken() { - private static final long serialVersionUID = 996573824362563041L; - }, - new TypeToken>() { - private static final long serialVersionUID = 7507644590282488025L; - })); - - assertFalse(TypeTokenHelper.isAssignable( - new TypeToken>() { - private static final long serialVersionUID = 6588698505383159642L; - }, - new TypeToken>() { - private static final long serialVersionUID = 2055481509347300371L; - })); - - assertTrue(TypeTokenHelper.isAssignable( - new TypeToken>() { - private static final long serialVersionUID = 6146344812465379270L; - }, - new TypeToken>() { - private static final long serialVersionUID = -1644821707399052814L; - })); - } - - @Test - public void testB() { - // Enclosing classes testing - - assertTrue(TypeTokenHelper.isAssignable( - new TypeToken.B>>() { - private static final long serialVersionUID = -7598875791253244116L; - }, - new TypeToken.B>>() { - private static final long serialVersionUID = -6473792914038707807L; - })); - - assertFalse(TypeTokenHelper.isAssignable( - new TypeToken>>.B>>() { - private static final long serialVersionUID = -7135507911189558819L; - }, - new TypeToken>>.B>>() { - private static final long serialVersionUID = -7720256698994675635L; - })); - - assertTrue(TypeTokenHelper.isAssignable( - new TypeToken>>.B>>() { - private static final long serialVersionUID = 3945720091540514712L; - }, - new TypeToken>>.B>>() { - private static final long serialVersionUID = -5900476749764702993L; - })); - } - - @Test - public void testC() { - assertFalse(TypeTokenHelper.isAssignable( - new TypeToken>() { - private static final long serialVersionUID = 210782457160028139L; - }, - new TypeToken>() { - private static final long serialVersionUID = 1830207951407728466L; - })); - - assertTrue(TypeTokenHelper.isAssignable( - new TypeToken>() { - private static final long serialVersionUID = 6306557918222324636L; - }, - new TypeToken>() { - private static final long serialVersionUID = 6287092056418459473L; - })); - - assertTrue(TypeTokenHelper.isAssignable( - new TypeToken() { - private static final long serialVersionUID = -2636161692715322380L; - }, - new TypeToken>() { - private static final long serialVersionUID = -7834521766542990084L; - })); - - assertTrue(TypeTokenHelper.isAssignable( - new TypeToken() { - private static final long serialVersionUID = -3899375880896785687L; - }, - new TypeToken>() { - private static final long serialVersionUID = 3361010897315894472L; - })); - - assertFalse(TypeTokenHelper.isAssignable( - new TypeToken>() { - private static final long serialVersionUID = -8695441578543610047L; - }, - new TypeToken() { - private static final long serialVersionUID = 3553380220811338485L; - })); - } - - private static class D extends A { - - } - - private static class C extends A { - - } - - private static class A { - - private class B { - } - } -} diff --git a/src/test/java/org/spongepowered/common/applaunch/config/core/DuplicateRemovalVisitorTest.java b/src/test/java/org/spongepowered/common/applaunch/config/core/DuplicateRemovalVisitorTest.java index 2d51ecded44..f8179b77e22 100644 --- a/src/test/java/org/spongepowered/common/applaunch/config/core/DuplicateRemovalVisitorTest.java +++ b/src/test/java/org/spongepowered/common/applaunch/config/core/DuplicateRemovalVisitorTest.java @@ -32,185 +32,187 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.commented.CommentedConfigurationNode; +import org.spongepowered.configurate.BasicConfigurationNode; +import org.spongepowered.configurate.ConfigurationNode; +import org.spongepowered.configurate.CommentedConfigurationNode; import org.junit.jupiter.api.Test; +import org.spongepowered.configurate.serialize.SerializationException; public class DuplicateRemovalVisitorTest { @Test void testEmpty() { - final ConfigurationNode parent = ConfigurationNode.root(); - final ConfigurationNode child = ConfigurationNode.root(); + final ConfigurationNode parent = BasicConfigurationNode.root(); + final ConfigurationNode child = BasicConfigurationNode.root(); DuplicateRemovalVisitor.visit(child, parent); } @Test void testClearEqualValues() { - final ConfigurationNode parent = ConfigurationNode.root(); - final ConfigurationNode child = ConfigurationNode.root(); - parent.setValue("test"); - child.setValue("test"); + final ConfigurationNode parent = BasicConfigurationNode.root(); + final ConfigurationNode child = BasicConfigurationNode.root(); + parent.raw("test"); + child.raw("test"); DuplicateRemovalVisitor.visit(child, parent); - assertNull(child.getValue()); + assertNull(child.raw()); } @Test void testClearsEqualDoubles() { - final ConfigurationNode parent = ConfigurationNode.root(); - final ConfigurationNode child = ConfigurationNode.root(); + final ConfigurationNode parent = BasicConfigurationNode.root(); + final ConfigurationNode child = BasicConfigurationNode.root(); - parent.setValue(3d); - child.setValue(3d); + parent.raw(3d); + child.raw(3d); DuplicateRemovalVisitor.visit(child, parent); - assertEquals(3d, parent.getValue()); - assertNull(child.getValue()); + assertEquals(3d, parent.raw()); + assertNull(child.raw()); - child.setValue(3); + child.raw(3); DuplicateRemovalVisitor.visit(child, parent); - assertNull(child.getValue()); + assertNull(child.raw()); } @Test void testClearsEqualDoublesInChild() { - final ConfigurationNode parent = ConfigurationNode.root(); - final ConfigurationNode child = ConfigurationNode.root(); + final ConfigurationNode parent = BasicConfigurationNode.root(); + final ConfigurationNode child = BasicConfigurationNode.root(); - parent.getNode("test").setValue(42); - child.getNode("test").setValue(42d); + parent.node("test").raw(42); + child.node("test").raw(42d); DuplicateRemovalVisitor.visit(child, parent); - assertTrue(child.isEmpty()); - assertNull(child.getNode("test").getValue()); + assertTrue(child.empty()); + assertNull(child.node("test").raw()); } @Test void testClearsMapKeys() { - final ConfigurationNode parent = ConfigurationNode.root(n -> { - n.getNode("test1").setValue("yeet"); - n.getNode("test2").setValue("yoink"); + final ConfigurationNode parent = BasicConfigurationNode.root(n -> { + n.node("test1").raw("yeet"); + n.node("test2").raw("yoink"); }); - final ConfigurationNode child = ConfigurationNode.root(n -> { - n.getNode("test1").setValue("yeet"); - n.getNode("test2").setValue("yikes"); + final ConfigurationNode child = BasicConfigurationNode.root(n -> { + n.node("test1").raw("yeet"); + n.node("test2").raw("yikes"); }); DuplicateRemovalVisitor.visit(child, parent); - assertTrue(child.getNode("test1").isVirtual()); - assertEquals("yikes", child.getNode("test2").getValue()); + assertTrue(child.node("test1").virtual()); + assertEquals("yikes", child.node("test2").raw()); } @Test - void testPreservesListElements() { - final ConfigurationNode parent = ConfigurationNode.root(n -> { - n.appendListNode().setValue("one"); - n.appendListNode().setValue("two"); - n.appendListNode().setValue("red"); - n.appendListNode().setValue("blue"); + void testPreservesListElements() throws SerializationException { + final ConfigurationNode parent = BasicConfigurationNode.root(n -> { + n.appendListNode().raw("one"); + n.appendListNode().raw("two"); + n.appendListNode().raw("red"); + n.appendListNode().raw("blue"); }); - final ConfigurationNode child = ConfigurationNode.root(n -> { - n.appendListNode().setValue("one"); - n.appendListNode().setValue("two"); - n.appendListNode().setValue("red"); - n.appendListNode().setValue("green"); + final ConfigurationNode child = BasicConfigurationNode.root(n -> { + n.appendListNode().raw("one"); + n.appendListNode().raw("two"); + n.appendListNode().raw("red"); + n.appendListNode().raw("green"); }); DuplicateRemovalVisitor.visit(child, parent); - assertEquals(ImmutableList.of("one", "two", "red", "green"), child.getList(String::valueOf)); + assertEquals(ImmutableList.of("one", "two", "red", "green"), child.getList(String.class)); } @Test void testEqualListCleared() { - final ConfigurationNode parent = ConfigurationNode.root(n -> { - n.appendListNode().setValue("one"); - n.appendListNode().setValue("two"); + final ConfigurationNode parent = BasicConfigurationNode.root(n -> { + n.appendListNode().raw("one"); + n.appendListNode().raw("two"); n.appendListNode().act(c -> { - c.getNode("zombie").setValue(false); - c.getNode("villager").setValue(false); - c.getNode("cat").setValue(true); - c.getNode("ocelot").setValue(true); + c.node("zombie").raw(false); + c.node("villager").raw(false); + c.node("cat").raw(true); + c.node("ocelot").raw(true); }); - n.appendListNode().setValue("blue"); + n.appendListNode().raw("blue"); }); - final ConfigurationNode child = ConfigurationNode.root(n -> { - n.appendListNode().setValue("one"); - n.appendListNode().setValue("two"); + final ConfigurationNode child = BasicConfigurationNode.root(n -> { + n.appendListNode().raw("one"); + n.appendListNode().raw("two"); n.appendListNode().act(c -> { - c.getNode("zombie").setValue(false); - c.getNode("villager").setValue(false); - c.getNode("cat").setValue(true); - c.getNode("ocelot").setValue(true); + c.node("zombie").raw(false); + c.node("villager").raw(false); + c.node("cat").raw(true); + c.node("ocelot").raw(true); }); - n.appendListNode().setValue("blue"); + n.appendListNode().raw("blue"); }); DuplicateRemovalVisitor.visit(child, parent); - assertTrue(child.isEmpty()); - assertNull(child.getValue()); + assertTrue(child.empty()); + assertNull(child.raw()); } @Test void testMapKeysClearedInList() { - final ConfigurationNode parent = ConfigurationNode.root(n -> { - n.appendListNode().setValue("one"); - n.appendListNode().setValue("two"); + final ConfigurationNode parent = BasicConfigurationNode.root(n -> { + n.appendListNode().raw("one"); + n.appendListNode().raw("two"); n.appendListNode().act(c -> { - c.getNode("zombie").setValue(false); - c.getNode("villager").setValue(false); - c.getNode("cat").setValue(true); - c.getNode("ocelot").setValue(true); + c.node("zombie").raw(false); + c.node("villager").raw(false); + c.node("cat").raw(true); + c.node("ocelot").raw(true); }); - n.appendListNode().setValue("blue"); + n.appendListNode().raw("blue"); }); - final ConfigurationNode child = ConfigurationNode.root(n -> { - n.appendListNode().setValue("one"); - n.appendListNode().setValue("two"); + final ConfigurationNode child = BasicConfigurationNode.root(n -> { + n.appendListNode().raw("one"); + n.appendListNode().raw("two"); n.appendListNode().act(c -> { - c.getNode("zombie").setValue(false); - c.getNode("villager").setValue(false); - c.getNode("cat").setValue(true); - c.getNode("ocelot").setValue(false); + c.node("zombie").raw(false); + c.node("villager").raw(false); + c.node("cat").raw(true); + c.node("ocelot").raw(false); }); - n.appendListNode().setValue("blue"); + n.appendListNode().raw("blue"); }); DuplicateRemovalVisitor.visit(child, parent); - assertEquals(4, child.getChildrenList().size()); - assertNull(child.getNode(2, "cat").getValue()); - assertEquals(false, child.getNode(2, "ocelot").getValue()); + assertEquals(4, child.childrenList().size()); + assertNull(child.node(2, "cat").raw()); + assertEquals(false, child.node(2, "ocelot").raw()); } @Test void testEmptyMapsPreservedInList() { - final ConfigurationNode parent = ConfigurationNode.root(n -> { - n.appendListNode().setValue("one"); - n.appendListNode().setValue("two"); + final ConfigurationNode parent = BasicConfigurationNode.root(n -> { + n.appendListNode().raw("one"); + n.appendListNode().raw("two"); n.appendListNode().act(c -> { - c.getNode("zombie").setValue(false); - c.getNode("villager").setValue(false); - c.getNode("cat").setValue(true); - c.getNode("ocelot").setValue(true); + c.node("zombie").raw(false); + c.node("villager").raw(false); + c.node("cat").raw(true); + c.node("ocelot").raw(true); }); - n.appendListNode().setValue("blue"); + n.appendListNode().raw("blue"); }); - final ConfigurationNode child = ConfigurationNode.root(n -> { - n.appendListNode().setValue("one"); - n.appendListNode().setValue("two"); + final ConfigurationNode child = BasicConfigurationNode.root(n -> { + n.appendListNode().raw("one"); + n.appendListNode().raw("two"); n.appendListNode().act(c -> { - c.getNode("zombie").setValue(false); - c.getNode("villager").setValue(false); - c.getNode("cat").setValue(true); - c.getNode("ocelot").setValue(true); + c.node("zombie").raw(false); + c.node("villager").raw(false); + c.node("cat").raw(true); + c.node("ocelot").raw(true); }); - n.appendListNode().setValue("green"); + n.appendListNode().raw("green"); }); DuplicateRemovalVisitor.visit(child, parent); - final ConfigurationNode expected = ConfigurationNode.root(n -> { - n.appendListNode().setValue("one"); - n.appendListNode().setValue("two"); - n.appendListNode().setValue(ImmutableMap.of()); - n.appendListNode().setValue("green"); + final ConfigurationNode expected = BasicConfigurationNode.root(n -> { + n.appendListNode().raw("one"); + n.appendListNode().raw("two"); + n.appendListNode().raw(ImmutableMap.of()); + n.appendListNode().raw("green"); }); assertEquals(expected, child); @@ -219,23 +221,23 @@ void testEmptyMapsPreservedInList() { @Test void testSpongeExample() { final ConfigurationNode parent = CommentedConfigurationNode.root(p -> { - p.getNode("sponge", "world-generation-modifiers").setValue(ImmutableList.of()).setComment("World Generation Modifiers to apply to the " + p.node("sponge", "world-generation-modifiers").raw(ImmutableList.of()).comment("World Generation Modifiers to apply to the " + "world"); - p.getNode("sponge", "player-block-tracker").act(pBT -> { - ((CommentedConfigurationNode) pBT.getNode("block-blacklist")).setValue(ImmutableList.of()).setComment("Block IDs that will be " + p.node("sponge", "player-block-tracker").act(pBT -> { + pBT.node("block-blacklist").raw(ImmutableList.of()).comment("Block IDs that will be " + "blacklisted for player block placement tracking"); - pBT.getNode("enabled").setValue(true); + pBT.node("enabled").raw(true); }); }); final ConfigurationNode child = parent.copy(); DuplicateRemovalVisitor.visit(child, parent); - assertTrue(child.isEmpty()); + assertTrue(child.empty()); } @Test void testVisitWithNullParentFails() { - assertThrows(NullPointerException.class, () -> DuplicateRemovalVisitor.visit(ConfigurationNode.root(), null)); + assertThrows(NullPointerException.class, () -> DuplicateRemovalVisitor.visit(BasicConfigurationNode.root(), null)); } } diff --git a/src/test/java/org/spongepowered/common/data/persistence/ConfigurateDataViewTest.java b/src/test/java/org/spongepowered/common/data/persistence/ConfigurateDataViewTest.java index dfc71e434b6..584c5009f37 100644 --- a/src/test/java/org/spongepowered/common/data/persistence/ConfigurateDataViewTest.java +++ b/src/test/java/org/spongepowered/common/data/persistence/ConfigurateDataViewTest.java @@ -30,9 +30,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Lists; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.ConfigurationOptions; -import ninja.leaping.configurate.commented.CommentedConfigurationNode; +import org.spongepowered.configurate.BasicConfigurationNode; +import org.spongepowered.configurate.ConfigurationNode; +import org.spongepowered.configurate.ConfigurationOptions; +import org.spongepowered.configurate.CommentedConfigurationNode; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.spongepowered.api.ResourceKey; @@ -59,20 +60,20 @@ public class ConfigurateDataViewTest { @Test void testNodeToData() { - final ConfigurationNode node = ConfigurationNode.root(); - node.getNode("foo","int").setValue(1); - node.getNode("foo", "double").setValue(10.0D); - node.getNode("foo", "long").setValue(Long.MAX_VALUE); + final ConfigurationNode node = BasicConfigurationNode.root(); + node.node("foo","int").raw(1); + node.node("foo", "double").raw(10.0D); + node.node("foo", "long").raw(Long.MAX_VALUE); final List stringList = Lists.newArrayList(); for (int i = 0; i < 100; i ++) { stringList.add("String" + i); } - node.getNode("foo", "stringList").setValue(stringList); + node.node("foo", "stringList").raw(stringList); final List dataList = new ArrayList<>(); for (int i = 0; i < 100; i++) { dataList.add(new SimpleData(i, 10.0 + i, "String" + i, Collections.emptyList())); } - node.getNode("foo", "nested", "Data").setValue(dataList); + node.node("foo", "nested", "Data").raw(dataList); final DataContainer manual = DataContainer.createNew(); manual.set(DataQuery.of("foo", "int"), 1) @@ -89,7 +90,7 @@ void testNodeToData() { @Test void testEmptyNodeToData() { - final ConfigurationNode source = ConfigurationNode.root(); + final ConfigurationNode source = BasicConfigurationNode.root(); final DataContainer container = ConfigurateTranslator.instance().translate(source); assertTrue(container.isEmpty()); } @@ -98,7 +99,7 @@ void testEmptyNodeToData() { void testEmptyDataToNode() { final DataContainer source = DataContainer.createNew(); final ConfigurationNode destination = ConfigurateTranslator.instance().translate(source); - assertTrue(destination.isEmpty()); + assertTrue(destination.empty()); } @Test @@ -106,11 +107,11 @@ void testTypesAreCoerced() { final DataContainer source = DataContainer.createNew(); source.set(DataQuery.of("i'm a short"), (short) 5); - final ConfigurationNode destination = ConfigurationNode.root(ConfigurationOptions.defaults() - .withNativeTypes(Collections.singleton(Integer.class))); + final ConfigurationNode destination = BasicConfigurationNode.root(ConfigurationOptions.defaults() + .nativeTypes(Collections.singleton(Integer.class))); ConfigurateTranslator.instance().translateDataToNode(destination, source); - assertEquals(5, destination.getNode("i'm a short").getValue()); + assertEquals(5, destination.node("i'm a short").raw()); } @Test @@ -162,7 +163,7 @@ void testNumber() throws IOException { final DataContainer container = DataContainer.createNew().set(DataQuery.of("double"), 1.0); final ConfigurationNode node = ConfigurateTranslator.instance().translate(container); - assertEquals(1.0, node.getNode("double").getValue()); + assertEquals(1.0, node.node("double").raw()); final DataContainer dc = ConfigurateTranslator.instance().translate(node); @@ -177,8 +178,8 @@ void testMapInsideList() throws IOException { final Map map = Collections.singletonMap("mkey", "mvalue"); final List list = Arrays.asList("lelement", map); - node.getNode("foo").setValue("bar"); - node.getNode("l").setValue(list); + node.node("foo").raw("bar"); + node.node("l").raw(list); final DataContainer jc = json.read("{\"foo\":\"bar\",\"l\":[\"lelement\",{\"mkey\":\"mvalue\"}]}"); final DataContainer hc = ConfigurateTranslator.instance().translate(node); @@ -189,7 +190,7 @@ void testMapInsideList() throws IOException { @Test void testNullRootKey() { assertThrows(IllegalArgumentException.class, () -> - ConfigurateTranslator.instance().translate(ConfigurationNode.root().setValue("bar"))); + ConfigurateTranslator.instance().translate(BasicConfigurationNode.root().raw("bar"))); } @Test @@ -198,8 +199,8 @@ void testNullMapKey() { final Map map = Collections.singletonMap(null, "v"); final List list = Arrays.asList("e", map); - node.getNode("foo").setValue("bar"); - node.getNode("l").setValue(list); + node.node("foo").raw("bar"); + node.node("l").raw(list); assertThrows(IllegalArgumentException.class, () -> ConfigurateTranslator.instance().translate(node)); } @@ -207,19 +208,19 @@ void testNullMapKey() { @Test void testNonRootNodeToData() { final ConfigurationNode root = CommentedConfigurationNode.root(n -> { - n.getNode("test").act(c -> { - c.getNode("child").setValue("hello"); - c.getNode("other").setValue("world"); + n.node("test").act(c -> { + c.node("child").raw("hello"); + c.node("other").raw("world"); }); }); - final DataView view = ConfigurateTranslator.instance().translate(root.getNode("test")); + final DataView view = ConfigurateTranslator.instance().translate(root.node("test")); assertEquals("hello", view.getString(DataQuery.of("child")).get()); assertEquals("world", view.getString(DataQuery.of("other")).get()); - ConfigurateTranslator.instance().translateDataToNode(root.getNode("test2"), view); - assertEquals(root.getNode("test").getValue(), root.getNode("test2").getValue()); + ConfigurateTranslator.instance().translateDataToNode(root.node("test2"), view); + assertEquals(root.node("test").raw(), root.node("test2").raw()); } } diff --git a/src/test/invalid/common/util/ReflectionTest.java b/src/test/java/org/spongepowered/common/util/ReflectionTest.java similarity index 78% rename from src/test/invalid/common/util/ReflectionTest.java rename to src/test/java/org/spongepowered/common/util/ReflectionTest.java index 3f093d93681..54f54cafe7d 100644 --- a/src/test/invalid/common/util/ReflectionTest.java +++ b/src/test/java/org/spongepowered/common/util/ReflectionTest.java @@ -24,19 +24,21 @@ */ package org.spongepowered.common.util; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.spongepowered.common.util.ReflectionUtil.createInstance; import static org.spongepowered.common.util.ReflectionUtil.findConstructor; -import com.google.common.reflect.TypeToken; -import org.junit.Test; +import io.leangen.geantyref.TypeToken; +import org.junit.jupiter.api.Test; import org.spongepowered.api.data.DataHolder; -import org.spongepowered.api.data.DataQuery; -import org.spongepowered.api.data.key.Key; -import org.spongepowered.api.data.value.immutable.ImmutableValue; -import org.spongepowered.api.data.value.mutable.Value; +import org.spongepowered.api.data.Key; +import org.spongepowered.api.data.persistence.DataQuery; +import org.spongepowered.api.data.value.Value; import org.spongepowered.api.event.EventListener; import org.spongepowered.api.event.data.ChangeDataHolderEvent; -import org.spongepowered.common.data.value.immutable.ImmutableSpongeValue; +import org.spongepowered.common.data.value.ImmutableSpongeValue; + +import java.lang.reflect.Type; public class ReflectionTest { @@ -47,14 +49,14 @@ public void testFindConstructor() { createInstance(Dummy.class, "dance"); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalArgs() { - findConstructor(Dummy.class); + assertThrows(IllegalArgumentException.class, () -> findConstructor(Dummy.class)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalArgs2() { - findConstructor(Dummy.class, "break", "dance"); + assertThrows(IllegalArgumentException.class, () -> findConstructor(Dummy.class, "break", "dance")); } @Test @@ -68,18 +70,18 @@ public void testNulls() { createInstance(Dummy.class, (Object) null); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalNullCtor() { - findConstructor(Complex.class, null, null, null, null); + assertThrows(IllegalArgumentException.class, () -> findConstructor(Complex.class, null, null, null, null)); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalNulls() { // This is valid to the compiler, but for java, // primitives can never be null, they're always a default value of 0 or false. // So, in this case, the runtime will throw an IllegalArgumentException when // the constructor tries to construct a new instance! - createInstance(Complex.class, null, null, null, null); + assertThrows(IllegalArgumentException.class, () -> createInstance(Complex.class, null, null, null, null)); } @Test @@ -93,7 +95,7 @@ public void testNoArgs() { createInstance(NoArgs.class); } - @Test + /* @Test public void testImmutableValueCache() { final Key> key = new Key>() { @@ -116,13 +118,13 @@ public String getName() { } @Override - public TypeToken> getValueToken() { + public Type getValueType() { return this.token; } @Override - public TypeToken getElementToken() { - return this.type; + public Type getElementType() { + return Double.class; } @Override @@ -136,26 +138,26 @@ public void registerEvent(Class holderFilter, EventLis } }; - final ImmutableValue myVal = ImmutableSpongeValue.cachedOf(key, 10D, 1D); + final ImmutableValue myVal = ImmutableSpongeValue.cached(key, 10D, 1D); final ImmutableValue testVal = ImmutableSpongeValue.cachedOf(key, 10D, 1d); assert myVal == testVal; - } + } */ public static final class Complex { - public Complex(int start, String dancing) { + public Complex(final int start, final String dancing) { } - public Complex(int start, String dancing, Object lol, boolean test) { + public Complex(final int start, final String dancing, final Object lol, final boolean test) { } } public static final class Dummy { - public Dummy(Object object) { + public Dummy(final Object object) { } } diff --git a/src/test/java/org/spongepowered/common/util/TypeTokenHelperTest.java b/src/test/java/org/spongepowered/common/util/TypeTokenHelperTest.java new file mode 100644 index 00000000000..8796b29ce1a --- /dev/null +++ b/src/test/java/org/spongepowered/common/util/TypeTokenHelperTest.java @@ -0,0 +1,164 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * 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. + */ +package org.spongepowered.common.util; + + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import io.leangen.geantyref.TypeToken; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.spongepowered.api.CatalogType; +import org.spongepowered.api.advancement.Advancement; +import org.spongepowered.api.data.DataRegistration; +import org.spongepowered.api.data.Key; +import org.spongepowered.api.data.value.Value; +import org.spongepowered.api.entity.living.Living; +import org.spongepowered.api.entity.living.monster.boss.dragon.EnderDragon; +import org.spongepowered.api.entity.living.monster.slime.Slime; +import org.spongepowered.common.data.value.SpongeValue; + +public final class TypeTokenHelperTest { + + @SuppressWarnings("rawtypes") + @Test + @Disabled + public void testA() { + assertTrue(TypeTokenHelper.isAssignable( + new TypeToken>>() {}, + new TypeToken>>() {})); + + assertTrue(TypeTokenHelper.isAssignable( + new TypeToken>() {}, + new TypeToken>>() {})); + + assertFalse(TypeTokenHelper.isAssignable( + new TypeToken>>() {}, + new TypeToken>>() {})); + + assertFalse(TypeTokenHelper.isAssignable( + new TypeToken>>() {}, + new TypeToken>>() {})); + + assertFalse(TypeTokenHelper.isAssignable( + new TypeToken>>() {}, + new TypeToken>>() {})); + + assertFalse(TypeTokenHelper.isAssignable( + new TypeToken>>() {}, + new TypeToken>>() {})); + + assertFalse(TypeTokenHelper.isAssignable( + new TypeToken>>() {}, + new TypeToken>>() {})); + + assertTrue(TypeTokenHelper.isAssignable( + new TypeToken>>() {}, + new TypeToken>>() {})); + + assertTrue(TypeTokenHelper.isAssignable( + new TypeToken>>() {}, + new TypeToken>>() {})); + + assertTrue(TypeTokenHelper.isAssignable( + new TypeToken>>() {}, + TypeToken.get(Key.class))); + + assertFalse(TypeTokenHelper.isAssignable( + TypeToken.get(Key.class), + new TypeToken>>() {})); + + // TODO + /*assertTrue(TypeTokenHelper.isAssignable( + new TypeToken() {}, + new TypeToken>() {})); + + assertFalse(TypeTokenHelper.isAssignable( + TypeToken.get(DataRegistration.class), + new TypeToken>() {})); + + assertFalse(TypeTokenHelper.isAssignable( + new TypeToken() {}, + new TypeToken>() {})); + + assertFalse(TypeTokenHelper.isAssignable( + new TypeToken>() {}, + new TypeToken>() {})); + + assertTrue(TypeTokenHelper.isAssignable( + new TypeToken>() {}, + new TypeToken>() {}));*/ + } + + @Test + public void testB() { + // Enclosing classes testing + + assertTrue(TypeTokenHelper.isAssignable( + new TypeToken.B>>() {}, + new TypeToken.B>>() {})); + + assertFalse(TypeTokenHelper.isAssignable( + new TypeToken>>.B>>() {}, + new TypeToken>>.B>>() {})); + + assertTrue(TypeTokenHelper.isAssignable( + new TypeToken>>.B>>() {}, + new TypeToken>>.B>>() {})); + } + + @Test + public void testC() { + assertFalse(TypeTokenHelper.isAssignable( + new TypeToken>() {}, + new TypeToken>() {})); + + assertTrue(TypeTokenHelper.isAssignable( + new TypeToken>() {}, + new TypeToken>() {})); + + assertTrue(TypeTokenHelper.isAssignable( + new TypeToken() {}, + new TypeToken>() {})); + + assertTrue(TypeTokenHelper.isAssignable( + new TypeToken() {}, + new TypeToken>() {})); + + assertFalse(TypeTokenHelper.isAssignable( + new TypeToken>() {}, + new TypeToken() {})); + } + + private static class D extends A {} + + private static class C extends A {} + + private static class A { + + private class B {} + } +} diff --git a/testplugins/src/main/java/org/spongepowered/test/commandtest/CommandTestPlugin.java b/testplugins/src/main/java/org/spongepowered/test/commandtest/CommandTestPlugin.java index 157247fc232..7d447b96401 100644 --- a/testplugins/src/main/java/org/spongepowered/test/commandtest/CommandTestPlugin.java +++ b/testplugins/src/main/java/org/spongepowered/test/commandtest/CommandTestPlugin.java @@ -25,7 +25,7 @@ package org.spongepowered.test.commandtest; import com.google.common.collect.ImmutableList; -import com.google.common.reflect.TypeToken; +import io.leangen.geantyref.TypeToken; import com.google.inject.Inject; import net.kyori.adventure.identity.Identity; import net.kyori.adventure.text.Component; @@ -116,8 +116,8 @@ public void onRegisterSpongeCommand(final RegisterCommandEvent testKey = Parameter.key("testKey", TypeToken.of(String.class)); - final Parameter.Key requiredKey = Parameter.key("requiredKey", TypeToken.of(Component.class)); + final Parameter.Key testKey = Parameter.key("testKey", String.class); + final Parameter.Key requiredKey = Parameter.key("requiredKey", Component.class); event.register( this.plugin, Command.builder() @@ -169,7 +169,7 @@ public void onRegisterSpongeCommand(final RegisterCommandEvent serverLocationKey = Parameter.key("serverLocation", TypeToken.of(ServerLocation.class)); + final Parameter.Key serverLocationKey = Parameter.key("serverLocation", ServerLocation.class); final Parameter.Value serverLocationParmeter = Parameter.location().setKey(serverLocationKey).build(); event.register( this.plugin, @@ -202,8 +202,8 @@ public void onRegisterSpongeCommand(final RegisterCommandEvent enumParameterKey = Parameter.key("enum", TypeToken.of(TestEnum.class)); - final Parameter.Key stringKey = Parameter.key("stringKey", TypeToken.of(String.class)); + final Parameter.Key enumParameterKey = Parameter.key("enum", TestEnum.class); + final Parameter.Key stringKey = Parameter.key("stringKey", String.class); event.register( this.plugin, Command.builder() @@ -218,7 +218,7 @@ public void onRegisterSpongeCommand(final RegisterCommandEvent resourceKeyKey = Parameter.key("rk", TypeToken.of(ResourceKey.class)); + final Parameter.Key resourceKeyKey = Parameter.key("rk", ResourceKey.class); event.register( this.plugin, Command.builder() @@ -231,7 +231,7 @@ public void onRegisterSpongeCommand(final RegisterCommandEvent userKey = Parameter.key("user", TypeToken.of(User.class)); + final Parameter.Key userKey = Parameter.key("user", User.class); event.register( this.plugin, Command.builder() @@ -244,7 +244,7 @@ public void onRegisterSpongeCommand(final RegisterCommandEvent stringLiteralKey = Parameter.key("literal", TypeToken.of(String.class)); + final Parameter.Key stringLiteralKey = Parameter.key("literal", String.class); event.register( this.plugin, Command.builder() diff --git a/testplugins/src/main/java/org/spongepowered/test/configtest/ConfigTest.java b/testplugins/src/main/java/org/spongepowered/test/configtest/ConfigTest.java index f8b88204b16..21fdeb6326b 100644 --- a/testplugins/src/main/java/org/spongepowered/test/configtest/ConfigTest.java +++ b/testplugins/src/main/java/org/spongepowered/test/configtest/ConfigTest.java @@ -24,54 +24,48 @@ */ package org.spongepowered.test.configtest; -import com.google.common.reflect.TypeToken; import com.google.inject.Inject; import net.kyori.adventure.identity.Identity; import net.kyori.adventure.text.Component; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.commented.CommentedConfigurationNode; -import ninja.leaping.configurate.loader.ConfigurationLoader; -import ninja.leaping.configurate.objectmapping.ObjectMappingException; +import org.spongepowered.configurate.ConfigurateException; +import org.spongepowered.configurate.CommentedConfigurationNode; import org.apache.logging.log4j.Logger; import org.spongepowered.api.command.parameter.CommandContext; import org.spongepowered.api.config.DefaultConfig; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.lifecycle.ConstructPluginEvent; import org.spongepowered.api.event.network.ServerSideConnectionEvent; +import org.spongepowered.configurate.reference.ConfigurationReference; +import org.spongepowered.configurate.reference.ValueReference; import org.spongepowered.plugin.jvm.Plugin; import org.spongepowered.test.LoadableModule; -import java.io.IOException; - @Plugin("configtest") public class ConfigTest implements LoadableModule { private final Logger logger; - private final ConfigurationLoader loader; - private ConfigurationNode node; - private ExampleConfiguration config; + private final ConfigurationReference reference; + private ValueReference config; @Inject - ConfigTest(final Logger logger, final @DefaultConfig(sharedRoot = true) ConfigurationLoader loader) { + ConfigTest(final Logger logger, final @DefaultConfig(sharedRoot = true) ConfigurationReference reference) { this.logger = logger; - this.loader = loader; + this.reference = reference; } @Listener public void onConstruction(final ConstructPluginEvent event) { try { - this.node = this.loader.load(); - this.config = this.node.getValue(TypeToken.of(ExampleConfiguration.class), new ExampleConfiguration()); - this.node.setValue(TypeToken.of(ExampleConfiguration.class), this.config); - this.loader.save(node); - } catch (IOException | ObjectMappingException e) { - this.logger.error("Unable to load test configuration", e); + this.config = this.reference.referenceTo(ExampleConfiguration.class); + this.reference.save(); + } catch (final ConfigurateException ex) { + this.logger.error("Unable to load test configuration", ex); } } @Listener public void clientConnected(final ServerSideConnectionEvent.Join event) { - final Component motd = this.config.getMotd(); + final Component motd = this.config.get().getMotd(); if (motd == null || motd == Component.empty()) { return; } diff --git a/testplugins/src/main/java/org/spongepowered/test/configtest/ExampleConfiguration.java b/testplugins/src/main/java/org/spongepowered/test/configtest/ExampleConfiguration.java index f94d99c9bf9..7e78a54c134 100644 --- a/testplugins/src/main/java/org/spongepowered/test/configtest/ExampleConfiguration.java +++ b/testplugins/src/main/java/org/spongepowered/test/configtest/ExampleConfiguration.java @@ -26,8 +26,8 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import ninja.leaping.configurate.objectmapping.Setting; -import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Setting; @ConfigSerializable public class ExampleConfiguration { diff --git a/testplugins/src/main/java/org/spongepowered/test/customdatatest/CustomDataTest.java b/testplugins/src/main/java/org/spongepowered/test/customdatatest/CustomDataTest.java index 4c04107c0ff..e56825871ed 100644 --- a/testplugins/src/main/java/org/spongepowered/test/customdatatest/CustomDataTest.java +++ b/testplugins/src/main/java/org/spongepowered/test/customdatatest/CustomDataTest.java @@ -24,33 +24,31 @@ */ package org.spongepowered.test.customdatatest; -import com.google.common.reflect.TypeToken; import com.google.inject.Inject; import net.kyori.adventure.text.Component; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.Sponge; -import org.spongepowered.api.adventure.SpongeComponents; import org.spongepowered.api.block.BlockTypes; import org.spongepowered.api.block.entity.BlockEntity; import org.spongepowered.api.command.Command; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.parameter.Parameter; -import org.spongepowered.api.data.DataHolder; import org.spongepowered.api.data.DataProvider; import org.spongepowered.api.data.DataRegistration; import org.spongepowered.api.data.DataTransactionResult; import org.spongepowered.api.data.Key; -import org.spongepowered.api.data.MutableDataProviderBuilder; import org.spongepowered.api.data.persistence.DataStore; import org.spongepowered.api.data.value.Value; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.EntityTypes; +import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.entity.living.player.User; import org.spongepowered.api.entity.living.player.server.ServerPlayer; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.lifecycle.RegisterCatalogEvent; import org.spongepowered.api.event.lifecycle.RegisterCommandEvent; import org.spongepowered.api.event.network.ServerSideConnectionEvent; +import org.spongepowered.api.item.ItemType; import org.spongepowered.api.item.ItemTypes; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.item.inventory.Slot; @@ -151,15 +149,15 @@ public void onRegisterSpongeCommand(final RegisterCommandEvent event) { - this.myKey = Key.builder().key(ResourceKey.of(this.plugin, "mydata")).type(TypeTokens.INTEGER_VALUE_TOKEN).build(); + this.myKey = Key.builder().key(ResourceKey.of(this.plugin, "mydata")).elementType(Integer.class).build(); final DataProvider, Integer> blockDataProvider = DataProvider.mutableBuilder() - .key(this.myKey).dataHolder(TypeTokens.SERVER_LOCATION_TOKEN) + .key(this.myKey).dataHolder(ServerLocation.class) .get(this::getData).set(this::setData).delete(this::removeData) .build(); final DataStore dataStore = DataStore.builder().key(this.myKey, "mykey") - .holder(TypeTokens.ITEM_TYPE_TOKEN, TypeTokens.USER_TOKEN, TypeTokens.PLAYER_TOKEN) + .holder(ItemType.class, User.class, Player.class) .build(); final DataRegistration myRegistration = DataRegistration.builder() diff --git a/vanilla/src/applaunch/java/org/spongepowered/vanilla/applaunch/handler/AbstractVanillaLaunchHandler.java b/vanilla/src/applaunch/java/org/spongepowered/vanilla/applaunch/handler/AbstractVanillaLaunchHandler.java index 1dee7766fdd..6be0bfa8971 100644 --- a/vanilla/src/applaunch/java/org/spongepowered/vanilla/applaunch/handler/AbstractVanillaLaunchHandler.java +++ b/vanilla/src/applaunch/java/org/spongepowered/vanilla/applaunch/handler/AbstractVanillaLaunchHandler.java @@ -72,14 +72,18 @@ public abstract class AbstractVanillaLaunchHandler implements ILaunchHandlerServ "org.spongepowered.plugin.", "org.spongepowered.common.applaunch.", "org.spongepowered.vanilla.applaunch.", - // configurate 3 - "com.google.common.reflect.TypeToken", - "ninja.leaping.configurate.", - // configurate 4 (coming soon) + // configurate 4 "io.leangen.geantyref.", "org.spongepowered.configurate." ); + /** + * Exceptions to the exclusions, because we've reached that point in life. + */ + protected static final List EXCLUDED_EXCEPTIONS = Arrays.asList( + "org.spongepowered.configurate.objectmapping.guice." + ); + @Override public void configureTransformationClassLoader(final ITransformingClassLoaderBuilder builder) { builder.setClassBytesLocator(this.getResourceLocator()); @@ -90,8 +94,15 @@ public Callable launchService(final String[] arguments, final ITransformin this.logger.info("Transitioning to Sponge launcher, please wait..."); launchClassLoader.addTargetPackageFilter(klass -> { - for (final String pkg : EXCLUDED_PACKAGES) { - if (klass.startsWith(pkg)) return false; + exclusions: for (final String pkg : EXCLUDED_PACKAGES) { + if (klass.startsWith(pkg)) { + for (final String bypass : EXCLUDED_EXCEPTIONS) { + if (klass.startsWith(bypass)) { + continue exclusions; + } + } + return false; + } } return true; });