Java Code Examples for org.yaml.snakeyaml.Yaml#dump()

The following examples show how to use org.yaml.snakeyaml.Yaml#dump() . These examples are extracted from open source projects. 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
private void assertGeneratedSwaggerSpecYaml(String description) throws MojoExecutionException, MojoFailureException, IOException {
    mojo.getApiSources().get(0).setOutputFormats("yaml");
    mojo.execute();

    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    options.setPrettyFlow(true);
    Yaml yaml = new Yaml(options);
    String actualYaml = yaml.dump(yaml.load(FileUtils.readFileToString(new File(swaggerOutputDir, "swagger.yaml"))));
    String expectYaml = yaml.dump(yaml.load(this.getClass().getResourceAsStream("/expectedOutput/swagger-spring.yaml")));

    ObjectMapper mapper = Json.mapper();
    JsonNode actualJson = mapper.readTree(YamlToJson(actualYaml));
    JsonNode expectJson = mapper.readTree(YamlToJson(expectYaml));

    changeDescription(expectJson, description);
    assertJsonEquals(expectJson, actualJson, Configuration.empty().when(IGNORING_ARRAY_ORDER));
}
 
Example 2
Source Project: snake-yaml   File: SafeRepresenterTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testStyle2() {
    List<Integer> list = new ArrayList<Integer>();
    list.add(new Integer(1));
    list.add(new Integer(1));
    Map<String, Object> map = new LinkedHashMap<String, Object>();
    map.put("age", 5);
    map.put("name", "Ubuntu");
    map.put("list", list);
    DumperOptions options = new DumperOptions();
    options.setDefaultScalarStyle(DumperOptions.ScalarStyle.SINGLE_QUOTED);
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW);
    Yaml yaml = new Yaml(options);
    String output = yaml.dump(map);
    assertEquals("{'age': !!int '5', 'name': 'Ubuntu', 'list': [!!int '1', !!int '1']}\n",
            output);
}
 
Example 3
Source Project: spring-cloud-skipper   File: YmlUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static String getYamlConfigValues(File yamlFile, String properties) {
	String configValuesYML = null;
	if (yamlFile != null) {
		Yaml yaml = new Yaml();
		// Validate it is yaml formatted.
		try {
			configValuesYML = yaml.dump(yaml.load(new FileInputStream(yamlFile)));
		}
		catch (FileNotFoundException e) {
			throw new SkipperException("Could not find file " + yamlFile.toString());
		}
	}
	else if (StringUtils.hasText(properties)) {
		configValuesYML = convertToYaml(properties);
	}
	return configValuesYML;
}
 
Example 4
/**
 * Redacts the values stored for keys that contain the following:  password,
 * secret, key, token, *credentials.*.
 * @param yml String containing a yaml.
 * @return redacted yaml String.
 */
public static String sanitizeYml(String yml) {
	String result = "";
	try {
		DumperOptions options = new DumperOptions();
		options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
		options.setPrettyFlow(true);
		Yaml yaml = new Yaml(options);
		Iterator<Object> iter = yaml.loadAll(yml).iterator();
		while (iter.hasNext()) {
			Object o = iter.next();
			if (o instanceof LinkedHashMap) {
				iterateLinkedHashMap((LinkedHashMap<String, Object>) o);
			}
			result += yaml.dump(o);
		}
	}
	catch (Throwable throwable) {
		logger.error("Unable to redact data from Manifest debug entry", throwable);
	}
	if (result == null || result.length() == 0) {
		result = yml;
	}
	return result;
}
 
Example 5
Source Project: snake-yaml   File: AbstractBeanTest.java    License: 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 6
public void testDumpListSameIntegers() {
    List<Integer> l = new ArrayList<Integer>(2);
    l.add(1);
    l.add(1);
    Yaml yaml = new Yaml();
    String result = yaml.dump(l);
    assertEquals("[1, 1]\n", result);
}
 
