org.yaml.snakeyaml.introspector.BeanAccess Java Examples

The following examples show how to use org.yaml.snakeyaml.introspector.BeanAccess. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ArrayInGenericCollectionTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
public void testArrayAsListValueWithTypeDespriptor() {
    Yaml yaml2dump = new Yaml();
    yaml2dump.setBeanAccess(BeanAccess.FIELD);
    B data = createB();
    String dump = yaml2dump.dump(data);
    // System.out.println(dump);

    TypeDescription aTypeDescr = new TypeDescription(B.class);
    aTypeDescr.putListPropertyType("meta", String[].class);

    Constructor c = new Constructor();
    c.addTypeDescription(aTypeDescr);
    Yaml yaml2load = new Yaml(c);
    yaml2load.setBeanAccess(BeanAccess.FIELD);

    B loaded = (B) yaml2load.load(dump);

    Assert.assertArrayEquals(data.meta.toArray(), loaded.meta.toArray());
}
 
Example #2
Source File: YamlConfigLoader.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
public static MxisdConfig loadFromFile(String path) throws IOException {
    File f = new File(path).getAbsoluteFile();
    log.info("Reading config from {}", f.toString());
    Representer rep = new Representer();
    rep.getPropertyUtils().setBeanAccess(BeanAccess.FIELD);
    rep.getPropertyUtils().setAllowReadOnlyProperties(true);
    rep.getPropertyUtils().setSkipMissingProperties(true);
    Yaml yaml = new Yaml(new Constructor(MxisdConfig.class), rep);
    try (FileInputStream is = new FileInputStream(f)) {
        MxisdConfig raw = yaml.load(is);
        log.debug("Read config in memory from {}", path);

        // SnakeYaml set objects to null when there is no value set in the config, even a full sub-tree.
        // This is problematic for default config values and objects, to avoid NPEs.
        // Therefore, we'll use Gson to re-parse the data in a way that avoids us checking the whole config for nulls.
        MxisdConfig cfg = GsonUtil.get().fromJson(GsonUtil.get().toJson(raw), MxisdConfig.class);

        log.info("Loaded config from {}", path);
        return cfg;
    } catch (ParserException t) {
        throw new ConfigurationException(t.getMessage(), "Could not parse YAML config file - Please check indentation and that the configuration options exist");
    }
}
 
Example #3
Source File: ArrayInGenericCollectionTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
public void testArrayAsMapValue() {
    Yaml yaml2dump = new Yaml();
    yaml2dump.setBeanAccess(BeanAccess.FIELD);
    A data = createA();
    String dump = yaml2dump.dump(data);
    // System.out.println(dump);

    Yaml yaml2load = new Yaml();
    yaml2load.setBeanAccess(BeanAccess.FIELD);
    A loaded = (A) yaml2load.load(dump);

    assertEquals(data.meta.size(), loaded.meta.size());
    Set<Entry<String, String[]>> loadedMeta = loaded.meta.entrySet();
    for (Entry<String, String[]> entry : loadedMeta) {
        assertTrue(data.meta.containsKey(entry.getKey()));
        Assert.assertArrayEquals(data.meta.get(entry.getKey()), entry.getValue());
    }
}
 
Example #4
Source File: TestUtils.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
/**
 * Create master key file.
 *
 * @param file                   file instance
 * @param masterKeyConfiguration master key configuration
 */
public static void createMasterKeyFile(File file, MasterKeyConfiguration masterKeyConfiguration) {
    try {
        file.createNewFile();
        file.deleteOnExit();
        FileWriter fileWriter = new FileWriter(file);

        DumperOptions options = new DumperOptions();
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);

        Representer representer = new Representer();
        representer.addClassTag(MasterKeyConfiguration.class, Tag.MAP);
        Yaml yaml = new Yaml(representer, options);

        yaml.setBeanAccess(BeanAccess.FIELD);
        yaml.dump(masterKeyConfiguration, fileWriter);
    } catch (IOException e) {
        Assert.fail("Failed to create temp password file");
    }
}
 
