Code Monkey home page Code Monkey logo

okaeri-configs's People

Contributors

dasavick avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

okaeri-configs's Issues

Empty string is added each time the configuration is loaded.

Describe the bug
New lines adds every time config loaded.

To Reproduce

TestConfig testConfig = ConfigManager.create(TestConfig.class, (it) -> {
            it.withConfigurer(new YamlBukkitConfigurer(SectionSeparator.NEW_LINE), new SerdesBukkit());
            it.withBindFile(getDataFolder().toPath().resolve("settings.yml"));
            it.withRemoveOrphans(true);
            it.saveDefaults();
            it.load(true);
        });

Each loading config will add extra empty line after header.

Expected behavior
Line shouldn't be added if already exists.

Library version

    implementation 'eu.okaeri:okaeri-configs-yaml-bukkit:4.0.6'
    implementation 'eu.okaeri:okaeri-configs-serdes-commons:4.0.6'
    implementation 'eu.okaeri:okaeri-configs-serdes-bukkit:4.0.6'

OkaeriConfig.save method will clear file of content if errors to simplify any object

using
implementation 'eu.okaeri:okaeri-configs-yaml-bukkit:5.0.0-beta.5'
implementation 'eu.okaeri:okaeri-configs-serdes-bukkit:5.0.0-beta.5'
bukkit
severity: medium

Describe the bug
i have
https://paste.md-5.net/ihowenijat.java
as you can see theres a few values and a NPCManager, ConifgNPC, those have no ObjectSerializer registered

im using
https://paste.md-5.net/ecawikikat.cs
for testing of file loading

the method it.load is not the issue, it.save is what clears the file

the method
eu.okaeri.configs.configurer.Configurer;simplify()
will
throw new OkaeriException("cannot simplify type " + serializerType + " (" + genericType + "): '" + value + "' [" + value.getClass() + "]");
if no serializer is found for the object, but this will brake the for loop
https://paste.md-5.net/quyunoxucu.coffeescript
found in the save method

im not sure why in the
return this.save(new PrintStream(new FileOutputStream(file, false), true, StandardCharsets.UTF_8.name()));
the autoFlush is not flushing the first few values

To Reproduce
create class with no objectSerializer and let it run
call load then save, or it.load(true)

Expected behavior
avoid value or add all but that one
whatever happens, not clearing the entire config file would be great otherwise theres a need for constant backups

Library version
implementation 'eu.okaeri:okaeri-configs-yaml-bukkit:5.0.0-beta.5'
implementation 'eu.okaeri:okaeri-configs-serdes-bukkit:5.0.0-beta.5'
i only use bukkit

Config classes and setup routine
already added

fix:
as seen in the video if instead of throwing we return null the value is ignored, the error is printed to console and the file doesnt get reset
https://vimeo.com/936353158?share=copy

other:
here are a few notes iv made while debugging this
https://paste.md-5.net/zaxukusono.cs

if you need more info feel free to dm me in discord .paradis

Screenshot_27
Screenshot_26
Screenshot_28

Support for `.properties` file

Is your feature request related to a problem? Please describe.
Nope

Describe the solution you'd like
Wsparcie dla plików properties z komentarzami

Describe alternatives you've considered
To co napisałem u góry

Additional context
e

System do migracji / wprowadzania zmian w konfiguracji

Propozycja dodania adnotacji @Migrate

Działanie
Adnotacja umożliwiłaby migracje pól np. ze starych systemów do zarządzania konfiguracją do nowych lub pozwoliłaby na zmianę lokalizacji pola. Jak by to miało wyglądać? Mamy przypadek, gdzie wartość trzymana jest pod kluczem np. new_key więc plik jak jest ładowany to po nim szuka. Jeśli damy w takim przypadku do załadowania stary plik gdzie ta sama wartość była trzymana pod kluczem np. old_key to jej nie znajdzie. Adnotacja Migrate miałaby działać na takiej zasadzie, że jeśli przy ładowaniu nie znajdzie nigdzie wartości w configu pod nowym (aktualnym) kluczem to spróbuje ją znaleźć po starym kluczu z adnotacji Migrate. Dodatkowo jeśli znajdzie wartość pod starym kluczem to się pozbędzie się starego pola z pliku i przypisze jego wartość nowemu kluczowi.

