org.yaml.snakeyaml.DumperOptions Java Examples

The following examples show how to use org.yaml.snakeyaml.DumperOptions. 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: ConfigViewFactory.java    From thorntail with Apache License 2.0 7 votes vote down vote up
private static Yaml newYaml(Map<String, String> environment) {
    return new Yaml(new EnvironmentConstructor(environment),
                    new Representer(),
                    new DumperOptions(),
                    new Resolver() {
                        @Override
                        public Tag resolve(NodeId kind, String value, boolean implicit) {
                            if (value != null) {
                                if (value.startsWith("${env.")) {
                                    return new Tag("!env");
                                }
                                if (value.equalsIgnoreCase("on") ||
                                        value.equalsIgnoreCase("off") ||
                                        value.equalsIgnoreCase("yes") ||
                                        value.equalsIgnoreCase("no")) {
                                    return Tag.STR;
                                }
                            }
                            return super.resolve(kind, value, implicit);
                        }
                    });
}
 
Example #2
Source File: ArgumentSanitizer.java    From spring-cloud-skipper with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #3
Source File: YAMLProcessor.java    From skript-yaml with MIT License 6 votes vote down vote up
public YAMLProcessor(File file, boolean writeDefaults, YAMLFormat format) {
	super(new LinkedHashMap<String, Object>(), writeDefaults);
	this.format = format;

	DumperOptions options = new FancyDumperOptions();
	options.setIndent(4);
	options.setDefaultFlowStyle(format.getStyle());
	options.setTimeZone(TimeZone.getDefault());

	//Representer representer = new SkriptYamlRepresenter();
	Representer representer = SkriptYaml.getInstance().getRepresenter();
	representer.setDefaultFlowStyle(format.getStyle());

	//yaml = new Yaml(new SkriptYamlConstructor(), representer, options);
	yaml = new Yaml(SkriptYaml.getInstance().getConstructor(), representer, options);
	
	this.file = file;
}
 
Example #4
Source File: Utils.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
/**
 * Create the CLI configuration information file.
 *
 * @param configuration instance containing the Configuration information.
 */
public static void createConfigurationFile(Configuration configuration) {
    DumperOptions options = new DumperOptions();
    options.setPrettyFlow(true);
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    Yaml yaml = new Yaml(options);

    // dump to the file
    try (Writer writer = new OutputStreamWriter(new FileOutputStream(getConfigFilePath()),
            StandardCharsets.UTF_8)) {
        yaml.dump(configuration, writer);
    } catch (IOException e) {
        BrokerClientException brokerClientException = new BrokerClientException();
        brokerClientException.addMessage("error when creating the configuration file. " + e.getMessage());
        throw brokerClientException;
    }
}
 
Example #5
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 #6
Source File: AnchorGeneratorTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
public void testCustomGenerator() {
    List<Object> list = new ArrayList<Object>();
    list.add("data123");
    list.add(list);
    Yaml yaml1 = new Yaml();
    String output = yaml1.dump(list);
    assertEquals("&id001\n" +
            "- data123\n" +
            "- *id001\n", output);


    DumperOptions options = new DumperOptions();
    Yaml yaml2 = new Yaml(options);
    options.setAnchorGenerator(new Gener(3));
    String output2 = yaml2.dump(list);
    assertEquals("&list-id004\n" +
            "- data123\n" +
            "- *list-id004\n", output2);
}
 
Example #7
Source File: YamlConfiguration.java    From CloudNet with Apache License 2.0 6 votes vote down vote up
@Override
protected Yaml initialValue() {
    Representer representer = new Representer() {
        {
            representers.put(Configuration.class, new Represent() {
                @Override
                public Node representData(Object data) {
                    return represent(((Configuration) data).self);
                }
            });
        }
    };

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

    return new Yaml(new Constructor(), representer, options);
}
 
Example #8
Source File: YamlParser.java    From nexus-repository-helm with Eclipse Public License 1.0 6 votes vote down vote up
public Map<String, Object> load(InputStream is) throws IOException {
  checkNotNull(is);
  String data = IOUtils.toString(new UnicodeReader(is));

  Map<String, Object> map;

  try {
    Yaml yaml = new Yaml(new Constructor(), new Representer(),
        new DumperOptions(), new Resolver());
    map = yaml.load(data);
  }
  catch (YAMLException e) {
    map = (Map<String, Object>) mapper.readValue(data, Map.class);
  }
  return map;
}
 