Example 7
Source Project: Nukkit   File: Config.java    License: GNU General Public License v3.0 5 votes vote down vote up
public boolean save(Boolean async) {
    if (this.file == null) throw new IllegalStateException("Failed to save Config. File object is undefined.");
    if (this.correct) {
        String content = "";
        switch (this.type) {
            case Config.PROPERTIES:
                content = this.writeProperties();
                break;
            case Config.JSON:
                content = new GsonBuilder().setPrettyPrinting().create().toJson(this.config);
                break;
            case Config.YAML:
                DumperOptions dumperOptions = new DumperOptions();
                dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
                Yaml yaml = new Yaml(dumperOptions);
                content = yaml.dump(this.config);
                break;
            case Config.ENUM:
                for (Object o : this.config.entrySet()) {
                    Map.Entry entry = (Map.Entry) o;
                    content += entry.getKey() + "\r\n";
                }
                break;
        }
        if (async) {
            Server.getInstance().getScheduler().scheduleAsyncTask(new FileWriteTask(this.file, content));

        } else {
            try {
                Utils.writeFile(this.file, content);
            } catch (IOException e) {
                Server.getInstance().getLogger().logException(e);
            }
        }
        return true;
    } else {
        return false;
    }
}
 
Example 8
Source Project: snake-yaml   File: DumpExampleTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testDumpWriter() {
    Map<String, Object> data = new HashMap<String, Object>();
    data.put("name", "Silenthand Olleander");
    data.put("race", "Human");
    data.put("traits", new String[] { "ONE_HAND", "ONE_EYE" });
    Yaml yaml = new Yaml();
    StringWriter writer = new StringWriter();
    yaml.dump(data, writer);
    assertTrue(writer.toString().contains("name: Silenthand Olleander"));
    assertTrue(writer.toString().contains("race: Human"));
    assertTrue(writer.toString().contains("traits: [ONE_HAND, ONE_EYE]"));
}
 
Example 9
Source Project: snake-yaml   File: PyRecursiveTest.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testDictSafeConstructor() {
    Map value = new TreeMap();
    value.put("abc", "www");
    value.put("qwerty", value);
    Yaml yaml = new Yaml(new SafeConstructor());
    String output1 = yaml.dump(value);
    assertEquals("&id001\nabc: www\nqwerty: *id001\n", output1);
    Map value2 = (Map) yaml.load(output1);
    assertEquals(2, value2.size());
    assertEquals("www", value2.get("abc"));
    assertTrue(value2.get("qwerty") instanceof Map);
    Map value3 = (Map) value2.get("qwerty");
    assertTrue(value3.get("qwerty") instanceof Map);
}
 
Example 10
Source Project: snake-yaml   File: DiceExampleTest.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void testImplicitResolverWithNull() {
    Yaml yaml = new Yaml(new DiceConstructor(), new DiceRepresenter());
    // the tag may start with anything
    yaml.addImplicitResolver(new Tag("!dice"), Pattern.compile("\\d+d\\d+"), null);
    // dump
    Map<String, Dice> treasure = new HashMap<String, Dice>();
    treasure.put("treasure", new Dice(10, 20));
    String output = yaml.dump(treasure);
    assertEquals("{treasure: 10d20}\n", output);
    // load
    Object data = yaml.load("{damage: 5d10}");
    Map<String, Dice> map = (Map<String, Dice>) data;
    assertEquals(new Dice(5, 10), map.get("damage"));
}
 
Example 11
Source Project: snake-yaml   File: FileTest.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void test() {
    File file = new File("src/test/resources/examples/list-bean-1.yaml");
    assertTrue(file.exists());
    Yaml yaml = new Yaml(new MyRepresenter());
    Map<String, File> map = new HashMap<String, File>();
    map.put("one", file);
    String output = yaml.dump(map);
    // System.out.println(output);
    assertTrue(output, output.startsWith("{one: !!java.io.File '"));
    assertTrue(output, output.endsWith("list-bean-1.yaml'}\n"));
    Map<String, File> parsed = (Map<String, File>) yaml.load(output);
    File file2 = parsed.get("one");
    assertTrue(file2.getAbsolutePath(), file2.getAbsolutePath().endsWith("list-bean-1.yaml"));
}
 
Example 12
Source Project: rpcx-java   File: YamlTest.java    License: Apache License 2.0 5 votes vote down vote up
private String dump() {
    DumperOptions options = new DumperOptions();
    options.setPrettyFlow(true);
    Yaml yaml = new Yaml(options);
    RpcxConfig config = new RpcxConfig();
    config.setConsumerPackage("com.test.consumer");
    config.setFilterPackage("com.test.filter");
    return yaml.dump(config);
}
 