config.yml (wersja 1):

old_key: value

config.yml (wersja 2):

new_key: value

Configuration.java

public class Configuration extends OkaeriConfig {

  @Migrate("old_key")
  @CustomKey("new_key")
  public String value = "Lorem ipsum";

}

Nie jestem pewien czy wszystko dobrze opisałem ale mam nadzieje, że tak.

Comments inside subconfigs from collections and maps don't work

Describe the bug

Created yaml file doesn't have comments on the field with subconfigs.
Here is the code example:

 // That's field in OkaeriConfig with Map of subconfigs (another OkaeriConfig impl.)
 private Map<String, ChatNotificationChannelConfig> channels = new LinkedHashMap<String, ChatNotificationChannelConfig>() {{
    put("default", new ChatNotificationChannelConfig());
    put("donate", new ChatNotificationChannelConfig(
       30,
       Lists.newArrayList("some message"),
       false,
       false
    ));
 }};

 @Getter
 @AllArgsConstructor
 @NoArgsConstructor
 @SuppressWarnings("FieldMayBeFinal")
 @Names(strategy = NameStrategy.HYPHEN_CASE, modifier = NameModifier.TO_LOWER_CASE)
 public static class ChatNotificationChannelConfig extends OkaeriConfig {

    @Comment("Time in seconds for periodically broadcasting")
    private int time = 60;

    @Comment
    @Comment({"line1", "line2"})
    private List<String> messages = Lists.newArrayList(
     "&8===================================\n" +
     "text\n" +
     "&8==================================="
    );

    @Comment
    @Comment("Enable this, if you want to restrict channel by permission")
    private boolean permissionRequired = false;

    @Comment
    @Comment("Enable this, if you want messages to be sent randomly")
    private boolean randomOrder = false;

 }

Config is loaded with:

ConfigManager.create(configClass, config -> {
    config.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(), true), new SerdesCommons(), new SerdesBukkit());
    config.withBindFile(dataFolderPath.resolve(fileName));
    config.withRemoveOrphans(true);
    config.saveDefaults();
    config.load(true);
});

The final yaml file looks like this (there are no comments):

chat:
  enable: true
  channels:
    default:
      time: 60
      messages:
      - |-
        &8===================================
        text
        &8===================================
      permission-required: false
      random-order: false
    donate:
      time: 30
      messages:
      - some message
      permission-required: false
      random-order: false

Add friendly exception messages for errors

When the exception is raised, for example from the inside of the okaeri-configs converters, it should be possible to make the exception more user-friendly, at least for the most popular cases.

The user-friendly format of the new exceptions is yet to be determined. Suggestions are welcome.

For me, the end-game format would be inspired by the rust errors, but adding support for each backend may be tricky. I'm okay with making the message itself more friendly for all backends, and form only for YAML.

new_errors2

Example of the current unfriendly stacktrace:

  • field: int number;
  • value: 0.1