Example #9
Source File: DefaultYamlConverter.java    From spring-cloud-skipper with Apache License 2.0 6 votes vote down vote up
private YamlConversionResult convert(Map<String, Collection<String>> properties) {
	if (properties.isEmpty()) {
		return YamlConversionResult.EMPTY;
	}

	YamlBuilder root = new YamlBuilder(mode, keyspaceList, status, YamlPath.EMPTY);
	for (Entry<String, Collection<String>> e : properties.entrySet()) {
		for (String v : e.getValue()) {
			root.addProperty(YamlPath.fromProperty(e.getKey()), v);
		}
	}

	Object object = root.build();

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

	Yaml yaml = new Yaml(options);
	String output = yaml.dump(object);
	return new YamlConversionResult(status, output);
}
 
Example #10
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 #11
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 #12
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 #13
Source File: WildFlySwarmManifest.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    Map<String,Object> data = new LinkedHashMap<String,Object>() {{
        if (asset != null) {
            put(ASSET, asset);
        }
        put(MAIN_CLASS, mainClass);
        put(HOLLOW, hollow);
        put(PROPERTIES, properties);
        put(MODULES, bootstrapModules);
        put(BOOTSTRAP_ARTIFACTS, bootstrapArtifacts);
        put(BUNDLE_DEPENDENCIES, bundleDependencies);
        put(DEPENDENCIES, dependencies);
    }};

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

    return yaml.dump(data);
}
 
Example #14
Source File: SafeRepresenterTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
public void testStyle() {
    List<Integer> list = new ArrayList<Integer>();
    list.add(new Integer(1));
    list.add(new Integer(1));
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("list", list);
    map.put("name", "Ubuntu");
    map.put("age", 5);
    DumperOptions options = new DumperOptions();
    options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED);
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    Yaml yaml = new Yaml(options);
    String output = yaml.dump(map);
    assertTrue(output.contains("\"age\": !!int \"5\""));
    assertTrue(output.contains("\"name\": \"Ubuntu\""));
    assertTrue(output.contains("- !!int \"1\""));
}
 
Example #15
Source File: BaseYAMLTestWriter.java    From ECTester with MIT License 5 votes vote down vote up
@Override
public void end() {
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    options.setPrettyFlow(true);
    Yaml yaml = new Yaml(options);

    Map<String, Object> result = new LinkedHashMap<>();
    result.put("testRun", testRun);
    String out = yaml.dump(result);

    output.println(out);
    output.println("---");
}
 
Example #16
Source File: DumpExampleTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testDumperOptionsFlowStyle() {
    List<Integer> data = new ArrayList<Integer>();
    for (int i = 0; i < 5; i++) {
        data.add(i);
    }
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    Yaml yaml = new Yaml(options);
    String output = yaml.dump(data);
    assertTrue(output.contains("- 0\n"));
    assertTrue(output.contains("- 1\n"));
    assertTrue(output.contains("- 4\n"));
}
 
Example #17
Source File: ConfigUtils.java    From incubator-heron with Apache License 2.0 5 votes vote down vote up
private static Yaml newYaml() {
  final DumperOptions options = new DumperOptions();
  options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
  options.setPrettyFlow(true);

  return new Yaml(options);
}
 
Example #18
Source File: DumpExampleTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testDumpMany() {
    List<Integer> docs = new ArrayList<Integer>();
    for (int i = 1; i < 4; i++) {
        docs.add(i);
    }
    DumperOptions options = new DumperOptions();
    options.setExplicitStart(true);
    Yaml yaml = new Yaml(options);
    String result = yaml.dumpAll(docs.iterator());
    assertNotNull(result);
    assertTrue(result.contains("--- 2"));
}
 
Example #19
Source File: YamlFileFixture.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
@Override
public String createContaining(String filename, Object data) {
    String file;
    if (data instanceof Map
            || data instanceof byte[]
            || data instanceof String) {
        file = valuesFileCreateContaining(filename, data);
    } else {
        String yamlStr = yaml.dumpAs(data, null, DumperOptions.FlowStyle.BLOCK);
        file = createContaining(filename, yamlStr);
    }
    return file;
}
 
Example #20
Source File: PluginBase.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void reloadConfig() {
    this.config = new Config(this.configFile);
    InputStream configStream = this.getResource("config.yml");
    if (configStream != null) {
        DumperOptions dumperOptions = new DumperOptions();
        dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        Yaml yaml = new Yaml(dumperOptions);
        try {
            this.config.setDefault(yaml.loadAs(Utils.readFile(this.configFile), LinkedHashMap.class));
        } catch (IOException e) {
            Server.getInstance().getLogger().logException(e);
        }
    }
}
 
Example #21
Source File: DumpExampleTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testDumpCustomJavaClass() {
    Hero hero = new Hero("Galain Ysseleg", -3, 2);
    DumperOptions options = new DumperOptions();
    options.setAllowReadOnlyProperties(true);
    Yaml yaml = new Yaml(options);
    String output = yaml.dump(hero);
    assertEquals("!!examples.Hero {hp: -3, name: Galain Ysseleg, sp: 2}\n", output);
}
 