Example 13
Source Project: julongchain   File: MspHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static void exportConfig(String mspDir, String caFile, boolean enable) throws JulongChainException {
    OrgUnitIdentifiersConfig clientOUIdentifier = new OrgUnitIdentifiersConfig();
    clientOUIdentifier.setCertificate(caFile);
    clientOUIdentifier.setOrganizationalUnitIdentifier(CLIENT_OU);

    OrgUnitIdentifiersConfig nodeOUIdentifier = new OrgUnitIdentifiersConfig();
    nodeOUIdentifier.setCertificate(caFile);
    nodeOUIdentifier.setOrganizationalUnitIdentifier(NODE_OU);

    NodeOUs nodeOUs = new NodeOUs();
    nodeOUs.setClientOUIdentifier(clientOUIdentifier);
    nodeOUs.setNodeOUIdentifier(nodeOUIdentifier);
    nodeOUs.setEnable(enable);

    Configuration configuration = new Configuration();
    configuration.setNodeOUs(nodeOUs);

    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    Yaml yaml = new Yaml(options);
    String path = Paths.get(mspDir, "config.yaml").toString();
    try {
        yaml.dump(configuration.getPropertyMap(), new FileWriter(path));
    } catch (IOException e) {
        throw new JulongChainException("An error occurred on exportConfig:" + e.getMessage());
    }
}
 
Example 14
@BeforeClass
public void beforeClass() throws Exception {
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    Yaml yaml = new Yaml(options);

    JSONObject root = (JSONObject) TestUtils.loadJson("/translator.json");
    graph = new DGraph(root);

    Aam aam = new Translator().translate(graph);
    String serializedYaml = yaml.dump(aam);
    System.out.println(serializedYaml);
    
    Map<String, Map> deserializedYaml = (Map) yaml.load(serializedYaml);
    Map<String, Map> topology = deserializedYaml.get("topology_template");
    nodeTemplates = topology.get("node_templates");
    nodeTypes = deserializedYaml.get("node_types");
    groups = deserializedYaml.get("groups");
    
    n1 = nodeTemplates.get(N1);
    n2 = nodeTemplates.get(N2);
    n3 = nodeTemplates.get(N3);
    n4 = nodeTemplates.get(N4);
    n5 = nodeTemplates.get(N5);
    n6 = nodeTemplates.get(N6);
    n7 = nodeTemplates.get(N7);
    
    t1 = nodeTypes.get(N1_TYPE);
    t2 = nodeTypes.get(N2_TYPE);
    t3 = nodeTypes.get(N3_TYPE);
    t4 = nodeTypes.get(N4_TYPE);
    t5 = nodeTypes.get(N5_TYPE);
    t6 = nodeTypes.get(N6_TYPE);
    t7 = nodeTypes.get(N7_TYPE);
}
 
Example 15
Source Project: snake-yaml   File: YamlMapTest.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void testYamlMap() {
    Map<String, Object> data = new TreeMap<String, Object>();
    data.put("customTag", new Custom(123));

    Yaml yaml = new Yaml(new ExtendedConstructor(), new ExtendedRepresenter());
    String output = yaml.dump(data);
    // System.out.println(output);
    Object o = yaml.load(output);

    assertTrue(o instanceof Map);
    Map<String, Object> m = (Map<String, Object>) o;
    assertTrue(m.get("customTag") instanceof Custom);
}
 
Example 16
@Test
public void testYamlMerge() throws IOException {
	DumperOptions dumperOptions = new DumperOptions();
	dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
	dumperOptions.setPrettyFlow(true);
	Yaml yaml = new Yaml(dumperOptions);

	Resource resource = new ClassPathResource("/org/springframework/cloud/skipper/server/service/ticktock-1.0.0");

	Package pkg = this.packageReader.read(resource.getFile());
	ConfigValues configValues = new ConfigValues();
	Map<String, Object> configValuesMap = new TreeMap<>();
	Map<String, Object> logMap = new TreeMap<>();
	logMap.put("appVersion", "1.2.1.RELEASE");
	configValuesMap.put("log", logMap);
	configValuesMap.put("hello", "universe");

	String configYaml = yaml.dump(configValuesMap);
	configValues.setRaw(configYaml);
	Map<String, Object> mergedMap = ConfigValueUtils.mergeConfigValues(pkg, configValues);

	String mergedYaml = yaml.dump(mergedMap);
	String expectedYaml = StreamUtils.copyToString(
			TestResourceUtils.qualifiedResource(getClass(), "merged.yaml").getInputStream(),
			Charset.defaultCharset());
	assertThat(mergedYaml).isEqualTo(expectedYaml);
}
 