[22:59:51 WARN]: eu.okaeri.configs.exception.OkaeriException: failed to #getValue for number
[22:59:51 WARN]:     at SpigotTemplate-1.0.0.jar//eu.okaeri.configs.OkaeriConfig.update(OkaeriConfig.java:649)
[22:59:51 WARN]:     at SpigotTemplate-1.0.0.jar//eu.okaeri.configs.OkaeriConfig.load(OkaeriConfig.java:469)
[22:59:51 WARN]:     at SpigotTemplate-1.0.0.jar//eu.okaeri.configs.OkaeriConfig.load(OkaeriConfig.java:491)
[22:59:51 WARN]:     at SpigotTemplate-1.0.0.jar//eu.okaeri.configs.OkaeriConfig.load(OkaeriConfig.java:505)
[22:59:51 WARN]:     at SpigotTemplate-1.0.0.jar//eu.okaeri.configs.OkaeriConfig.load(OkaeriConfig.java:479)
[22:59:51 WARN]:     at SpigotTemplate-1.0.0.jar//eu.okaeri.configs.OkaeriConfig.load(OkaeriConfig.java:426)
[22:59:51 WARN]:     at SpigotTemplate-1.0.0.jar//dev.bloedarend.spigottemplate.plugin.managers.ConfigManager$Companion.registerConfig(ConfigManager.kt:43)
[22:59:51 WARN]:     at SpigotTemplate-1.0.0.jar//dev.bloedarend.spigottemplate.plugin.managers.ConfigManager$Companion.registerConfigs(ConfigManager.kt:26)
[22:59:51 WARN]:     at SpigotTemplate-1.0.0.jar//dev.bloedarend.spigottemplate.plugin.Main.onEnable(Main.kt:25)
[22:59:51 WARN]:     at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:264)
[22:59:51 WARN]:     at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:370)
[22:59:51 WARN]:     at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:542)
[22:59:51 WARN]:     at org.bukkit.craftbukkit.v1_19_R1.CraftServer.enablePlugin(CraftServer.java:565)
[22:59:51 WARN]:     at org.bukkit.craftbukkit.v1_19_R1.CraftServer.enablePlugins(CraftServer.java:479)
[22:59:51 WARN]:     at net.minecraft.server.MinecraftServer.loadWorld0(MinecraftServer.java:636)
[22:59:51 WARN]:     at net.minecraft.server.MinecraftServer.loadLevel(MinecraftServer.java:422)
[22:59:51 WARN]:     at net.minecraft.server.dedicated.DedicatedServer.e(DedicatedServer.java:306)
[22:59:51 WARN]:     at net.minecraft.server.MinecraftServer.v(MinecraftServer.java:1100)
[22:59:51 WARN]:     at net.minecraft.server.MinecraftServer.lambda$spin$0(MinecraftServer.java:305)
[22:59:51 WARN]:     at java.base/java.lang.Thread.run(Thread.java:833)
[22:59:51 WARN]: Caused by: java.lang.ArithmeticException: Rounding necessary
[22:59:51 WARN]:     at java.base/java.math.BigDecimal.longValueExact(BigDecimal.java:3630)
[22:59:51 WARN]:     at java.base/java.math.BigDecimal.intValueExact(BigDecimal.java:3696)
[22:59:51 WARN]:     at SpigotTemplate-1.0.0.jar//eu.okaeri.configs.serdes.standard.StringToIntegerTransformer.transform(StringToIntegerTransformer.java:19)
[22:59:51 WARN]:     at SpigotTemplate-1.0.0.jar//eu.okaeri.configs.serdes.standard.StringToIntegerTransformer.transform(StringToIntegerTransformer.java:10)
[22:59:51 WARN]:     at SpigotTemplate-1.0.0.jar//eu.okaeri.configs.configurer.Configurer.resolveType(Configurer.java:399)
[22:59:51 WARN]:     at SpigotTemplate-1.0.0.jar//eu.okaeri.configs.yaml.bukkit.YamlBukkitConfigurer.resolveType(YamlBukkitConfigurer.java:61)
[22:59:51 WARN]:     at SpigotTemplate-1.0.0.jar//eu.okaeri.configs.configurer.Configurer.resolveType(Configurer.java:334)
[22:59:51 WARN]:     at SpigotTemplate-1.0.0.jar//eu.okaeri.configs.yaml.bukkit.YamlBukkitConfigurer.resolveType(YamlBukkitConfigurer.java:61)
[22:59:51 WARN]:     at SpigotTemplate-1.0.0.jar//eu.okaeri.configs.configurer.Configurer.getValue(Configurer.java:210)
[22:59:51 WARN]:     at SpigotTemplate-1.0.0.jar//eu.okaeri.configs.OkaeriConfig.update(OkaeriConfig.java:647)
[22:59:51 WARN]:     ... 19 more

Problem z mapą objektów z rozserzeniem OkaeriConfigs