Example #5
Source File: ArrayInGenericCollectionTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
public void testArrayAsMapValueWithTypeDespriptor() {
    Yaml yaml2dump = new Yaml();
    yaml2dump.setBeanAccess(BeanAccess.FIELD);
    A data = createA();
    String dump = yaml2dump.dump(data);
    // System.out.println(dump);

    TypeDescription aTypeDescr = new TypeDescription(A.class);
    aTypeDescr.putMapPropertyType("meta", String.class, String[].class);

    Constructor c = new Constructor();
    c.addTypeDescription(aTypeDescr);
    Yaml yaml2load = new Yaml(c);
    yaml2load.setBeanAccess(BeanAccess.FIELD);

    A loaded = (A) yaml2load.load(dump);

    assertEquals(data.meta.size(), loaded.meta.size());
    Set<Entry<String, String[]>> loadedMeta = loaded.meta.entrySet();
    for (Entry<String, String[]> entry : loadedMeta) {
        assertTrue(data.meta.containsKey(entry.getKey()));
        Assert.assertArrayEquals(data.meta.get(entry.getKey()), entry.getValue());
    }
}
 
Example #6
Source File: AbstractBeanTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
public void testErrorMessage() throws Exception {

        BeanA1 b = new BeanA1();
        b.setId(2l);
        b.setName("name1");

        Constructor c = new Constructor();
        Representer r = new Representer();

        PropertyUtils pu = new PropertyUtils();
        c.setPropertyUtils(pu);
        r.setPropertyUtils(pu);

        pu.getProperties(BeanA1.class, BeanAccess.FIELD);

        Yaml yaml = new Yaml(c, r);
        // yaml.setBeanAccess(BeanAccess.FIELD);
        String dump = yaml.dump(b);
        BeanA1 b2 = (BeanA1) yaml.load(dump);
        assertEquals(b.getId(), b2.getId());
        assertEquals(b.getName(), b2.getName());
    }
 
Example #7
Source File: ChronixSparkLoader.java    From chronix.spark with Apache License 2.0 6 votes vote down vote up
public ChronixSparkLoader() {
    Representer representer = new Representer();
    representer.getPropertyUtils().setSkipMissingProperties(true);

    Constructor constructor = new Constructor(YamlConfiguration.class);

    TypeDescription typeDescription = new TypeDescription(ChronixYAMLConfiguration.class);
    typeDescription.putMapPropertyType("configurations", Object.class, ChronixYAMLConfiguration.IndividualConfiguration.class);
    constructor.addTypeDescription(typeDescription);

    Yaml yaml = new Yaml(constructor, representer);
    yaml.setBeanAccess(BeanAccess.FIELD);

    InputStream in = this.getClass().getClassLoader().getResourceAsStream("test_config.yml");
    chronixYAMLConfiguration = yaml.loadAs(in, ChronixYAMLConfiguration.class);
}
 
Example #8
Source File: Utils.java    From msf4j with Apache License 2.0 6 votes vote down vote up
public static TransportsConfiguration resolveTransportsNSConfiguration(Object transportsConfig)
        throws ConfigurationException {

    TransportsConfiguration transportsConfiguration;

    if (transportsConfig instanceof Map) {
        LinkedHashMap httpConfig = ((LinkedHashMap) ((Map) transportsConfig).get("http"));
        if (httpConfig != null) {
            String configYaml = new Yaml().dump(httpConfig);
            Yaml yaml = new Yaml(new CustomClassLoaderConstructor(TransportsConfiguration.class,
                    TransportsConfiguration.class.getClassLoader()));
            yaml.setBeanAccess(BeanAccess.FIELD);
            transportsConfiguration = yaml.loadAs(configYaml, TransportsConfiguration.class);

        } else {
            transportsConfiguration = new TransportsConfiguration();
        }
    } else {
        throw new ConfigurationException("The first level config under 'transports' namespace should be " +
                "a map.");
    }
    return transportsConfiguration;
}
 
Example #9
Source File: ContainerDataYaml.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Read the yaml content, and return containerData.
 *
 * @throws IOException
 */
public static ContainerData readContainer(InputStream input)
    throws IOException {

  ContainerData containerData;
  PropertyUtils propertyUtils = new PropertyUtils();
  propertyUtils.setBeanAccess(BeanAccess.FIELD);
  propertyUtils.setAllowReadOnlyProperties(true);

  Representer representer = new ContainerDataRepresenter();
  representer.setPropertyUtils(propertyUtils);

  Constructor containerDataConstructor = new ContainerDataConstructor();

  Yaml yaml = new Yaml(containerDataConstructor, representer);
  yaml.setBeanAccess(BeanAccess.FIELD);

  containerData = (ContainerData)
      yaml.load(input);

  return containerData;
}
 
