org.yaml.snakeyaml.DumperOptions.FlowStyle Java Examples

The following examples show how to use org.yaml.snakeyaml.DumperOptions.FlowStyle. 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: JodaTimeFlowStylesTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
/**
 * !!timestamp must be used, without it the implicit tag will be ignored
 * because 'date' is the JavaBean property.
 * 
 * Since the timestamp contains ':' character it cannot use plain scalar
 * style in the FLOW mapping style. Emitter suggests single quoted scalar
 * style and that is why the explicit '!!timestamp' is present in the YAML
 * document.
 * 
 * @see <a href="http://code.google.com/p/snakeyaml/issues/detail?id=128"></a>
 * 
 */
public void testLoadBeanWithAutoFlow() {
    MyBean bean = new MyBean();
    bean.setId("id123");
    DateTime etalon = new DateTime(timestamp, DateTimeZone.UTC);
    bean.setDate(etalon);
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(FlowStyle.AUTO);
    Yaml dumper = new Yaml(new JodaTimeRepresenter(), options);
    String doc = dumper.dump(bean);
    // System.out.println(doc);
    assertEquals(
            "!!examples.jodatime.MyBean {date: !!timestamp '2001-09-09T01:46:40Z', id: id123}\n",
            doc);
    Yaml loader = new Yaml(new JodaTimeImplicitContructor());
    MyBean parsed = (MyBean) loader.load(doc);
    assertEquals(etalon, parsed.getDate());
}
 
Example #2
Source File: BaseRepresenter.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
protected Node representSequence(Tag tag, Iterable<?> sequence, Boolean flowStyle) {
    int size = 10;// default for ArrayList
    if (sequence instanceof List<?>) {
        size = ((List<?>) sequence).size();
    }
    List<Node> value = new ArrayList<Node>(size);
    SequenceNode node = new SequenceNode(tag, value, flowStyle);
    representedObjects.put(objectToRepresent, node);
    boolean bestStyle = true;
    for (Object item : sequence) {
        Node nodeItem = representData(item);
        if (!(nodeItem instanceof ScalarNode && ((ScalarNode) nodeItem).getStyle() == null)) {
            bestStyle = false;
        }
        value.add(nodeItem);
    }
    if (flowStyle == null) {
        if (defaultFlowStyle != FlowStyle.AUTO) {
            node.setFlowStyle(defaultFlowStyle.getStyleBoolean());
        } else {
            node.setFlowStyle(bestStyle);
        }
    }
    return node;
}
 
Example #3
Source File: BaseRepresenter.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
protected Node representMapping(Tag tag, Map<?, ?> mapping, Boolean flowStyle) {
    List<NodeTuple> value = new ArrayList<NodeTuple>(mapping.size());
    MappingNode node = new MappingNode(tag, value, flowStyle);
    representedObjects.put(objectToRepresent, node);
    boolean bestStyle = true;
    for (Map.Entry<?, ?> entry : mapping.entrySet()) {
        Node nodeKey = representData(entry.getKey());
        Node nodeValue = representData(entry.getValue());
        if (!(nodeKey instanceof ScalarNode && ((ScalarNode) nodeKey).getStyle() == null)) {
            bestStyle = false;
        }
        if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null)) {
            bestStyle = false;
        }
        value.add(new NodeTuple(nodeKey, nodeValue));
    }
    if (flowStyle == null) {
        if (defaultFlowStyle != FlowStyle.AUTO) {
            node.setFlowStyle(defaultFlowStyle.getStyleBoolean());
        } else {
            node.setFlowStyle(bestStyle);
        }
    }
    return node;
}
 
