SnakeYaml "Невозможно найти ошибку собственности" - PullRequest
0 голосов
/ 03 октября 2018

Вот часть моего config.yml:

#Authenctication
AuthenticationConfig:
  AuthencticationType: LDAP
  LDAPConfig:
     LDAPUrl: ldap://localhost:389
     ConnectionType: simple
     LDAPSecurityConfig:
        RootDN: cn=manager,dc=maxcrc,dc=com
        RootPassword: secret
        UserSearchDN: ou=People,dc=maxcrc,dc=com
        GroupdSearchDB: ou=Groups,dc=maxcrc,dc=com

У меня есть класс, используемый для разбора:

public class YamlConfiguraiton {
    private AuthenticationConfiguration AuthenticationConfig;

    public void setAuthenticationConfig(AuthenticationConfiguration AuthenticationConfig) {
        this.AuthenticationConfig = AuthenticationConfig;
    }

    public AuthenticationConfiguration getAuthenticationConfig() {
        return this.AuthenticationConfig;
    }
}

Однако, когда я запускаю

try(InputStream in = new FileInputStream(new File(ymalPath))) {
            yamlConfig = yaml.loadAs(in, YamlConfiguraiton.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

происходит следующая ошибка:

Exception in thread "main" Cannot create property=AuthenticationConfig for JavaBean=com.ibm.entity.matching.common.bootstrap.YamlConfiguraiton@e7860081
 in 'reader', line 2, column 1:
    AuthenticationConfig:
    ^
Unable to find property 'AuthenticationConfig' on class: com.ibm.entity.matching.common.bootstrap.YamlConfiguraiton
 in 'reader', line 3, column 4:
       AuthencticationType: LDAP
       ^

    at org.yaml.snakeyaml.constructor.Constructor$ConstructMapping.constructJavaBean2ndStep(Constructor.java:270)
    at org.yaml.snakeyaml.constructor.Constructor$ConstructMapping.construct(Constructor.java:149)
    at org.yaml.snakeyaml.constructor.Constructor$ConstructYamlObject.construct(Constructor.java:309)
    at org.yaml.snakeyaml.constructor.BaseConstructor.constructObjectNoCheck(BaseConstructor.java:204)
    at org.yaml.snakeyaml.constructor.BaseConstructor.constructObject(BaseConstructor.java:193)
    at org.yaml.snakeyaml.constructor.BaseConstructor.constructDocument(BaseConstructor.java:159)
    at org.yaml.snakeyaml.constructor.BaseConstructor.getSingleData(BaseConstructor.java:146)
    at org.yaml.snakeyaml.Yaml.loadFromReader(Yaml.java:524)
    at org.yaml.snakeyaml.Yaml.loadAs(Yaml.java:518)
    at com.ibm.entity.matching.bootstrap.EntityMatching.boot(EntityMatching.java:55)
    at com.ibm.entity.matching.bootstrap.EntityMatching.main(EntityMatching.java:35)
Caused by: org.yaml.snakeyaml.error.YAMLException: Unable to find property 'AuthenticationConfig' on class: com.ibm.entity.matching.common.bootstrap.YamlConfiguraiton
    at org.yaml.snakeyaml.introspector.PropertyUtils.getProperty(PropertyUtils.java:159)
    at org.yaml.snakeyaml.introspector.PropertyUtils.getProperty(PropertyUtils.java:148)
    at org.yaml.snakeyaml.constructor.Constructor$ConstructMapping.getProperty(Constructor.java:287)
    at org.yaml.snakeyaml.constructor.Constructor$ConstructMapping.constructJavaBean2ndStep(Constructor.java:208)
    ... 10 more

Почему он жалуется, что не может найти свойство AuthenticationConfig, а AuthenticationConfig - это просто имя переменной экземпляра?

ОБНОВЛЕНИЕ После того, как я изменил переменные экземпляра с "private" на "public", они были распознаны SnakeYaml, но это не то, что мы ожидаем наверняка.Классы не распознаются как JavaBean.

ОБНОВЛЕНИЕ Я нашел основную причину.Это соглашение об именах.Если вы хотите, чтобы SnakeYaml проанализировал ваш файл yaml, должен быть соблюден camelCase.Имя метода установки и метода получения также важно.Скажем, есть личная переменная экземпляра с именем ldapConfig, тогда ее имя получателя и сеттера должно быть getLdapConfig и setLdapConfig, даже getLDAPConfig и setLDAPConfig не будут работать.

1 Ответ

0 голосов
/ 03 октября 2018

Основная причина ошибки заключается в том, что вам нужно определить все атрибуты, присутствующие в файле Yaml в классе POJO (т. Е. YamlConfiguraiton).

Вы можете использовать приведенный ниже код, чтобы пропустить неопределенные свойства.

Representer representer = new Representer();
            representer.getPropertyUtils().setSkipMissingProperties(true);
            Yaml yaml = new Yaml(new Constructor(YamlConfiguraiton.class), representer);

Во-первых, переименуйте имена атрибутов в camelCase в файле Yaml.

См. Следующий код: -

Код: -

public class YamlReadCustom {

    private static String yamlPath = "/authentication.yaml";

    public static void main(String[] args) {
        Representer representer = new Representer();
        representer.getPropertyUtils().setSkipMissingProperties(true);
        Yaml yaml = new Yaml(new Constructor(Authentication.class), representer);
        try(InputStream in = YamlReadCustom.class.getResourceAsStream (yamlPath)) {
            Authentication authentication = yaml.loadAs(in, Authentication.class);
            System.out.println(authentication.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Аутентификация: -

public class Authentication {
    private String authenticationConfig;
    private String authencticationType;
    private LdapConfig ldapConfig;

    //getters and setters
}

LdapConfig: -

public class LdapConfig {
    private String ldapUrl;
    private String connectionType;
    private Map<String, Object> ldapSecurityConfig;
    //getters and setters
}

authentication.yaml

authenticationConfig:
authencticationType: LDAP
ldapConfig:
  ldapUrl: ldap://localhost:389
  connectionType: simple
  ldapSecurityConfig:
    rootDn: cn=manager,dc=maxcrc,dc=com
    rootPassword: secret
    userSearchDn: ou=People,dc=maxcrc,dc=com
    groupdSearchDb: ou=Groups,dc=maxcrc,dc=com
...