java.lang.NullPointerException: Cannot invoke "java.util.Map.put(Object, Object)" because "this.this$0.flags" is null
	at pl.minecodes.mineplots.data.configuration.PlotsConfiguration$1.<init>(PlotsConfiguration.java:50) ~[?:?]
	at pl.minecodes.mineplots.data.configuration.PlotsConfiguration.<init>(PlotsConfiguration.java:48) ~[?:?]
	at jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:?]
	at jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:78) ~[?:?]
	at jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[?:?]
	at java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499) ~[?:?]
	at java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:128) ~[?:?]
	at jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:350) ~[?:?]
	at java.lang.Class.newInstance(Class.java:642) ~[?:?]
	at pl.minecodes.mineplots.data.okaeriConfigsConfigManager.create(okaeriConfigsConfigManager.java:23) ~[?:?]
	at pl.minecodes.mineplots.data.okaeriConfigsConfigManager.create(okaeriConfigsConfigManager.java:50) ~[?:?]
	at pl.minecodes.mineplots.Plots.onEnable(Plots.java:19) ~[?:?]
	at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:263) ~[patched_1.17.jar:git-Paper-74]
	at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:370) ~[patched_1.17.jar:git-Paper-74]
	at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:500) ~[patched_1.17.jar:git-Paper-74]
	at org.bukkit.craftbukkit.v1_17_R1.CraftServer.enablePlugin(CraftServer.java:518) ~[patched_1.17.jar:git-Paper-74]
	at org.bukkit.craftbukkit.v1_17_R1.CraftServer.enablePlugins(CraftServer.java:432) ~[patched_1.17.jar:git-Paper-74]
	at org.bukkit.craftbukkit.v1_17_R1.CraftServer.reload(CraftServer.java:957) ~[patched_1.17.jar:git-Paper-74]
	at org.bukkit.Bukkit.reload(Bukkit.java:769) ~[patched_1.17.jar:git-Paper-74]
	at org.bukkit.command.defaults.ReloadCommand.execute(ReloadCommand.java:54) ~[patched_1.17.jar:git-Paper-74]
	at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:159) ~[patched_1.17.jar:git-Paper-74]
	at org.bukkit.craftbukkit.v1_17_R1.CraftServer.dispatchCommand(CraftServer.java:821) ~[patched_1.17.jar:git-Paper-74]
	at org.bukkit.craftbukkit.v1_17_R1.CraftServer.dispatchServerCommand(CraftServer.java:784) ~[patched_1.17.jar:git-Paper-74]
	at net.minecraft.server.dedicated.DedicatedServer.handleConsoleInputs(DedicatedServer.java:516) ~[patched_1.17.jar:git-Paper-74]
	at net.minecraft.server.dedicated.DedicatedServer.tickChildren(DedicatedServer.java:478) ~[patched_1.17.jar:git-Paper-74]
	at net.minecraft.server.MinecraftServer.tickServer(MinecraftServer.java:1404) ~[patched_1.17.jar:git-Paper-74]
	at net.minecraft.server.MinecraftServer.runServer(MinecraftServer.java:1180) ~[patched_1.17.jar:git-Paper-74]
	at net.minecraft.server.MinecraftServer.lambda$spin$0(MinecraftServer.java:320) ~[patched_1.17.jar:git-Paper-74]
	at java.lang.Thread.run(Thread.java:831) [?:?]

Support for snakeyaml platform

  • there is currently no independent library for YAML configs
  • yaml-snakeyaml allows YAML configs on Sponge/Velocity (Minecraft) platforms, snakeyaml is available there due to Configurate

No comments for all options

Describe the bug
No comments for all configuration options.
To Reproduce
No errors in logs.

Library version
3.4.2

Config classes and setup routine

Configuration class
@Data
@EqualsAndHashCode(callSuper = false)
@Names(strategy = NameStrategy.HYPHEN_CASE, modifier = NameModifier.TO_LOWER_CASE)
public class LocaleMessages extends OkaeriConfig {

    @Exclude
    private MiniMessage miniMessage = MiniMessage.miniMessage();

    @Comment({
            "PL: Gdy użytkownik nie posiada uprawnień do komendy.",
            "EN: "
    })
    private Component dontHavePermission = this.miniMessage.parse("<red>You are not permitted to perform this command! <dark_gray>(<yellow>{permission}<dark_gray>)");