Example #4
Source File: HelmChartHandler.java    From module-ballerina-kubernetes with Apache License 2.0 6 votes vote down vote up
private void generateChartYAML(Path helmBaseOutputDir) throws KubernetesPluginException {
    DeploymentModel model = this.dataHolder.getDeploymentModel();
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(FlowStyle.BLOCK);
    Yaml yaml = new Yaml(options);
    Map<String, String> values = new LinkedHashMap<>();
    values.put(HELM_API_VERSION, HELM_API_VERSION_DEFAULT);
    values.put(HELM_APP_VERSION, HELM_APP_VERSION_DEFAULT);
    values.put(HELM_DESCRIPTION, "Helm chart for " + model.getName());
    values.put(HELM_NAME, model.getName());
    values.put(HELM_VERSION, model.getVersion() == null ? HELM_VERSION_DEFAULT : model.getVersion());
    try (FileWriter writer = new FileWriter(helmBaseOutputDir.resolve(HELM_CHART_YAML_FILE_NAME).toString())) {
        yaml.dump(values, writer);
    } catch (IOException e) {
        throw new KubernetesPluginException("error in generating the Helm chart: " + e.getMessage(), e);
    }
}
 
Example #5
Source File: YamlPipelineConfiguration.java    From baleen with Apache License 2.0 6 votes vote down vote up
@Override
public String dumpOrdered(List<Object> ann, List<Object> con) {

  Map<String, Object> confMap;
  if (root instanceof Map<?, ?>) {
    confMap = new LinkedHashMap<>((Map<String, Object>) root);
  } else {
    confMap = new LinkedHashMap<>();
  }
  confMap.put("annotators", ann);
  confMap.put("consumers", con);

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

  org.yaml.snakeyaml.Yaml y = new org.yaml.snakeyaml.Yaml(options);
  return y.dump(confMap);
}
 
Example #6
Source File: XmlBuildSpecMigrator.java    From onedev with MIT License 6 votes vote down vote up
private static Node migrateJobDependency(Element jobDependencyElement) {
	List<NodeTuple> tuples = new ArrayList<>();
	tuples.add(new NodeTuple(
			new ScalarNode(Tag.STR, "jobName"), 
			new ScalarNode(Tag.STR, jobDependencyElement.elementText("jobName").trim())));
	tuples.add(new NodeTuple(
			new ScalarNode(Tag.STR, "requireSuccessful"), 
			new ScalarNode(Tag.STR, jobDependencyElement.elementText("requireSuccessful").trim())));
	Element artifactsElement = jobDependencyElement.element("artifacts");
	if (artifactsElement != null) {
		tuples.add(new NodeTuple(
				new ScalarNode(Tag.STR, "artifacts"), 
				new ScalarNode(Tag.STR, artifactsElement.getText().trim())));
	}
	
	List<Node> paramSupplyNodes = migrateParamSupplies(jobDependencyElement.element("jobParams").elements());
	if (!paramSupplyNodes.isEmpty()) {
		tuples.add(new NodeTuple(
				new ScalarNode(Tag.STR, "jobParams"), 
				new SequenceNode(Tag.SEQ, paramSupplyNodes, FlowStyle.BLOCK)));
	}
	return new MappingNode(Tag.MAP, tuples, FlowStyle.BLOCK);
}
 
Example #7
Source File: ImplicitTagsTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
public void testNoRootTag() {
    CarWithWheel car1 = new CarWithWheel();
    car1.setPlate("12-XP-F4");
    Wheel wheel = new Wheel();
    wheel.setId(2);
    car1.setWheel(wheel);
    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("id", 3);
    car1.setMap(map);
    car1.setYear("2008");
    String carYaml1 = new Yaml().dumpAs(car1, Tag.MAP, FlowStyle.AUTO);
    assertEquals(Util.getLocalResource("constructor/car-without-root-tag.yaml"), carYaml1);
    //
    Constructor contructor = new Constructor(CarWithWheel.class);
    CarWithWheel car2 = (CarWithWheel) new Yaml(contructor).load(carYaml1);
    String carYaml2 = new Yaml().dumpAs(car2, Tag.MAP, FlowStyle.AUTO);
    assertEquals(carYaml1, carYaml2);
}
 