Example #22
Source File: ExecutorModule.java    From docker-compose-executor with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
Yaml provideYaml() {
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    return new Yaml(options);
}
 
Example #23
Source File: GenerateTestPlanCommand.java    From testgrid with Apache License 2.0 5 votes vote down vote up
/**
 * Creates and returns a {@link Yaml} instance that
 * does not include null values when dumping a yaml object.
 *
 * @return {@link Yaml} instance
 */
private Yaml createYamlInstance() {
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    options.setPrettyFlow(true);
    return new Yaml(new NullRepresenter(), options);
}
 
Example #24
Source File: DatanodeIdYaml.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a yaml file using DatnodeDetails. This method expects the path
 * validation to be performed by the caller.
 *
 * @param datanodeDetails {@link DatanodeDetails}
 * @param path            Path to datnode.id file
 */
public static void createDatanodeIdFile(DatanodeDetails datanodeDetails,
                                        File path) throws IOException {
  DumperOptions options = new DumperOptions();
  options.setPrettyFlow(true);
  options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW);
  Yaml yaml = new Yaml(options);

  try (Writer writer = new OutputStreamWriter(
      new FileOutputStream(path), "UTF-8")) {
    yaml.dump(getDatanodeDetailsYaml(datanodeDetails), writer);
  }
}
 
Example #25
Source File: ConfigValueUtilsTests.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@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 #26
Source File: Serializer.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
public Serializer(Emitable emitter, Resolver resolver, DumperOptions opts, Tag rootTag) {
    this.emitter = emitter;
    this.resolver = resolver;
    this.explicitStart = opts.isExplicitStart();
    this.explicitEnd = opts.isExplicitEnd();
    if (opts.getVersion() != null) {
        this.useVersion = opts.getVersion();
    }
    this.useTags = opts.getTags();
    this.serializedNodes = new HashSet<Node>();
    this.anchors = new HashMap<Node, String>();
    this.lastAnchorId = 0;
    this.closed = null;
    this.explicitRoot = rootTag;
}
 
Example #27
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@VisibleForTesting
@Restricted(NoExternalUse.class)
public static void serializeYamlNode(Node root, Writer writer) throws IOException {
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(BLOCK);
    options.setDefaultScalarStyle(PLAIN);
    options.setSplitLines(true);
    options.setPrettyFlow(true);
    Serializer serializer = new Serializer(new Emitter(writer, options), new Resolver(),
            options, null);
    serializer.open();
    serializer.serialize(root);
    serializer.close();
}
 
Example #28
Source File: YAMLConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
public void dump(final Writer out, final DumperOptions options)
        throws ConfigurationException, IOException
{
    final Yaml yaml = new Yaml(options);
    yaml.dump(constructMap(getNodeModel().getNodeHandler().getRootNode()),
            out);
}
 
Example #29
Source File: PackageWriterTests.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
private Package createSimplePackage() throws IOException {
	Package pkg = new Package();

	// Add package metadata
	PackageMetadata packageMetadata = new PackageMetadata();
	packageMetadata.setName("myapp");
	packageMetadata.setVersion("1.0.0");
	packageMetadata.setMaintainer("bob");
	pkg.setMetadata(packageMetadata);

	// Add ConfigValues
	Map<String, String> map = new HashMap<>();
	map.put("foo", "bar");
	map.put("fiz", "faz");
	DumperOptions dumperOptions = new DumperOptions();
	dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
	dumperOptions.setPrettyFlow(true);
	Yaml yaml = new Yaml(dumperOptions);
	ConfigValues configValues = new ConfigValues();
	configValues.setRaw(yaml.dump(map));
	pkg.setConfigValues(configValues);

	// Add template
	Resource resource = new ClassPathResource("/org/springframework/cloud/skipper/io/generic-template.yml");
	String genericTempateData = StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset());
	Template template = new Template();
	template.setData(genericTempateData);
	template.setName(resource.getURL().toString());
	List<Template> templateList = new ArrayList<>();
	templateList.add(template);
	pkg.setTemplates(templateList);

	return pkg;
}
 
Example #30
Source File: UuidSupportTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
@Test
public void dumpBean() {
    BeanWithId bean = new BeanWithId();
    bean.setValue(3);
    UUID uuid = UUID.fromString("ac4877be-0c31-4458-a86e-0272efe1aaa8");
    bean.setId(uuid);
    Yaml yaml = new Yaml();
    String output = yaml.dumpAs(bean, Tag.MAP, DumperOptions.FlowStyle.BLOCK);
    String expected = Util.getLocalResource("issues/issue306-2.yaml");
    assertEquals(expected, output);
}