Example #10
Source File: ContainerDataYaml.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Given a ContainerType this method returns a Yaml representation of
 * the container properties.
 *
 * @param containerType type of container
 * @return Yamal representation of container properties
 *
 * @throws StorageContainerException if the type is unrecognized
 */
public static Yaml getYamlForContainerType(ContainerType containerType)
    throws StorageContainerException {
  PropertyUtils propertyUtils = new PropertyUtils();
  propertyUtils.setBeanAccess(BeanAccess.FIELD);
  propertyUtils.setAllowReadOnlyProperties(true);

  switch (containerType) {
  case KeyValueContainer:
    Representer representer = new ContainerDataRepresenter();
    representer.setPropertyUtils(propertyUtils);
    representer.addClassTag(
        KeyValueContainerData.class,
        KeyValueContainerData.KEYVALUE_YAML_TAG);

    Constructor keyValueDataConstructor = new ContainerDataConstructor();

    return new Yaml(keyValueDataConstructor, representer);
  default:
    throw new StorageContainerException("Unrecognized container Type " +
        "format " + containerType, ContainerProtos.Result
        .UNKNOWN_CONTAINER_TYPE);
  }
}
 
Example #11
Source File: YAMLConfigManager.java    From siddhi with Apache License 2.0 6 votes vote down vote up
/**
 * Initialises YAML Config Manager by parsing the YAML file
 *
 * @throws YAMLConfigManagerException Exception is thrown if there are issues in processing thr yaml file
 */
private void init(String yamlContent) throws YAMLConfigManagerException {
    try {
        CustomClassLoaderConstructor constructor = new CustomClassLoaderConstructor(
                RootConfiguration.class, RootConfiguration.class.getClassLoader());
        PropertyUtils propertyUtils = new PropertyUtils();
        propertyUtils.setSkipMissingProperties(true);
        constructor.setPropertyUtils(propertyUtils);

        Yaml yaml = new Yaml(constructor);
        yaml.setBeanAccess(BeanAccess.FIELD);
        this.rootConfiguration = yaml.load(yamlContent);
    } catch (Exception e) {
        throw new YAMLConfigManagerException("Unable to parse YAML string, '" + yamlContent + "'.", e);
    }
}
 
Example #12
Source File: OutdatedConfigurationPropertyUtils.java    From ServerListPlus with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Property getProperty(Class<?> type, String name, BeanAccess bAccess) {
    if (bAccess != BeanAccess.FIELD) return super.getProperty(type, name, bAccess);
    Map<String, Property> properties = getPropertiesMap(type, bAccess);
    Property property = properties.get(Helper.toLowerCase(name));

    if (property == null) { // Check if property was missing and notify user if necessary
        if (type != UnknownConf.class)
            core.getLogger().log(WARN, "Unknown configuration property: %s @ %s", name, type.getSimpleName());
        return new OutdatedMissingProperty(name);
    }

    if (!property.isWritable()) // Throw exception from super method
        throw new YAMLException("Unable to find writable property '" + name + "' on class: " + type.getName());

    return property;
}
 
Example #13
Source File: YamlSerializer.java    From copper-engine with Apache License 2.0 5 votes vote down vote up
protected Yaml initialYaml() {
    DumperOptions dO = new DumperOptions();
    dO.setAllowReadOnlyProperties(true);
    Yaml yaml = new Yaml(dO);
    yaml.setBeanAccess(BeanAccess.FIELD);
    return yaml;
}
 
Example #14
Source File: ArrayInGenericCollectionTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testArrayAsListValue() {
    Yaml yaml2dump = new Yaml();
    yaml2dump.setBeanAccess(BeanAccess.FIELD);
    B data = createB();
    String dump = yaml2dump.dump(data);
    // System.out.println(dump);

    Yaml yaml2load = new Yaml();
    yaml2load.setBeanAccess(BeanAccess.FIELD);
    B loaded = (B) yaml2load.load(dump);

    Assert.assertArrayEquals(data.meta.toArray(), loaded.meta.toArray());
}
 