Example #8
Source File: YamlFactory.java    From waggle-dance with Apache License 2.0 6 votes vote down vote up
public static Yaml newYaml() {
  PropertyUtils propertyUtils = new AdvancedPropertyUtils();
  propertyUtils.setSkipMissingProperties(true);

  Constructor constructor = new Constructor(Federations.class);
  TypeDescription federationDescription = new TypeDescription(Federations.class);
  federationDescription.putListPropertyType("federatedMetaStores", FederatedMetaStore.class);
  constructor.addTypeDescription(federationDescription);
  constructor.setPropertyUtils(propertyUtils);

  Representer representer = new AdvancedRepresenter();
  representer.setPropertyUtils(new FieldOrderPropertyUtils());
  representer.addClassTag(Federations.class, Tag.MAP);
  representer.addClassTag(AbstractMetaStore.class, Tag.MAP);
  representer.addClassTag(WaggleDanceConfiguration.class, Tag.MAP);
  representer.addClassTag(YamlStorageConfiguration.class, Tag.MAP);
  representer.addClassTag(GraphiteConfiguration.class, Tag.MAP);

  DumperOptions dumperOptions = new DumperOptions();
  dumperOptions.setIndent(2);
  dumperOptions.setDefaultFlowStyle(FlowStyle.BLOCK);

  return new Yaml(constructor, representer, dumperOptions);
}
 
Example #9
Source File: DbEnvironmentXmlEnricherTest.java    From obevo with Apache License 2.0 6 votes vote down vote up
@Test
    public void convert() throws Exception {
        XMLConfiguration configuration = new FileBasedConfigurationBuilder<>(XMLConfiguration.class)
                .configure(new Parameters().hierarchical()
                        .setFile(new File("./src/test/resources/DbEnvironmentXmlEnricher/system-config.xml"))
                ).getConfiguration();

        Map<String, Object> myMap = constructMap(configuration.getNodeModel().getNodeHandler().getRootNode());

        YAMLConfiguration yamlConfiguration = new YAMLConfiguration(configuration);
        StringWriter sw = new StringWriter();
//        yamlConfiguration.write();
        DumperOptions dumperOptions = new DumperOptions();
//        dumperOptions.setPrettyFlow(true);
        dumperOptions.setDefaultFlowStyle(FlowStyle.BLOCK);
        Yaml yaml = new Yaml(dumperOptions);
        yaml.dump(myMap, sw);

//        yamlConfiguration.dump(sw, new DumperOptions());
        System.out.println(sw.toString());
    }
 
Example #10
Source File: EmitterMultiLineTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
public void testWriteMultiLineList() {
    String one = "first\nsecond\nthird";
    String two = "one\ntwo\nthree\n";
    byte[] binary = { 8, 14, 15, 10, 126, 32, 65, 65, 65 };
    List<Object> list = new ArrayList<Object>(2);
    list.add(one);
    list.add(two);
    list.add(binary);
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(FlowStyle.BLOCK);
    Yaml yaml = new Yaml(options);
    String output = yaml.dump(list);
    // System.out.println(output);
    String etalon = "- |-\n  first\n  second\n  third\n- |\n  one\n  two\n  three\n- !!binary |-\n  CA4PCn4gQUFB\n";
    assertEquals(etalon, output);
    @SuppressWarnings("unchecked")
    List<Object> parsed = (List<Object>) yaml.load(etalon);
    assertEquals(3, parsed.size());
    assertEquals(one, parsed.get(0));
    assertEquals(two, parsed.get(1));
    assertEquals(new String(binary), new String((byte[]) parsed.get(2)));
}
 
Example #11
Source File: JavaBeanTimeStampTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
public void testLoadDefaultJavaSqlTimestamp() {
    JavaBeanWithSqlTimestamp javaBeanToDump = new JavaBeanWithSqlTimestamp();
    Timestamp stamp = new Timestamp(1000000000000L);
    javaBeanToDump.setTimestamp(stamp);
    Date date = new Date(1001376000000L);
    javaBeanToDump.setDate(date);
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(FlowStyle.BLOCK);
    Yaml yaml = new Yaml(options);
    String dumpStr = yaml.dump(javaBeanToDump);
    assertEquals(
            "!!org.yaml.snakeyaml.JavaBeanWithSqlTimestamp\ndate: 2001-09-25T00:00:00Z\ntimestamp: 2001-09-09T01:46:40Z\n",
            dumpStr);
    Yaml loader = new Yaml();
    JavaBeanWithSqlTimestamp javaBeanToLoad = loader.loadAs(dumpStr,
            JavaBeanWithSqlTimestamp.class);
    assertEquals(stamp, javaBeanToLoad.getTimestamp());
    assertEquals(date, javaBeanToLoad.getDate());
}
 