    @Comment({
            "PL: Gdy użytkownik nie istnieje w bazie danych.",
            "EN: "
    })
    private Component userDoesNotExist = this.miniMessage.parse("<red>User does not exist in the database.");

    @Comment({
            "PL: Gdy plugin wykryje konto premium w niedozwolonej akcji dla tego typu konta.",
            "EN: "
    })
    private Component premiumAccountDetected = this.miniMessage.parse("<red>Premium account detected!");

    @Comment({
            "PL: Gdy plugin wykryje konto cracked w niedozwolonej akcji dla tego typu konta.",
            "EN: "
    })
    private Component crackedAccountDetected = this.miniMessage.parse("<red>Cracked account detected!");
   
...
CofnigManager configuration
        return ConfigManager.create(clazz, it -> it
                .withConfigurer(new YamlBungeeConfigurer("#", SectionSeparator.NEW_LINE), registry -> {
                    registry.register(new StringToComponentTransformer());
                })
                .withBindFile(file)
                .saveDefaults()
                .load(true)
        );

image

Give access to root object in serializer

I'd like to access root object in serializer. I'll give an exmaple:

I have object... For eg. ComplexMessage that contains ChatMessage & ActionbarMessage . In normal serializer I would serialize it to something like that:

message:
  chat: "Chat message"
  actionbar: "Actionbar message"

which is fine when I have 2 messages types used

But when I have only 1 message type (for eg. chat) I ends up with

message:
  chat: "Chat message"

but I wants it's to be simpler - and serialize it as String:

message: "Chat message"

YamlSnakeYamlConfigurer isn't compatible with latest versions of snakeyaml

Describe the bug
Because of use of deprecated constructor in YamlSnakeYamlConfigurer, it fails to run with latest version of snakeyaml, as deprecated constructors were removed in newer versions.

To Reproduce
Steps to reproduce the behavior:

  1. Create project with use of okaeri-configs-yaml-snakeyaml
  2. Exclude default snakeyaml library
  3. Include latest snakeyaml library
  4. Attempt to create any configuration

Expected behavior
Running without throwing exception, caused by missing constructor.

Library version
5.0.0-beta.4

Stacktrace

Exception in thread "main" java.lang.NoSuchMethodError: org.yaml.snakeyaml.constructor.Constructor: method 'void <init>()' not found
        at eu.okaeri.configs.yaml.snakeyaml.YamlSnakeYamlConfigurer.<init>(YamlSnakeYamlConfigurer.java:44)

Access to the parent Map in the ObjectSerializer

How can I access the key of a Map<String, Object> when serializing a custom object?

I have a Channel object where I want to map the key of the map to the identifier of the channel. How can I do this?

    @Override
    public boolean supports(final @NonNull Class<? super Channel> type) {
        return Channel.class.isAssignableFrom(type);
    }

    @Override
    public void serialize(final @NonNull Channel object, final @NonNull SerializationData data) {
        data.add("id", object.uuid());
        data.add("identifier", object.identifier()); // <--- set the identifier as the Map.key instead
        data.add("name", object.displayName());
        data.add("format", Objects.requireNonNullElse(object.format(), Channel.DEFAULT_CHANNEL_MESSAGE_FORMAT).getOrNull(Format.MINI_MESSAGE_TEMPLATE));

        for (final Setting<?> setting : object.settings().settings()) {
            data.add(setting.key().asString(), object.getOrNull(setting));
        }
    }

    @Override
    public Channel deserialize(final @NonNull DeserializationData data, final @NonNull GenericsDeclaration generics) {
        final Channel.Builder builder = Channel.channel();

        if (data.containsKey("id"))
            builder.uuid(data.get("id", UUID.class));
        if (data.containsKey("identifier")) // <--- this should come from the Map.key
            builder.identifier(data.get("identifier", String.class));
        if (data.containsKey("name"))
            builder.displayName(data.get("name", Component.class));
        if (data.containsKey("format"))
            builder.format(Format.miniMessageFormat(data.get("format", String.class)));

        for (final Setting<?> setting : Channel.SETTINGS) {
            addSetting(data, builder, setting.key().asString().replace(SChat.NAMESPACE + ":", ""), setting);
        }

        return builder.build();
    }