Example #15
Source File: AbstractPropertyUtils.java    From ServerListPlus with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Map<String, Property> getPropertiesMap(Class<?> type, BeanAccess bAccess) {
    if (bAccess == BeanAccess.FIELD) {
        Map<String, Property> properties = new LinkedHashMap<>();
        findProperties(type, properties);
        propertiesCache.put(type, properties);
        return properties;
    } else return super.getPropertiesMap(type, bAccess);
}
 
Example #16
Source File: ArrayInGenericCollectionTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testNoTags() {
    Yaml yaml2dump = new Yaml();
    yaml2dump.setBeanAccess(BeanAccess.FIELD);
    B data = createB();
    String dump = yaml2dump.dumpAs(data, Tag.MAP, FlowStyle.AUTO);
    // System.out.println(dump);
    assertEquals("meta:\n- [whatever]\n- [something, something else]\n", dump);
    //
    Constructor constr = new Constructor(B.class);
    Yaml yaml2load = new Yaml(constr);
    yaml2load.setBeanAccess(BeanAccess.FIELD);
    B loaded = (B) yaml2load.load(dump);

    Assert.assertArrayEquals(data.meta.toArray(), loaded.meta.toArray());
}
 
Example #17
Source File: ConfigurationPropertyUtils.java    From ServerListPlus with GNU General Public License v3.0 5 votes vote down vote up
@Override // Print warning for unknown properties
public Property getProperty(Class<?> type, String name, BeanAccess bAccess) {
    if (bAccess != BeanAccess.FIELD) return super.getProperty(type, name, bAccess);
    Property p = super.getProperty(type, Helper.toLowerCase(name), bAccess);
    // Check if property was missing and notify user if necessary
    if ((p instanceof MissingProperty) && type != UnknownConf.class)
        core.getLogger().log(WARN, "Unknown configuration property: {} @ {}", name, type.getSimpleName());
    return p;
}
 
Example #18
Source File: DumpSetAsSequenceExampleTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
private void check(String doc) {
    Yaml yamlLoader = new Yaml();
    yamlLoader.setBeanAccess(BeanAccess.FIELD);
    Blog blog = (Blog) yamlLoader.load(doc);
    assertEquals("Test Me!", blog.getName());
    assertEquals(2, blog.numbers.size());
    assertEquals(2, blog.getPosts().size());
    for (Post post : blog.getPosts()) {
        assertEquals(Post.class, post.getClass());
    }
}
 
Example #19
Source File: SetAsSequenceTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testYaml() {
    String serialized = Util.getLocalResource("issues/issue73-2.txt");
    // System.out.println(serialized);
    Yaml beanLoader = new Yaml();
    beanLoader.setBeanAccess(BeanAccess.FIELD);
    Blog rehydrated = beanLoader.loadAs(serialized, Blog.class);
    checkTestBlog(rehydrated);
}
 
Example #20
Source File: SetAsSequenceTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testLoad() {
    Yaml yaml = new Yaml();
    yaml.setBeanAccess(BeanAccess.FIELD);
    String doc = Util.getLocalResource("issues/issue73-1.txt");
    Blog blog = (Blog) yaml.load(doc);
    // System.out.println(blog);
    assertEquals("Test Me!", blog.getName());
    assertEquals(2, blog.numbers.size());
    assertEquals(2, blog.getPosts().size());
    for (Post post : blog.getPosts()) {
        assertEquals(Post.class, post.getClass());
    }
}
 
Example #21
Source File: FieldListTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testYaml() {
    Yaml beanLoader = new Yaml();
    beanLoader.setBeanAccess(BeanAccess.FIELD);
    BlogField rehydrated = beanLoader.loadAs(Util.getLocalResource("issues/issue55_2.txt"),
            BlogField.class);
    assertEquals(4, rehydrated.getPosts().size());
}
 
Example #22
Source File: YamlFieldAccessCollectionTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testYamlDefaultWithFeildAccess() {
    Yaml yaml = new Yaml();
    yaml.setBeanAccess(BeanAccess.FIELD);
    Blog original = createTestBlog();
    String serialized = yaml.dump(original);
    assertEquals(Util.getLocalResource("issues/issue55_1_rootTag.txt"), serialized);
    Blog rehydrated = (Blog) yaml.load(serialized);
    checkTestBlog(rehydrated);
}
 