Example #12
Source File: XmlBuildSpecMigrator.java    From onedev with MIT License 6 votes vote down vote up
private static Node migrateDefaultValueProvider(Element defaultValueProviderElement) {
	List<NodeTuple> tuples = new ArrayList<>();
	String classTag = getClassTag(defaultValueProviderElement.attributeValue("class"));
	Element scriptNameElement = defaultValueProviderElement.element("scriptName");
	if (scriptNameElement != null) {
		tuples.add(new NodeTuple(
				new ScalarNode(Tag.STR, "scriptName"), 
				new ScalarNode(Tag.STR, scriptNameElement.getText().trim())));
	}
	Element valueElement = defaultValueProviderElement.element("value");
	if (valueElement != null) {
		tuples.add(new NodeTuple(
				new ScalarNode(Tag.STR, "value"), 
				new ScalarNode(Tag.STR, valueElement.getText().trim())));
	}
	
	return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
 
Example #13
Source File: XmlBuildSpecMigrator.java    From onedev with MIT License 6 votes vote down vote up
private static Node migrateDefaultMultiValueProvider(Element defaultMultiValueProviderElement) {
	List<NodeTuple> tuples = new ArrayList<>();
	String classTag = getClassTag(defaultMultiValueProviderElement.attributeValue("class"));
	Element scriptNameElement = defaultMultiValueProviderElement.element("scriptName");
	if (scriptNameElement != null) {
		tuples.add(new NodeTuple(
				new ScalarNode(Tag.STR, "scriptName"), 
				new ScalarNode(Tag.STR, scriptNameElement.getText().trim())));
	}
	Element valueElement = defaultMultiValueProviderElement.element("value");
	if (valueElement != null) {
		List<Node> valueItemNodes = new ArrayList<>();
		for (Element valueItemElement: valueElement.elements())
			valueItemNodes.add(new ScalarNode(Tag.STR, valueItemElement.getText().trim()));
		tuples.add(new NodeTuple(
				new ScalarNode(Tag.STR, "value"), 
				new SequenceNode(Tag.SEQ, valueItemNodes, FlowStyle.BLOCK)));
	}
	
	return new MappingNode(new Tag(classTag), tuples, FlowStyle.BLOCK);
}
 
Example #14
Source File: BaseRepresenter.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
protected Node representSequence(Tag tag, Iterable<?> sequence, Boolean flowStyle) {
    int size = 10;// default for ArrayList
    if (sequence instanceof List<?>) {
        size = ((List<?>) sequence).size();
    }
    List<Node> value = new ArrayList<Node>(size);
    SequenceNode node = new SequenceNode(tag, value, flowStyle);
    representedObjects.put(objectToRepresent, node);
    boolean bestStyle = true;
    for (Object item : sequence) {
        Node nodeItem = representData(item);
        if (!((nodeItem instanceof ScalarNode && ((ScalarNode) nodeItem).getStyle() == null))) {
            bestStyle = false;
        }
        value.add(nodeItem);
    }
    if (flowStyle == null) {
        if (defaultFlowStyle != FlowStyle.AUTO) {
            node.setFlowStyle(defaultFlowStyle.getStyleBoolean());
        } else {
            node.setFlowStyle(bestStyle);
        }
    }
    return node;
}
 
Example #15
Source File: BaseRepresenter.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
protected Node representMapping(Tag tag, Map<?, ?> mapping, Boolean flowStyle) {
    List<NodeTuple> value = new ArrayList<NodeTuple>(mapping.size());
    MappingNode node = new MappingNode(tag, value, flowStyle);
    representedObjects.put(objectToRepresent, node);
    boolean bestStyle = true;
    for (Map.Entry<?, ?> entry : mapping.entrySet()) {
        Node nodeKey = representData(entry.getKey());
        Node nodeValue = representData(entry.getValue());
        if (!((nodeKey instanceof ScalarNode && ((ScalarNode) nodeKey).getStyle() == null))) {
            bestStyle = false;
        }
        if (!((nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null))) {
            bestStyle = false;
        }
        value.add(new NodeTuple(nodeKey, nodeValue));
    }
    if (flowStyle == null) {
        if (defaultFlowStyle != FlowStyle.AUTO) {
            node.setFlowStyle(defaultFlowStyle.getStyleBoolean());
        } else {
            node.setFlowStyle(bestStyle);
        }
    }
    return node;
}
 
Example #16
Source File: SingleQuoteTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
private void checkQuotes(boolean isBlock, String expectation) {
    DumperOptions options = new DumperOptions();
    options.setIndent(4);
    if (isBlock) {
        options.setDefaultFlowStyle(FlowStyle.BLOCK);
    }
    Representer representer = new Representer();

    Yaml yaml = new Yaml(new SafeConstructor(), representer, options);

    LinkedHashMap<String, Object> lvl1 = new LinkedHashMap<String, Object>();
    lvl1.put("steak:cow", "11");
    LinkedHashMap<String, Object> root = new LinkedHashMap<String, Object>();
    root.put("cows", lvl1);
    String output = yaml.dump(root);
    assertEquals(expectation + "\n", output);

    // parse the value back
    @SuppressWarnings("unchecked")
    Map<String, Object> cows = (Map<String, Object>) yaml.load(output);
    @SuppressWarnings("unchecked")
    Map<String, String> cow = (Map<String, String>) cows.get("cows");
    assertEquals("11", cow.get("steak:cow"));
}
 
Example #17
Source File: BoolTagTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
/**
 * test block style
 */
public void testBoolOutAsEmpty3() {
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(FlowStyle.BLOCK);
    Yaml yaml = new Yaml(new BoolRepresenter("True"), options);
    Map<String, Boolean> map = new HashMap<String, Boolean>();
    map.put("aaa", false);
    map.put("bbb", true);
    String output = yaml.dump(map);
    assertEquals("aaa: false\nbbb: True\n", output);
}
 
Example #18
Source File: ArrayTagsTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testFlowBlock() {
    CarWithArray car = new CarWithArray();
    car.setPlate("12-XP-F4");
    Wheel[] wheels = new Wheel[5];
    for (int i = 1; i < 6; i++) {
        Wheel wheel = new Wheel();
        wheel.setId(i);
        wheels[i - 1] = wheel;
    }
    car.setWheels(wheels);
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(FlowStyle.BLOCK);
    Yaml yaml = new Yaml(options);
    assertEquals(Util.getLocalResource("constructor/cararray-with-tags.yaml"), yaml.dump(car));
}
 
Example #19
Source File: EmitterTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testWriteIndicatorIndent() {
    DumperOptions options = new DumperOptions();
    options.setIndent(5);
    options.setIndicatorIndent(2);
    options.setDefaultFlowStyle(FlowStyle.BLOCK);
    List<?> topLevel = Arrays.asList(Collections.singletonMap("k1", "v1"), Collections.singletonMap("k2", "v2"));
    Map<String, ?> map = Collections.singletonMap("aaa", topLevel);
    Yaml yaml = new Yaml(options);
    String output = yaml.dump(map);
    String etalon = "aaa:\n  -  k1: v1\n  -  k2: v2\n";
    assertEquals(etalon, output);
}
 
Example #20
Source File: HouseTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
/**
 * with global root class tag (global tag should be avoided)
 */
public void testDump2() {
    House house = new House();
    FrontDoor frontDoor = new FrontDoor("qaz1", 5);
    frontDoor.setKeytype("qwerty123");
    house.setFrontDoor(frontDoor);
    List<Room> rooms = new ArrayList<Room>();
    rooms.add(new Room("Hall"));
    rooms.add(new Room("Kitchen"));
    house.setRooms(rooms);
    Map<String, String> reminders = new TreeMap<String, String>();
    reminders.put("today", "do nothig");
    reminders.put("tomorrow", "go shoping");
    house.setReminders(reminders);
    house.setNumber(1);
    house.setStreet("Wall Street");
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(FlowStyle.BLOCK);
    Yaml beanDumper = new Yaml(options);
    String yaml = beanDumper.dump(house);
    String etalon = Util.getLocalResource("javabeans/house-dump2.yaml");
    assertEquals(etalon, yaml);
    // load
    Yaml beanLoader = new Yaml();
    House loadedHouse = beanLoader.loadAs(yaml, House.class);
    assertNotNull(loadedHouse);
    assertEquals("Wall Street", loadedHouse.getStreet());
    // dump again
    String yaml3 = beanDumper.dump(loadedHouse);
    assertEquals(yaml, yaml3);
}
 
Example #21
Source File: NullTagTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
/**
 * test block style
 */
public void testBoolOutAsEmpty3() {
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(FlowStyle.BLOCK);
    Yaml yaml = new Yaml(new NullRepresenter(), options);
    Map<String, String> map = new HashMap<String, String>();
    map.put("aaa", "foo");
    map.put("bbb", null);
    String output = yaml.dump(map);
    assertEquals("aaa: foo\nbbb:\n", output);
}
 
Example #22
Source File: Representer.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
/**
 * Tag logic:<br>
 * - explicit root tag is set in serializer <br>
 * - if there is a predefined class tag it is used<br>
 * - a global tag with class name is always used as tag. The JavaBean parent
 * of the specified JavaBean may set another tag (tag:yaml.org,2002:map)
 * when the property class is the same as runtime class
 *
 * @param properties
 *            JavaBean getters
 * @param javaBean
 *            instance for Node
 * @return Node to get serialized
 */
protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
    List<NodeTuple> value = new ArrayList<NodeTuple>(properties.size());
    Tag tag;
    Tag customTag = classTags.get(javaBean.getClass());
    tag = customTag != null ? customTag : new Tag(javaBean.getClass());
    // flow style will be chosen by BaseRepresenter
    MappingNode node = new MappingNode(tag, value, null);
    representedObjects.put(javaBean, node);
    boolean bestStyle = true;
    for (Property property : properties) {
        Object memberValue = property.get(javaBean);
        Tag customPropertyTag = memberValue == null ? null : classTags.get(memberValue
                .getClass());
        NodeTuple tuple = representJavaBeanProperty(javaBean, property, memberValue,
                customPropertyTag);
        if (tuple == null) {
            continue;
        }
        if (((ScalarNode) tuple.getKeyNode()).getStyle() != null) {
            bestStyle = false;
        }
        Node nodeValue = tuple.getValueNode();
        if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null)) {
            bestStyle = false;
        }
        value.add(tuple);
    }
    if (defaultFlowStyle != FlowStyle.AUTO) {
        node.setFlowStyle(defaultFlowStyle.getStyleBoolean());
    } else {
        node.setFlowStyle(bestStyle);
    }
    return node;
}
 