    private <V> void addSetting(final DeserializationData data, final Channel.Builder builder, final String key, final Setting<V> setting) {
        if (data.containsKey(key))
            builder.setting(setting, data.get(key, setting.type()));
    }

Not compatible with Java 17

Describe the bug
Config generator printing null error with Java 17 when launching newest 1.18 minecraft version (paper).

To Reproduce
Steps to reproduce the behavior:

  1. Create config with ConfigurationFactory and YamlBukkitConfigurer.
  2. Launch minecraft server.
  3. See error.

Expected behavior
It wont create configuration file.

Library version
I've tried 3.1.0, 3.4.2 and 4.0.0-beta2.

Config classes and setup routine
Add config files source code and setup routine (the part with ConfigManager.create(...)).

Newly added variables are not in the proper order

Newly added variables are not in proper order

Steps to reproduce the behavior:

  1. Create configuration file with configurer presented below.
  2. Add new variable to your config class.
  3. Update your config.

Your newly added variables won't be placed in order as you initialized them in your config class.

All libs are versioned in 3.4.2.

ConfigManager.create(PluginConfiguration.class, (it) -> {
            it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(SectionSeparator.NEW_LINE), true), new SerdesBukkit());
            it.withBindFile(pluginConfigurationFile);
            it.saveDefaults();
            it.load(true);
        });

JSON Gson configs do not encode special characters

Describe the bug
JsonGsonConfigurer does not encode characters like ó, ę, ś, ą, ń, ć, », &

To Reproduce
Steps to reproduce the behavior:
Create a normal config using the JsonGsonConfigurer

Expected behavior
Characters should be encoded normally instead they're replaced as ? or an escaped java unicode character like \u0026

Library version
json gson configs ver 3.4.2

Config classes and setup routine
coreConfig = ConfigManager.create(CoreConfig.class, (it) ->
it.withConfigurer(new JsonGsonConfigurer())
.withBindFile(new File(this.getDataFolder(), "config.json"))
.saveDefaults()
.load(true));

potioneffecttype transformer where

Caused by: dev.cdfn.pets.dependency.eu.okaeri.configs.exception.OkaeriException: cannot simplify type class org.bukkit.potion.PotionEffectType (GenericsDeclaration(type=class org.bukkit.potion.PotionEffectType, subtype=null, isEnum=false)): 'PotionEffectType[3, FAST_DIGGING]' [class org.bukkit.potion.PotionEffectTypeWrapper]

PotionEffectType transformer is not registered in SerdesBukkit although it exists

Null value after config update

When config file is updated with new variable, it sets null value for it and in the config class I have something different in my initializer.

Steps to reproduce the behavior:

Create configuration file with built-in class.
Initialize class and assign it to variable at same time to create an instance of object to the config.
After doing that update your configuration file by adding new String variable to constructor params and initialize it in the class also (class variable defined earlier).
Try to update your configuration with preset presented on the bottom.
Your updated String variable will be null after updating the config with newly added custom class variable.

All used libs are versioned in 3.4.2.

Config classes and setup routine

public PluginConfiguration createPluginConfiguration(File pluginConfigurationFile) {
        return ConfigManager.create(PluginConfiguration.class, (it) -> {
            it.withConfigurer(new OkaeriValidator(new YamlBukkitConfigurer(SectionSeparator.NEW_LINE), true), new SerdesBukkit());
            it.withBindFile(pluginConfigurationFile);
            it.saveDefaults();
            it.load(true);
        });
    }

Try to update this config file with java class file attached.
bug-files.zip

Subconfigurations validation seem to be not implemented

Describe the bug
I have such code:

@Getter
@SuppressWarnings("FieldMayBeFinal")
@Names(strategy = NameStrategy.HYPHEN_CASE, modifier = NameModifier.TO_LOWER_CASE)
public class ModerationConfig extends OkaeriConfig {

    private CapsModerationConfig caps = new CapsModerationConfig();

    @Positive
    private int exampleField = 6;

    @Getter
    @SuppressWarnings("FieldMayBeFinal")
    @Names(strategy = NameStrategy.HYPHEN_CASE, modifier = NameModifier.TO_LOWER_CASE)
    public static class CapsModerationConfig extends OkaeriConfig {