Example #23
Source File: YamlFieldAccessCollectionTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testYaml() {
    Blog original = createTestBlog();
    Yaml yamlDumper = constructYamlDumper();
    String serialized = yamlDumper.dumpAsMap(original);
    // System.out.println(serialized);
    assertEquals(Util.getLocalResource("issues/issue55_1.txt"), serialized);
    Yaml blogLoader = new Yaml();
    blogLoader.setBeanAccess(BeanAccess.FIELD);
    Blog rehydrated = blogLoader.loadAs(serialized, Blog.class);
    checkTestBlog(rehydrated);
}
 
Example #24
Source File: JavaBeanListTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testYaml() {
    Yaml beanLoader = new Yaml();
    beanLoader.setBeanAccess(BeanAccess.FIELD);
    BlogBean rehydrated = (BlogBean) beanLoader.loadAs(
            Util.getLocalResource("issues/issue55_2.txt"), BlogBean.class);
    assertEquals(4, rehydrated.getPosts().size());
}
 
Example #25
Source File: ConfigSerializer.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
public ConfigSerializer() {
  final DumperOptions options = new DumperOptions();
  options.setPrettyFlow(true);
  options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);

  yaml = new Yaml(new ConfigConstructor(), new ConfigRepresenter(), options);
  yaml.setBeanAccess(BeanAccess.FIELD);
}
 
Example #26
Source File: VersionedYamlDoc.java    From onedev with MIT License 5 votes vote down vote up
OneYaml() {
	super(newConstructor(), newRepresenter());
	
	/*
	 * Use property here as yaml will be read by human and we want to make 
	 * it consistent with presented in UI 
	 */
	setBeanAccess(BeanAccess.PROPERTY);
}
 
Example #27
Source File: AdvancedPropertyUtilsTest.java    From waggle-dance with Apache License 2.0 5 votes vote down vote up
@Test
public void allowReadOnlyProperties() throws IntrospectionException {
  propertyUtils.setAllowReadOnlyProperties(true);
  Set<Property> properties = propertyUtils.createPropertySet(UnwriteableTestBean.class, BeanAccess.DEFAULT);
  assertThat(properties.size(), is(1));
  assertThat(properties.iterator().next().getName(), is(longPropertyName));
}
 
Example #28
Source File: ObjectMapConfiguration.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
public void save(Writer writer) {
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(FlowStyle.AUTO);
    options.setIndent(4);
    Representer representer = new Representer();
    representer.getPropertyUtils().setBeanAccess(BeanAccess.DEFAULT);
    new Yaml(options).dump(this, writer);
}
 
Example #29
Source File: JavaBeanLoader.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
public JavaBeanLoader(LoaderOptions options, BeanAccess beanAccess) {
    if (options == null) {
        throw new NullPointerException("LoaderOptions must be provided.");
    }
    if (options.getRootTypeDescription() == null) {
        throw new NullPointerException("TypeDescription must be provided.");
    }
    Constructor constructor = new Constructor(options.getRootTypeDescription());
    loader = new Yaml(constructor, options, new Representer(), new DumperOptions(),
            new Resolver());
    loader.setBeanAccess(beanAccess);
}
 
Example #30
Source File: AppSvcManager.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
private void processSynapseConfig(MxisdConfig cfg) {
    String synapseRegFile = cfg.getAppsvc().getRegistration().getSynapse().getFile();

    if (StringUtils.isBlank(synapseRegFile)) {
        log.info("No synapse registration file path given - skipping generation...");
        return;
    }

    SynapseRegistrationYaml syncCfg = SynapseRegistrationYaml.parse(cfg.getAppsvc(), cfg.getMatrix().getDomain());

    Representer rep = new Representer();
    rep.getPropertyUtils().setBeanAccess(BeanAccess.FIELD);
    Yaml yaml = new Yaml(rep);

    // SnakeYAML set the type of object on the first line, which can fail to be parsed on synapse
    // We therefore need to split the resulting string, remove the first line, and then write it
    List<String> lines = new ArrayList<>(Arrays.asList(yaml.dump(syncCfg).split("\\R+")));
    if (StringUtils.equals(lines.get(0), "!!" + SynapseRegistrationYaml.class.getCanonicalName())) {
        lines.remove(0);
    }

    try (FileOutputStream os = new FileOutputStream(synapseRegFile)) {
        IOUtils.writeLines(lines, System.lineSeparator(), os, StandardCharsets.UTF_8);
    } catch (IOException e) {
        throw new RuntimeException("Unable to write synapse appservice registration file", e);
    }
}