Example #23
Source File: EmitterMultiLineTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testWriteMultiLineQuotedInFlowContext() {
    String source = "{a: 1, b: 'mama\n\n    mila\n\n    ramu'}\n";
    // System.out.println("Source:\n" + source);
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(FlowStyle.FLOW);
    Yaml yaml = new Yaml(options);
    @SuppressWarnings("unchecked")
    Map<String, Object> parsed = (Map<String, Object>) yaml.load(source);
    String value = (String) parsed.get("b");
    // System.out.println(value);
    assertEquals("mama\nmila\nramu", value);
    String dumped = yaml.dump(parsed);
    // System.out.println(dumped);
    assertEquals("{a: 1, b: \"mama\\nmila\\nramu\"}\n", dumped);
}
 
Example #24
Source File: DumpSetAsSequenceExampleTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testDumpBlock() {
    DumperOptions options = new DumperOptions();
    options.setAllowReadOnlyProperties(true);
    options.setDefaultFlowStyle(FlowStyle.BLOCK);
    Yaml yaml = new Yaml(new SetRepresenter(), options);
    String output = yaml.dump(createBlog());
    // System.out.println(output);
    assertEquals(Util.getLocalResource("issues/issue73-dump8.txt"), output);
    //
    check(output);
}
 
Example #25
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 #26
Source File: DumpTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testDumperNullTag() {
    Yaml yaml = new Yaml();
    Bean124 bean = new Bean124();
    String output1 = yaml.dumpAs(bean, null, FlowStyle.BLOCK);
    assertEquals(
            "!!org.yaml.snakeyaml.issues.issue124.Bean124\na: aaa\nnumbers:\n- 1\n- 2\n- 3\n",
            output1);
}
 