        private boolean enable = true;

        @Positive
        private int length = 6;

        @Min(0) @Max(100)
        private int percent = 80;

        private boolean block = true;

    }

}

If I set "exampleField" and "length" to zeros, I get exception only for the field from topper class. If I set to zero "length" only, result is the same.

Library version

implementation 'eu.okaeri:okaeri-configs-yaml-bukkit:4.0.6'
implementation 'eu.okaeri:okaeri-configs-serdes-commons:4.0.6'
implementation 'eu.okaeri:okaeri-configs-serdes-bukkit:4.0.6'
implementation 'eu.okaeri:okaeri-configs-validator-okaeri:4.0.6'

Nested Object Serialization

Describe the bug
I have the following config and want to use the already registered serializer for the message text of the object:

public class ConfigTest extends OkaeriConfig {

    List<Message> messages = new ArrayList<>(List.of(
            new Message(text("Hi")),
            new Message(text("there!"))
    ));
}

@Data
public class Message {

    private final Component text;

    public Message(Component text) {
        this.text = text;
    }
}

final class MessageSerializer implements ObjectSerializer<Message> {

    @Override
    public boolean supports(Class<? super Message> type) {
        return Message.class.isAssignableFrom(type);
    }

    @Override
    public void serialize(Message object, SerializationData data) {
        data.add("text", object.getText());
    }

    @Override
    public Message deserialize(DeserializationData data, GenericsDeclaration generics) {
        return new Message(data.get("text", Component.class));
    }
}

final class MiniMessageComponentSerializer extends BidirectionalTransformer<String, Component> {

    private final MiniMessage parser = MiniMessage.miniMessage();

    @Override
    public GenericsPair<String, Component> getPair() {
        return new GenericsPair<>(GenericsDeclaration.of(String.class), GenericsDeclaration.of(Component.class));
    }

    @Override
    public Component leftToRight(final @NonNull String data, final @NonNull SerdesContext serdesContext) {
        return parser.deserialize(data);
    }

    @Override
    public String rightToLeft(final @NonNull Component data, final @NonNull SerdesContext serdesContext) {
        return parser.serialize(data);
    }
}

@PluginMain
public class TemplatePlugin extends JavaPlugin {

    @Getter
    @Accessors(fluent = true)
    private ConfigTest config;

    public TemplatePlugin() {
    }

    public TemplatePlugin(
            JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) {
        super(loader, description, dataFolder, file);
    }

    @Override
    public void onEnable() {
        loadConfig();
    }

    private void loadConfig() {
        this.config = ConfigManager.create(ConfigTest.class, config -> config
                .withConfigurer(new YamlBukkitConfigurer(), new SerdesBukkit(), new SerdesCommons(), new ExamplePack())
                .withBindFile("config.yml")
                .saveDefaults()
                .load(true));
    }
}

To Reproduce
See the following repository with a failing test: https://github.com/sVoxelDev/okaeri-nested-serialization-bug

Expected behavior
The serializers should leverage already existing serializers.

failed to #getValue for crates and Cannot cast me.paradis.smashcratess.crates.actions.MessageAction to java.util.List

really nice framework, i use it for all my projects but this time i tried to do something a little bit more complex

Describe the bug
registered serializer for class but its not able to find it, or get a value?
Caused by: eu.okaeri.configs.exception.OkaeriException: failed to #getValue for crates

To Reproduce
Steps to reproduce the behavior:
tried to follow the LocationSerializer under SerdesBukkit

  1. created class
  2. created serializer
  3. registered it but i get failed to get value

Expected behavior
MessageActionSerializer to override serialize method and save my custom value

Library version
implementation 'eu.okaeri:okaeri-configs-yaml-bukkit:5.0.0-beta.5'
implementation 'eu.okaeri:okaeri-configs-serdes-bukkit:5.0.0-beta.5'

Config classes and setup routine
all parts: https://paste.md-5.net/vowasuceki.java
full error: https://paste.md-5.net/osiqufiluc.bash

thank you 😄

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.