Java Code Examples for org.yaml.snakeyaml.DumperOptions#setDefaultFlowStyle()

The following examples show how to use org.yaml.snakeyaml.DumperOptions#setDefaultFlowStyle() . 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: 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 2
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 3
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 4
Source File: Config.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
private void parseContent(String content) {
    switch (this.type) {
        case Config.PROPERTIES:
            this.parseProperties(content);
            break;
        case Config.JSON:
            GsonBuilder builder = new GsonBuilder();
            Gson gson = builder.create();
            this.config = new ConfigSection(gson.fromJson(content, new TypeToken<LinkedHashMap<String, Object>>() {
            }.getType()));
            break;
        case Config.YAML:
            DumperOptions dumperOptions = new DumperOptions();
            dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
            Yaml yaml = new Yaml(dumperOptions);
            this.config = new ConfigSection(yaml.loadAs(content, LinkedHashMap.class));
            break;
        // case Config.SERIALIZED
        case Config.ENUM:
            this.parseList(content);
            break;
        default:
            this.correct = false;
    }
}
 
Example 5
Source File: HelmPackage.java    From gradle-plugins with Apache License 2.0 6 votes vote down vote up
private void applyValues(File templatedDir) throws IOException {
	File valuesFile = new File(templatedDir, "values.yaml");


	DumperOptions options = new DumperOptions();
	options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
	Yaml yaml = new Yaml(options);
	Map data;
	try (FileReader reader = new FileReader(valuesFile)) {
		data = yaml.load(reader);
	}

	for (Map.Entry<String, Object> entry : values.entrySet()) {
		List<String> key = Arrays.asList(entry.getKey().split("\\."));
		putValue(data, key, entry.getValue());
	}

	try (FileWriter writer = new FileWriter(valuesFile)) {
		yaml.dump(data, writer);
	}
}
 
Example 6
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 7
Source File: SafeRepresenterTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
public void testDate() {
    List<Date> list = new ArrayList<Date>();
    list.add(new Date(1229684761159L));
    list.add(new Date(1229684761059L));
    list.add(new Date(1229684761009L));
    list.add(new Date(1229684761150L));
    list.add(new Date(1229684761100L));
    list.add(new Date(1229684761000L));
    list.add(new Date(1229684760000L));
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    Yaml yaml = new Yaml(options);
    String output = yaml.dump(list);
    assertEquals(
            "- 2008-12-19T11:06:01.159Z\n- 2008-12-19T11:06:01.059Z\n- 2008-12-19T11:06:01.009Z\n- 2008-12-19T11:06:01.150Z\n- 2008-12-19T11:06:01.100Z\n- 2008-12-19T11:06:01Z\n- 2008-12-19T11:06:00Z\n",
            output);
}
 
Example 8
Source File: YAMLImportExport.java    From thunderstorm with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void exportToFile(String fp, int floatPrecision, GenericTable table, List<String> columns) throws IOException {
    assert(table != null);
    assert(fp != null);
    assert(!fp.isEmpty());
    assert(columns != null);
    
    int nrows = table.getRowCount();

    DecimalFormat df = StringFormatting.getDecimalFormat(floatPrecision);
    
    ArrayList<HashMap<String, String>> results = new ArrayList<>();
    for(int r = 0; r < nrows; r++) {
        HashMap<String, String> molecule = new HashMap<>();
        for (String column : columns) {
            molecule.put(table.getColumnLabel(column), df.format(table.getValue(r, column)));
        }
        results.add(molecule);
        IJ.showProgress((double)r / (double)nrows);
    }

    BufferedWriter writer = new BufferedWriter(new FileWriter(fp));
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    Yaml yaml = new Yaml(options);
    writer.write(yaml.dump(results));
    writer.close();
}
 
Example 9
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);
}
 
Example 10
Source File: Config.java    From Nemisys with 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 11
Source File: Config.java    From BukkitPE with GNU General Public License v3.0 5 votes vote down vote up
private void parseContent(String content) {
    switch (this.type) {
        case Config.PROPERTIES:
            this.parseProperties(content);
            break;
        case Config.JSON:
            GsonBuilder builder = new GsonBuilder();
            Gson gson = builder.create();
            this.config = new ConfigSection(gson.fromJson(content, new TypeToken<LinkedHashMap<String, Object>>() {
            }.getType()));
            break;
        case Config.YAML:
            DumperOptions dumperOptions = new DumperOptions();
            dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
            Yaml yaml = new Yaml(dumperOptions);
            this.config = new ConfigSection(yaml.loadAs(content, LinkedHashMap.class));
            if (this.config == null) {
                this.config = new ConfigSection();
            }
            break;
        // case Config.SERIALIZED
        case Config.ENUM:
            this.parseList(content);
            break;
        default:
            this.correct = false;
    }
}
 