Example #27
Source File: HumanTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testNoChildrenPretty() {
    Human father = new Human();
    father.setName("Father");
    father.setBirthday(new Date(1000000000));
    father.setBirthPlace("Leningrad");
    father.setBankAccountOwner(father);
    Human mother = new Human();
    mother.setName("Mother");
    mother.setBirthday(new Date(100000000000L));
    mother.setBirthPlace("Saint-Petersburg");
    father.setPartner(mother);
    mother.setPartner(father);
    mother.setBankAccountOwner(father);
    DumperOptions options = new DumperOptions();
    options.setPrettyFlow(true);
    options.setDefaultFlowStyle(FlowStyle.FLOW);
    Yaml yaml = new Yaml(options);
    String output = yaml.dump(father);
    String etalon = Util.getLocalResource("recursive/no-children-1-pretty.yaml");
    assertEquals(etalon, output);
    //
    Human father2 = (Human) yaml.load(output);
    assertNotNull(father2);
    assertEquals("Father", father2.getName());
    assertEquals("Mother", father2.getPartner().getName());
    assertEquals("Father", father2.getBankAccountOwner().getName());
    assertSame(father2, father2.getBankAccountOwner());
}
 
Example #28
Source File: YamlOrderedSkipEmptyRepresenter.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
@Override
protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
    List<NodeTuple> value = new ArrayList<>(properties.size());
    Tag tag;
    Tag customTag = classTags.get(javaBean.getClass());
    tag = customTag != null ? customTag : new Tag(javaBean.getClass());
    MappingNode node = new MappingNode(tag, value, FlowStyle.BLOCK);
    representedObjects.put(javaBean, node);

    List<Property> orderProperties = new ArrayList<>(properties);
    orderProperties.sort(sorter);

    for (Property property : orderProperties) {
        Object memberValue = property.get(javaBean);
        Tag customPropertyTag = memberValue == null ? null
            : classTags.get(memberValue.getClass());
        NodeTuple tuple = representJavaBeanProperty(javaBean, property, memberValue,
            customPropertyTag);
        if (tuple == null) {
            continue;
        }

        value.add(tuple);
    }

    return node;
}
 
Example #29
Source File: SkriptYamlRepresenter.java    From skript-yaml with MIT License 5 votes vote down vote up
@SuppressWarnings({ "unchecked" })
public <T> T representMapping(Tag tag, Map<?, ?> mapping) {
	if (SkriptYaml.getInstance().getServerVersion() >= 13) {
		return (T) representMapping(tag, mapping, FlowStyle.BLOCK);
	} else {
		T node = null;
           try {
   			node = (T) representMappingMethod.invoke(this, tag, mapping, null);
           } catch (SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
           	e.printStackTrace();
           }
		return (T) node;
	}
}
 
Example #30
Source File: DumpTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testDumperNullStyle2() {
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(FlowStyle.BLOCK);
    Yaml yaml = new Yaml(options);
    Bean124 bean = new Bean124();
    String output1 = yaml.dumpAs(bean, new Tag("!!foo2.bar2"), null);
    assertEquals("!!foo2.bar2\na: aaa\nnumbers:\n- 1\n- 2\n- 3\n", output1);
}