Example 17
Source Project: Jupiter   File: Config.java    License: GNU General Public License v3.0 5 votes vote down vote up
public boolean save(Boolean async) {
    if (this.file == null) throw new IllegalStateException("Failed to save Config. File object is undefined.");
    if (this.correct) {
        String content = "";
        switch (this.type) {
            case Config.PROPERTIES:
                content = this.writeProperties();
                break;
            case Config.JSON:
                content = new GsonBuilder().setPrettyPrinting().create().toJson(this.config);
                break;
            case Config.YAML:
                DumperOptions dumperOptions = new DumperOptions();
                dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
                Yaml yaml = new Yaml(dumperOptions);
                content = yaml.dump(this.config);
                break;
            case Config.ENUM:
                for (Object o : this.config.entrySet()) {
                    Map.Entry entry = (Map.Entry) o;
                    content += String.valueOf(entry.getKey()) + "\r\n";
                }
                break;
        }
        if (async) {
            Server.getInstance().getScheduler().scheduleAsyncTask(new FileWriteTask(this.file, content));

        } else {
            try {
                Utils.writeFile(this.file, content);
            } catch (IOException e) {
                Server.getInstance().getLogger().logException(e);
            }
        }
        return true;
    } else {
        return false;
    }
}
 
Example 18
public void testNoTimezone() {
    Yaml yaml = new Yaml();
    String output = yaml.dump(new Date());
    assertTrue(output, output.endsWith("Z\n"));
}
 
Example 19
Source Project: snake-yaml   File: HumanGenericsTest.java    License: Apache License 2.0 4 votes vote down vote up
public void testChildren2() throws IOException, IntrospectionException {
    if (!GenericsBugDetector.isProperIntrospection()) {
        return;
    }
    HumanGen2 father = new HumanGen2();
    father.setName("Father");
    father.setBirthday(new Date(1000000000));
    father.setBirthPlace("Leningrad");
    father.setBankAccountOwner(father);
    //
    HumanGen2 mother = new HumanGen2();
    mother.setName("Mother");
    mother.setBirthday(new Date(100000000000L));
    mother.setBirthPlace("Saint-Petersburg");
    father.setPartner(mother);
    mother.setPartner(father);
    mother.setBankAccountOwner(father);
    //
    HumanGen2 son = new HumanGen2();
    son.setName("Son");
    son.setBirthday(new Date(310000000000L));
    son.setBirthPlace("Munich");
    son.setBankAccountOwner(father);
    son.setFather(father);
    son.setMother(mother);
    //
    HumanGen2 daughter = new HumanGen2();
    daughter.setName("Daughter");
    daughter.setBirthday(new Date(420000000000L));
    daughter.setBirthPlace("New York");
    daughter.setBankAccountOwner(father);
    daughter.setFather(father);
    daughter.setMother(mother);
    //
    HashMap<HumanGen2, String> children = new LinkedHashMap<HumanGen2, String>(2);
    children.put(son, "son");
    children.put(daughter, "daughter");
    father.setChildren(children);
    mother.setChildren(children);
    //
    Representer representer = new Representer();
    representer.addClassTag(HumanGen2.class, Tag.MAP);
    Yaml yaml = new Yaml(representer);
    String output = yaml.dump(son);
    // System.out.println(output);
    String etalon = Util.getLocalResource("recursive/generics/with-children-2.yaml");
    assertEquals(etalon, output);
    // load
    TypeDescription humanDescription = new TypeDescription(HumanGen2.class);
    humanDescription.putMapPropertyType("children", HumanGen2.class, String.class);
    Yaml beanLoader = new Yaml(new Constructor(humanDescription));
    //
    HumanGen2 son2 = beanLoader.loadAs(output, HumanGen2.class);
    assertNotNull(son2);
    assertEquals("Son", son.getName());

    HumanGen2 father2 = son2.getFather();
    assertEquals("Father", father2.getName());
    assertEquals("Mother", son2.getMother().getName());
    assertSame(father2, father2.getBankAccountOwner());
    assertSame(father2.getPartner(), son2.getMother());
    assertSame(father2, son2.getMother().getPartner());

    Map<HumanGen2, String> children2 = father2.getChildren();
    assertEquals(2, children2.size());
    assertSame(father2.getPartner().getChildren(), children2);

}
 
Example 20
Source Project: sahagin-java   File: YamlUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static String dumpToString(Map<String, Object> yamlObj) {
    Yaml yaml = new Yaml();
    return yaml.dump(yamlObj);
}