Example 12
Source File: ConfigurationFileBuilder.java    From smart-testing with Apache License 2.0 5 votes vote down vote up
void writeTo(Path filePath) {
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    options.setPrettyFlow(true);

    Yaml yaml = new Yaml(options);
    try {
        FileWriter writer = new FileWriter(filePath.toString());
        yaml.dump(properties, writer);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 13
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 14
Source File: YamlFormatter.java    From structlog4j with MIT License 5 votes vote down vote up
@Override
protected Yaml initialValue() {
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    options.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);

    return new Yaml(options);
}
 
Example 15
Source File: Config.java    From Nemisys with GNU General Public License v3.0 5 votes vote down vote up
private void parseContent(String content) {
    switch (this.type) {
        case Config.PROPERTIES:
            this.parseProperties(content);
            break;
        case Config.JSON:
            GsonBuilder builder = new GsonBuilder();
            Gson gson = builder.create();
            this.config = new ConfigSection(gson.fromJson(content, new TypeToken<LinkedHashMap<String, Object>>() {
            }.getType()));
            break;
        case Config.YAML:
            DumperOptions dumperOptions = new DumperOptions();
            dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
            Yaml yaml = new Yaml(dumperOptions);
            this.config = new ConfigSection(yaml.loadAs(content, LinkedHashMap.class));
            if (this.config == null) {
                this.config = new ConfigSection();
            }
            break;
        // case Config.SERIALIZED
        case Config.ENUM:
            this.parseList(content);
            break;
        default:
            this.correct = false;
    }
}
 
Example 16
Source File: BeanConstructorTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testPrimitivesConstructor() {
    Yaml yaml = new Yaml(new Constructor(TestBean1.class));
    String document = Util.getLocalResource("constructor/test-primitives1.yaml");
    TestBean1 result = (TestBean1) yaml.load(document);
    assertNotNull(result);
    assertEquals(new Byte((byte) 1), result.getByteClass());
    assertEquals((byte) -3, result.getBytePrimitive());
    assertEquals(new Short((short) 0), result.getShortClass());
    assertEquals((short) -13, result.getShortPrimitive());
    assertEquals(new Integer(5), result.getInteger());
    assertEquals(17, result.getIntPrimitive());
    assertEquals("the text", result.getText());
    assertEquals("13", result.getId());
    assertEquals(new Long(11111111111L), result.getLongClass());
    assertEquals(9999999999L, result.getLongPrimitive());
    assertEquals(Boolean.TRUE, result.getBooleanClass());
    assertTrue(result.isBooleanPrimitive());
    assertEquals(Character.valueOf('2'), result.getCharClass());
    assertEquals('#', result.getCharPrimitive());
    assertEquals(new BigInteger("1234567890123456789012345678901234567890"),
            result.getBigInteger());
    assertEquals(new Float(2), result.getFloatClass());
    assertEquals(new Float(3.1416), result.getFloatPrimitive());
    assertEquals(new Double(4), result.getDoubleClass());
    assertEquals(new Double(11200), result.getDoublePrimitive());
    assertEquals(1199836800000L, result.getDate().getTime());
    assertEquals("public", result.publicField);
    //
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    Yaml yamlToDump = new Yaml(options);
    String output = yamlToDump.dump(result);
    TestBean1 result2 = (TestBean1) yaml.load(output);
    assertNotNull(result2);
    TestBean1 result3 = (TestBean1) new Yaml().load(output);
    assertNotNull(result3);
}
 
Example 17
Source File: Config.java    From BukkitPE with 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
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 19
Source File: ProjectConfigurator.java    From smart-testing with Apache License 2.0 5 votes vote down vote up
private void dumpConfiguration(Path configFilePath) {
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW);

    Representer representer = new Representer() {
        @Override
        protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
            Tag customTag) {
            // if value of property is null, ignore it.
            if (propertyValue == null) {
                return null;
            } else {
                return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
            }
        }
    };

    representer.addClassTag(Configuration.class, Tag.MAP);

    Yaml yaml = new Yaml(representer, options);
    String config = yaml.dump(configuration);

    for (TestExecutionPlannerFactory factory : new JavaSPILoader().all(TestExecutionPlannerFactory.class)) {
        StrategyConfiguration strategyConfig = factory.strategyConfiguration();
        config = config.replaceAll("!!" + strategyConfig.getClass().getName(), strategyConfig.name() + ":");
    }
    try {
        Files.write(configFilePath, config.getBytes());
    } catch (IOException e) {
        throw new RuntimeException("Failed to dump configuration in file " + configFilePath, e);
    }
}
 
Example 20
Source File: PluginDescription.java    From Jupiter with GNU General Public License v3.0 4 votes vote down vote up
public PluginDescription(String yamlString) {
    DumperOptions dumperOptions = new DumperOptions();
    dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    Yaml yaml = new Yaml(dumperOptions);
    this.loadMap(yaml.loadAs(yamlString, LinkedHashMap.class));
}