Java Code Examples for org.yaml.snakeyaml.Yaml

The following are top voted examples for showing how to use org.yaml.snakeyaml.Yaml. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openNaEF   File: AttrNameMapping.java   Source Code and License 8 votes vote down vote up
@Override
protected synchronized Map<String, Mapping> loadInner(Yaml yaml, InputStream is) throws ConfigurationException {
    Map<String, Map<String, Object>> flesh = yaml.loadAs(is, Map.class);
    Map<String, Mapping> config = new HashMap<>();

    for (Map.Entry<String, Map<String, Object>> entry : flesh.entrySet()) {
        Map<String, Object> rawMapping = entry.getValue();

        String contextName = entry.getKey();
        String mvoClassStr = (String) rawMapping.get("mvo");
        String dtoClassStr = (String) rawMapping.get("dto");
        Map<String, Map<String, String>> attrs = (Map<String, Map<String, String>>) rawMapping.get("attrs");
        try {
            Mapping mapping = new Mapping(contextName, mvoClassStr, dtoClassStr, attrs);
            config.put(contextName, mapping);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    return Collections.unmodifiableMap(config);
}
 
Example 2
Project: everywhere   File: ConfigController.java   Source Code and License 8 votes vote down vote up
public static void writeConfigToYaml(ConfigSetting configSetting) {
    try {
        Yaml yaml = new Yaml();
        String output = yaml.dump(configSetting);
        byte[] sourceByte = output.getBytes();
        File file = new File(Constants.CONFIG_FILEPATH);
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(sourceByte);
        fileOutputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 3
Project: RestyPass   File: ConfigurableServerContext.java   Source Code and License 7 votes vote down vote up
/**
 * 加载配置文件
 */
private void loadServerFromConfigFile() {
    InputStream inputStream = parseYamlFile(CONFIG_FILE_NAME, true);
    Yaml yaml = new Yaml();
    YamlServerConfig config = yaml.loadAs(inputStream, YamlServerConfig.class);

    List<YamlServerList> servers = config.servers;
    for (YamlServerList server : servers) {
        for (ServerInstance instance : server.getInstances()) {
            instance.setServiceName(server.getServiceName());
            instance.ready();
        }
        instanceMap.put(server.getServiceName(), server.getInstances());
    }
    log.info("成功加载server的配置文件:{},Server:{}", CONFIG_FILE_NAME, instanceMap);
}
 
Example 4
Project: Biliomi   File: UserSettingsProducer.java   Source Code and License 7 votes vote down vote up
@PostConstruct
private void initUserSettingsProducer() {
  try {
    File coreYml = new File(BiliomiContainer.getParameters().getConfigurationDir(), "core.yml");
    Yaml yamlInstance = new Yaml(new Constructor(YamlCoreSettings.class));
    yamlCoreSettings = yamlInstance.loadAs(new FileInputStream(coreYml), YamlCoreSettings.class);

    String updateMode = yamlCoreSettings.getBiliomi().getCore().getUpdateMode();
    // Somehow Yaml thinks "off" means "false"
    if (StringUtils.isEmpty(updateMode)) {
      this.updateMode = UpdateModeType.OFF;
    } else {
      this.updateMode = EnumUtils.toEnum(updateMode, UpdateModeType.class);
    }
  } catch (FileNotFoundException e) {
    this.yamlCoreSettings = new YamlCoreSettings();
    ObjectGraphs.initializeObjectGraph(this.yamlCoreSettings);
    this.updateMode = UpdateModeType.INSTALL;
    this.yamlCoreSettings.getBiliomi().getCore().setUpdateMode(this.updateMode.toString());
  }
}
 
Example 5
Project: prometheus-jdbc-exporter   File: JdbcConfigTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testConfigShouldBuildWithoutQueryRef() {
  JdbcConfig config = new JdbcConfig((Map<String, Object>) new Yaml().load("---\n" +
      "jobs:\n" +
      "- name: \"global\"\n" +
      "  connections:\n" +
      "  - url: jdbc\n" +
      "    username: sys\n" +
      "    password: sys\n" +
      "  queries:\n" +
      "  - name: jdbc\n" +
      "    values:\n" +
      "    - v1\n" +
      "    query: abc\n" +
      ""));
  assertNotNull(config);
}
 
Example 6
Project: spring-cloud-skipper   File: PackageTemplateTests.java   Source Code and License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testMustasche() throws IOException {
	Yaml yaml = new Yaml();
	Map model = (Map) yaml.load(valuesResource.getInputStream());
	String templateAsString = StreamUtils.copyToString(nestedMapResource.getInputStream(),
			Charset.defaultCharset());
	Template mustacheTemplate = Mustache.compiler().compile(templateAsString);
	String resolvedYml = mustacheTemplate.execute(model);
	Map map = (Map) yaml.load(resolvedYml);

	logger.info("Resolved yml = " + resolvedYml);
	assertThat(map).containsKeys("apiVersion", "deployment");
	Map deploymentMap = (Map) map.get("deployment");
	assertThat(deploymentMap).contains(entry("name", "time"))
			.contains(entry("count", 10));
	Map applicationProperties = (Map) deploymentMap.get("applicationProperties");
	assertThat(applicationProperties).contains(entry("log.level", "DEBUG"), entry("server.port", 8089));
	Map deploymentProperties = (Map) deploymentMap.get("deploymentProperties");
	assertThat(deploymentProperties).contains(entry("app.time.producer.partitionKeyExpression", "payload"),
			entry("app.log.spring.cloud.stream.bindings.input.consumer.maxAttempts", 5));
}
 
Example 7
Project: MediaTool   File: YamlConfigLoader.java   Source Code and License 6 votes vote down vote up
public static MediaToolConfig get(Path config)
{
    try {
        Yaml yaml = new Yaml();
        try (InputStream in = Files.newInputStream(config))
        {
            MediaToolConfig mediaConfig = yaml.loadAs(in, MediaToolConfig.class);
            if (logger.isInfoEnabled())
                logger.info("{}", mediaConfig.toString());
            return mediaConfig;
        }
    } catch (IOException oie) {
        logger.error("{}", oie.getMessage(), oie);
    }
    return null;
}
 
Example 8
Project: spring-cloud-skipper   File: DefaultYamlConverter.java   Source Code and License 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 9
Project: prometheus-jdbc-exporter   File: JdbcConfigTest.java   Source Code and License 6 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testConfigShouldFailIfJobQueryRefNonExistingQuery() {
  new JdbcConfig((Map<String, Object>) new Yaml().load("---\n" +
      "jobs:\n" +
      "- name: \"global\"\n" +
      "  connections:\n" +
      "  - url: jdbc\n" +
      "    username: sys\n" +
      "    password: sys\n" +
      "  queries:\n" +
      "  - name: jdbc\n" +
      "    values:\n" +
      "    - v1\n" +
      "    query_ref: abc\n" +
      ""));
}
 
Example 10
Project: spring-cloud-skipper   File: PackageReaderTests.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void assertTickTockPackage(Package pkg) {
	PackageMetadata metadata = pkg.getMetadata();
	assertThat(metadata.getApiVersion()).isEqualTo("skipper.spring.io/v1");
	assertThat(metadata.getKind()).isEqualTo("SkipperPackageMetadata");
	assertThat(metadata.getName()).isEqualTo("ticktock");
	assertThat(metadata.getVersion()).isEqualTo("1.0.0");
	assertThat(metadata.getPackageSourceUrl()).isEqualTo("https://example.com/dataflow/ticktock");
	assertThat(metadata.getPackageHomeUrl()).isEqualTo("http://example.com/dataflow/ticktock");
	Set<String> tagSet = convertToSet(metadata.getTags());
	assertThat(tagSet).hasSize(3).contains("stream", "time", "log");
	assertThat(metadata.getMaintainer()).isEqualTo("https://github.com/markpollack");
	assertThat(metadata.getDescription()).isEqualTo("The ticktock stream sends a time stamp and logs the value.");
	String rawYamlString = pkg.getConfigValues().getRaw();
	Yaml yaml = new Yaml();
	Map<String, String> valuesAsMap = (Map<String, String>) yaml.load(rawYamlString);
	assertThat(valuesAsMap).hasSize(2).containsEntry("foo", "bar").containsEntry("biz", "baz");

	assertThat(pkg.getDependencies()).hasSize(2);
	assertTimeOrLogPackage(pkg.getDependencies().get(0));
	assertTimeOrLogPackage(pkg.getDependencies().get(1));

}
 
Example 11
Project: DAWAreplicator   File: Main.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (args.length < 1) {
        System.out.println("Usage: <file.yml> [iffnit]");
        return;
    }

    Yaml yaml = new Yaml();
    try (InputStream in = Files.newInputStream(Paths.get(args[0]))) {
        Configuration config = yaml.loadAs(in, Configuration.class);
        System.out.println(config.toString());
    }

    if (args.length > 1 && args[1].equals("init")) {
        ReplicaInit replicaInit = new ReplicaInit();
        replicaInit.start();
    } else if (args.length > 1 && !args[1].equals("init")) {
        System.out.println("Usage: <file.yml> [init]");
    } else {
        ReplicaEvent replicaEvent = new ReplicaEvent();
        replicaEvent.start();
    }
}
 
Example 12
Project: cdep   File: V3Reader.java   Source Code and License 6 votes vote down vote up
@NotNull
public static io.cdep.cdep.yml.cdepmanifest.CDepManifestYml convertStringToManifest(@NotNull String content) {
  Yaml yaml = new Yaml(new Constructor(io.cdep.cdep.yml.cdepmanifest.v3.CDepManifestYml.class));
  io.cdep.cdep.yml.cdepmanifest.CDepManifestYml manifest;
  try {
    CDepManifestYml prior = (CDepManifestYml) yaml.load(
        new ByteArrayInputStream(content.getBytes(StandardCharsets
            .UTF_8)));
    prior.sourceVersion = CDepManifestYmlVersion.v3;
    manifest = convert(prior);
    require(manifest.sourceVersion == CDepManifestYmlVersion.v3);
  } catch (YAMLException e) {
    manifest = convert(V2Reader.convertStringToManifest(content));
  }
  return manifest;
}
 
Example 13
Project: cdep   File: TestCDep.java   Source Code and License 6 votes vote down vote up
@Test
public void testMissingGithubCoordinate() throws Exception {
  CDepYml config = new CDepYml();
  System.out.printf(new Yaml().dump(config));
  File yaml = new File(".test-files/runMathfu/cdep.yml");
  yaml.getParentFile().mkdirs();
  Files.write("builders: [cmake, cmakeExamples]\ndependencies:\n- compile: com.github.jomof:mathfoo:1.0.2-rev7\n",
      yaml, StandardCharsets.UTF_8);
  try {
    String result = main("-wf", yaml.getParent());
    System.out.printf(result);
    fail("Expected an exception");
  } catch (RuntimeException e) {
    assertThat(e).hasMessage("Could not resolve 'com.github.jomof:mathfoo:1.0.2-rev7'. It doesn't exist.");
  }
}
 
Example 14
Project: cdep   File: TestCDep.java   Source Code and License 6 votes vote down vote up
@Test
public void unfindableLocalFile() throws Exception {
  CDepYml config = new CDepYml();
  System.out.printf(new Yaml().dump(config));
  File yaml = new File(".test-files/unfindableLocalFile/cdep.yml");
  yaml.getParentFile().mkdirs();
  Files.write("builders: [cmake, cmakeExamples]\ndependencies:\n- compile: ../not-a-file/cdep-manifest.yml\n",
      yaml, StandardCharsets.UTF_8);

  try {
    main("-wf", yaml.getParent());
    fail("Expected failure");
  } catch (RuntimeException e) {
    assertThat(e).hasMessage("Could not resolve '../not-a-file/cdep-manifest.yml'. It doesn't exist.");
  }
}
 
Example 15
Project: cdep   File: TestCDep.java   Source Code and License 6 votes vote down vote up
@Test
public void sqlite() throws Exception {
  CDepYml config = new CDepYml();
  System.out.printf(new Yaml().dump(config));
  File yaml = new File(".test-files/firebase/cdep.yml");
  yaml.getParentFile().mkdirs();
  Files.write("builders: [cmake, cmakeExamples]\n"
          + "dependencies:\n"
          + "- compile: com.github.jomof:sqlite:3.16.2-rev45\n",
      yaml, StandardCharsets.UTF_8);
  String result1 = main("show", "manifest", "-wf", yaml.getParent());
  yaml.delete();
  Files.write(result1, yaml, StandardCharsets.UTF_8);
  System.out.print(result1);
  String result = main("-wf", yaml.getParent());
  System.out.printf(result);
}
 
Example 16
Project: JPRE   File: YamlConfig.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void reload() {
	Config.createConfigFile(this.file);

	DumperOptions dumperOptions = new DumperOptions();
	dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
	Yaml yaml = new Yaml(dumperOptions);
	try {
		this.list = yaml.loadAs(Utils.readFile(file), Map.class);
	} catch (IOException e) {
		e.printStackTrace();
	}

	if (this.list == null) {
		this.list = useSynchronization ? new Hashtable<>() : new HashMap<>();
	} else {
		this.list = useSynchronization ? new Hashtable<>(this.list) : new HashMap<>(this.list);
	}
}
 
Example 17
Project: TOSCAna   File: ResourceFileCreatorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testReplicationControllerCreation() {
    ResourceFileCreator resourceFileCreator = new ResourceFileCreator(Pod.getPods(TestNodeStacks.getLampNodeStacks(log)));

    HashMap<String, String> result = null;
    try {
        result = resourceFileCreator.create();
    } catch (JsonProcessingException e) {
        e.printStackTrace();
        fail();
    }

    String service = result.get(appServiceName);
    String deployment = result.get(appDeploymentName);
    Yaml yaml = new Yaml();
    serviceTest((Map) yaml.load(service));
    deploymentTest((Map) yaml.load(deployment));
}
 
Example 18
Project: datatree-adapters   File: YamlSnakeYaml.java   Source Code and License 6 votes vote down vote up
public YamlSnakeYaml() {

		// Representer
		ExtensibleRepresenter representer = new ExtensibleRepresenter();

		// Install Java / Apache Cassandra serializers
		addDefaultSerializers(representer);

		// Install MongoDB / BSON serializers
		tryToAddSerializers("io.datatree.dom.adapters.YamlSnakeYamlBsonSerializers", representer);

		// Create flow-style YAML mapper
		DumperOptions optionsNormal = new DumperOptions();
		optionsNormal.setDefaultFlowStyle(FlowStyle.FLOW);
		mapper = new Yaml(representer, optionsNormal);

		// Create "pretty" YAML mapper
		DumperOptions optionsPretty = new DumperOptions();
		optionsPretty.setDefaultFlowStyle(FlowStyle.BLOCK);
		prettyMapper = new Yaml(representer, optionsPretty);
	}
 
Example 19
Project: jijimaku   File: AppConfig.java   Source Code and License 6 votes vote down vote up
/**
 * Read user preferences from a YAML config file.
 */
public AppConfig(File configFile) {
  this.configFilePath = configFile.getAbsolutePath();

  // Parse YAML file
  try {
    Yaml yaml = new Yaml();
    String yamlStr = FileManager.fileAnyEncodingToString(configFile);
    configMap = (new HashMap<String, Object>()).getClass().cast(yaml.load(yamlStr));
  } catch (IOException | ClassCastException exc) {
    LOGGER.error("Problem reading YAML config {}", configFilePath);
    LOGGER.debug("Got exception", exc);
    throw new UnexpectedError();
  }

  // TODO: check type of array values(not done on cast)
  dictionary = getConfigValue("dictionary", String.class);
  definitionSize = getConfigValue("definitionSize", Integer.class);
  highlightColors = getConfigValue("highlightColors", (new ArrayList<String>()).getClass());
  displayOtherLemma = getConfigValue("displayOtherLemma", Boolean.class);
  ignoreFrequencies = getConfigValue("ignoreFrequencies", (new ArrayList<Integer>()).getClass());
  ignoreWords = getConfigValue("ignoreWords", (new ArrayList<String>()).getClass());

  properNouns = new HashMap<>();  // Ignore fo now
  assStyles = getConfigValue("assStyles", String.class);
}
 
Example 20
Project: everywhere   File: ConfigController.java   Source Code and License 5 votes vote down vote up
public static ConfigSetting readConfig() {
    ConfigSetting configSetting = null;
    try {
        InputStream configIs = Files.newInputStream(Paths.get(Constants.CONFIG_FILEPATH));
        Yaml yaml = new Yaml(new Constructor(ConfigSetting.class));
        configSetting = yaml.loadAs(configIs, ConfigSetting.class);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return configSetting;
}
 
Example 21
Project: prometheus-jdbc-exporter   File: JdbcConfigTest.java   Source Code and License 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testConfigShouldFailIfJobQueryValuesEmpty() {
  new JdbcConfig((Map<String, Object>) new Yaml().load("---\n" +
      "jobs:\n" +
      "- name: \"global\"\n" +
      "  connections:\n" +
      "  - url: jdbc\n" +
      "    username: sys\n" +
      "    password: sys\n" +
      "  queries:\n" +
      "  - name: jdbc\n" +
      "    values:\n" +
      ""));
}
 
Example 22
Project: device-bluetooth   File: YamlReaderSnakeImpl.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Map<String, Object> readYamlFileAsMap(File file) {
	try (FileInputStream fis = new FileInputStream(file)) {
		Yaml yaml = new Yaml();
		return (Map<String, Object>) yaml.load(fis);
	} catch (Exception ex) {
		logger.error("Exception occurs when reading Yaml file:" + file.getPath(), ex);
		throw new DataValidationException("Error parsing device profile from YAML: " + file.getPath());
	}
}
 
Example 23
Project: prometheus-jdbc-exporter   File: JdbcConfigTest.java   Source Code and License 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testConfigShouldFailIfJobQueriesEmpty() {
  new JdbcConfig((Map<String, Object>) new Yaml().load("---\n" +
      "jobs:\n" +
      "- name: \"global\"\n" +
      "  connections:\n" +
      "  - url: jdbc\n" +
      "    username: sys\n" +
      "    password: sys\n" +
      "  queries:\n" +
      ""));
}
 
Example 24
Project: flow-platform   File: NodeUtilYmlTest.java   Source Code and License 5 votes vote down vote up
@Test
public void should_create_node_by_string() throws Throwable {
    Node node = NodeUtil.buildFromYml(ymlContent, "flow");
    Assert.assertEquals("flow", node.getName());

    String yml = new Yaml().dump(node);
    Assert.assertNotNull(yml);
}
 
Example 25
Project: spring-cloud-skipper   File: PackageWriterTests.java   Source Code and License 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 26
Project: jmxpromo   File: Config.java   Source Code and License 5 votes vote down vote up
public static Config from(String configString) {
  try {
    Map<String, Object> newYamlConfig = (Map<String, Object>) new Yaml().load(configString);
    Config config = new Config();
    from(config, newYamlConfig);
    return config;
  } catch (Exception ex) {
    throw new RuntimeException("Error on loading config from string: " + configString, ex);
  }
}
 
Example 27
Project: pl   File: PluginYamlProducer.java   Source Code and License 5 votes vote down vote up
static String generate(Yaml yaml, PluginSpec from) throws Exception {
    Map<String, Object> data = new HashMap<>();
    data.put("main", from.getPluginClass());
    data.put("name", validateName(getName(from)));
    data.put("version", validateVersion(getVersion(from)));

    Putter<Pl, String, Object> putter = ifNotEmpty(from.getPl(), putter(data));
    putter.put("description", Pl::description);
    putter.put("authors", Pl::authors, a -> a.length != 0);
    putter.put("loadOn", y -> y.loadOn().name(), loadOn -> !loadOn.equals("POSTWORLD"));

    putter.put("depend", y -> Stream.of(y.depend())
                                    .filter(d -> !d.soft())
                                    .map(Dep::value)
                                    .collect(Collectors.toList()), list -> list.size() != 0);

    putter.put("softdepend", y -> Stream.of(y.depend())
                                        .filter(d -> d.soft())
                                        .map(Dep::value)
                                        .collect(Collectors.toList()), list -> list.size() != 0);
    putter.put("loadbefore", Pl::loadbefore, lb -> lb.length != 0);
    putter.put("prefix", Pl::prefix);
    putter.put("website", Pl::website);

    Map<String, Map<String, Object>> commandMap = new HashMap<>();
    putCommands(commandMap, from.getCommands());
    if (!commandMap.isEmpty())
        data.put("commands", commandMap);

    return yaml.dump(data);
}
 
Example 28
Project: cdep   File: TestCDep.java   Source Code and License 5 votes vote down vote up
@Test
public void noDependencies() throws Exception {
  CDepYml config = new CDepYml();
  System.out.printf(new Yaml().dump(config));
  File yaml = new File(".test-files/simpleDependency/cdep.yml");
  yaml.getParentFile().mkdirs();
  Files.write("builders: [cmake, cmakeExamples]\ndependencies:\n", yaml, StandardCharsets.UTF_8);
  String result1 = main("-wf", yaml.getParent());
  System.out.printf(result1);
  assertThat(result1).contains("Nothing");
}
 
Example 29
Project: CoreX   File: PluginBase.java   Source Code and License 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 30
Project: prometheus-jdbc-exporter   File: JdbcCollector.java   Source Code and License 5 votes vote down vote up
JdbcCollector(File in) throws FileNotFoundException {
  configFile = in;
  config =
      new JdbcConfig(
          (Map<String, Object>) new Yaml().load(new FileReader(in)),
          in.lastModified());
}
 
Example 31
Project: train-simulator   File: OriginalMapBuilder.java   Source Code and License 5 votes vote down vote up
public void MapImporter() throws IOException{
  Resource resource = new ClassPathResource("maps/basic.yaml");
  Yaml yaml = new Yaml();
  Map<String, Object> map = (Map<String, Object>) yaml.load(resource.getInputStream());

  Map<Integer, Object> tracks = (Map<Integer, Object>) map.get("tracks");

  /**/
}
 
Example 32
Project: train-simulator   File: MapImporterTest.java   Source Code and License 5 votes vote down vote up
@Test
public void readYaml() {
  Yaml yaml = new Yaml();
  String document = "\n- Hesperiidae\n- Papilionidae\n- Apatelodidae\n- Epiplemidae";
  List<String> list = (List<String>) yaml.load(document);
  //System.out.println(list);
}
 
Example 33
Project: train-simulator   File: MapImporterTest.java   Source Code and License 5 votes vote down vote up
@Test
public void readYamlFile() throws IOException {
  Resource resource = new ClassPathResource("maps/basic.yaml");
  Yaml yaml = new Yaml();
  Map<String, Object> list = (Map<String, Object>) yaml.load(resource.getInputStream());

  //System.out.println(list);
}
 
Example 34
Project: Biliomi   File: ConfigService.java   Source Code and License 5 votes vote down vote up
public ConfigService(String configPath, Class<T> constructorClass) {
  T loadedConfig = null;
  File file = new File(BiliomiContainer.getParameters().getConfigurationDir(), configPath);
  Yaml yaml = new Yaml(new Constructor(constructorClass));

  try {
    loadedConfig = yaml.loadAs(new FileInputStream(file), constructorClass);
  } catch (FileNotFoundException e) {
    LogManager.getLogger(getClass().getName()).error("Failed loading module configuration from " + file.getAbsolutePath());
  }

  this.config = loadedConfig;
}
 
Example 35
Project: flow-platform   File: NodeUtil.java   Source Code and License 5 votes vote down vote up
/**
 * Verify and create node tree by yml
 *
 * @param yml raw yml string
 * @return root node of yml
 * @throws YmlException if yml format is illegal
 */
public static Node buildFromYml(String yml, String rootName) {
    try {
        Yaml yaml = new Yaml(ROOT_YML_CONSTRUCTOR);
        RootYmlWrapper node = yaml.load(yml);

        // verify flow node
        if (Objects.isNull(node.flow)) {
            throw new YmlException("The 'flow' content must be defined");
        }

        // current version only support single flow
        if (node.flow.size() > 1) {
            throw new YmlException("Unsupported multiple flows definition");
        }

        // steps must be provided
        List<NodeWrapper> steps = node.flow.get(0).steps;
        if (Objects.isNull(steps) || steps.isEmpty()) {
            throw new YmlException("The 'step' must be defined");
        }

        node.flow.get(0).name = rootName;
        Node root = node.flow.get(0).toNode();

        buildNodeRelation(root);
        VALIDATOR.validate(root);

        return root;
    } catch (YAMLException e) {
        throw new YmlException(e.getMessage());
    }
}
 
Example 36
Project: incubator-servicecomb-java-chassis   File: YAMLConfigLoader.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected Map<String, Object> loadData(URL url) throws IOException {
  Yaml yaml = new Yaml();

  try (InputStream inputStream = url.openStream()) {
    return yaml.loadAs(inputStream, Map.class);
  }
}
 
Example 37
Project: Nukkit-Java9   File: PluginBase.java   Source Code and License 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 38
Project: Nukkit-Java9   File: Config.java   Source Code and License 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 39
Project: Nukkit-Java9   File: Config.java   Source Code and License 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 40
Project: Biliomi   File: FirstTimeInstallSetupTask.java   Source Code and License 5 votes vote down vote up
private void saveSettings() throws IOException {
  // Component and integration settings are saved in separate files, these tags should be null in core.yml

  Yaml yamlInstance = new Yaml(new Constructor(YamlCoreSettings.class));
  String yamlString = yamlInstance.dumpAs(yamlCoreSettings, new Tag("nl/juraji/biliomi"), DumperOptions.FlowStyle.BLOCK);

  FileUtils.writeStringToFile(coreYamlFile, yamlString, "UTF-8", false);
}
 
Example 41
Project: monica   File: ConfigurationContext.java   Source Code and License 5 votes vote down vote up
public static List<String> loadYamlRouterConfig() throws FileNotFoundException, IOException{
	Yaml yaml = new Yaml();
	File path = Utils.getPropertiesPath("\\yaml\\router.yaml");
	//YamlRouter yamlRouter = yaml.loadAs(new FileInputStream(path), YamlRouter.class);	
	YamlRouter yamlRouter = yaml.loadAs(Utils.loadResources("yaml/router.yaml").openStream(), YamlRouter.class);
	return yamlRouter.toStringList();
}
 
Example 42
Project: vrops-export   File: ConfigLoader.java   Source Code and License 5 votes vote down vote up
static public Config parse(Reader rdr) {
	Yaml yaml = new Yaml(new Constructor(Config.class));
	Config conf = (Config) yaml.load(rdr);
	if(conf.getOutputFormat() == null) 
		conf.setOutputFormat("csv");
	return conf;
}
 
Example 43
Project: flow-platform   File: NodeUtil.java   Source Code and License 5 votes vote down vote up
/**
 * Verify root format and parse to yml
 */
public static String parseToYml(Node root) {
    VALIDATOR.validate(root);

    RootYmlWrapper ymlWrapper = new RootYmlWrapper(new NodeWrapper(root));

    // clean property which not used in root
    ymlWrapper.flow.get(0).name = null;
    ymlWrapper.flow.get(0).allowFailure = null;

    Yaml yaml = new Yaml(ROOT_YML_CONSTRUCTOR, ORDERED_SKIP_EMPTY_REPRESENTER, DUMPER_OPTIONS);
    String dump = yaml.dump(ymlWrapper);
    dump = dump.substring(dump.indexOf(LINE_BREAK.getString()) + 1);
    return dump;
}
 
Example 44
Project: Jenisys3   File: Config.java   Source Code and License 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 45
Project: Jupiter   File: Config.java   Source Code and License 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 46
Project: cmakeify   File: TestCmakeify.java   Source Code and License 5 votes vote down vote up
@Test
public void dumpIsSelfHost() throws IOException {
  CMakeifyYml config = new CMakeifyYml();
  System.out.printf(new Yaml().dump(config));
  File yaml = new File("test-files/simpleConfiguration/cmakeify.yml");
  yaml.getParentFile().mkdirs();
  Files.write("", yaml, StandardCharsets.UTF_8);
  String result1 = main("-wf", yaml.getParent(), "--dump");
  yaml.delete();
  Files.write(result1, yaml, StandardCharsets.UTF_8);
  System.out.print(result1);
  String result2 = main("-wf", yaml.getParent(), "--dump");
  assertThat(result2).isEqualTo(result1);
}
 
Example 47
Project: open-kilda   File: YamlParser.java   Source Code and License 5 votes vote down vote up
private Map<String, Object> getOverrides() {
	try {
		Yaml  yaml = new Yaml();
		Object object = yaml.load(new FileInputStream(overridesFilename));
		return getFlattenedMap(asMap(object));	
	} catch (FileNotFoundException e) {
		throw new RuntimeException("can't read file " + overridesFilename);			
	}				
}
 
Example 48
Project: openNaEF   File: CmdBuilderMapping.java   Source Code and License 5 votes vote down vote up
@Override
protected synchronized Map<String, ApiConfig> loadInner(Yaml yaml, InputStream is) throws ConfigurationException {
    Map<String, ?> flesh = yaml.loadAs(is, Map.class);

    Map<String, ApiConfig> confs = new LinkedHashMap<>();
    for (Map.Entry<String, ?> entry : flesh.entrySet()) {
        String apiName = entry.getKey();
        Object raw = entry.getValue();
        ApiConfig conf = createConfig(apiName, raw);
        confs.put(apiName, conf);
    }
    return confs;
}
 
Example 49
Project: open-kilda   File: YamlParser.java   Source Code and License 5 votes vote down vote up
private Map<String, Object> getOverrides() {
	try {
		Yaml  yaml = new Yaml();
		Object object = yaml.load(new FileInputStream(overridesFilename));
		return getFlattenedMap(asMap(object));	
	} catch (FileNotFoundException e) {
		throw new RuntimeException("can't read file " + overridesFilename);			
	}				
}
 
Example 50
Project: waggle-dance   File: WaggleDanceRunner.java   Source Code and License 5 votes vote down vote up
public WaggleDanceRunner build() {
  Yaml yaml = YamlFactory.newYaml();

  HashMap<String, Object> extraConfig = new HashMap<>();
  extraConfig.put("graphite", graphiteConfiguration);
  extraConfig.put("yaml-storage", yamlStorageConfiguration);
  File serverConfig = marshall(yaml, SERVER_CONFIG + ".yml", waggleDanceConfiguration, extraConfig);

  Federations federations = new Federations(primaryMetaStore, federatedMetaStores);
  File federationConfig = marshall(yaml, FEDERATION_CONFIG + ".yml", federations);

  WaggleDanceRunner wgRunner = new WaggleDanceRunner(serverConfig, federationConfig);

  return wgRunner;
}
 
Example 51
Project: Jenisys3   File: PluginBase.java   Source Code and License 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 52
Project: TOSCAna   File: ServiceModel.java   Source Code and License 5 votes vote down vote up
public ServiceModel(File template, Log log) {
    this.log = log;
    this.logger = log.getLogger(getClass());
    Yaml yaml = new Yaml();
    try {
        Node snakeNode = yaml.compose(new FileReader(template));
        this.graph = new ServiceGraph(snakeNode, log);
        ToscaStructure.buildBasicStructure(this.graph); // in case this has not already been established
        GraphNormalizer.normalize(this);
        new LinkResolver(this).resolveLinks();
    } catch (FileNotFoundException e) {
        logger.error(String.format("Template '%s' does not exist - failed to construct ServiceModel", template), e);
        throw new IllegalStateException();
    }
}
 
Example 53
Project: CoreX   File: Config.java   Source Code and License 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 54
Project: microbean-helm   File: Configs.java   Source Code and License 5 votes vote down vote up
private static final Map<String, Object> computeEffectiveValues(final ConfigOrBuilder config, Map<String, Object> targetMap) {
  if (targetMap == null) {
    targetMap = new HashMap<>();
  }
  if (config != null) {
    final String raw = config.getRaw();
    if (raw != null && !raw.isEmpty()) {
      @SuppressWarnings("unchecked")
      final Map<String, Object> sourceMap = new Yaml().loadAs(raw, Map.class);
      targetMap = Values.coalesceMaps(sourceMap, targetMap);
    }
  }
  return targetMap;
}
 
Example 55
Project: microbean-helm   File: TestRequirements.java   Source Code and License 5 votes vote down vote up
@Test
public void testYamlUnmarshalling() throws IOException {
  final URL requirementsYaml = Thread.currentThread().getContextClassLoader().getResource("TestRequirements/requirements.yaml");
  assertNotNull(requirementsYaml);
  try (final InputStream stream = new BufferedInputStream(requirementsYaml.openStream())) {
    final Yaml yaml = new Yaml();
    final Requirements requirements = yaml.loadAs(stream, Requirements.class);
    assertNotNull(requirements);
    final Collection<Dependency> dependencies = requirements.getDependencies();
    assertNotNull(dependencies);
    assertEquals(2, dependencies.size());
    final Iterator<Dependency> iterator = dependencies.iterator();
    assertNotNull(iterator);
    assertTrue(iterator.hasNext());

    final Dependency firstDependency = iterator.next();
    assertEquals("subchart1", firstDependency.getName());
    assertEquals("http://localhost:10191", firstDependency.getRepository());
    assertEquals("0.1.0", firstDependency.getVersion());
    assertEquals("subchart1.enabled, global.subchart1.enabled", firstDependency.getCondition());
    Collection<String> tags = firstDependency.getTags();
    assertNotNull(tags);
    assertEquals(2, tags.size());
    
    assertTrue(iterator.hasNext());
    
    final Dependency secondDependency = iterator.next();
    assertEquals("subchart2", secondDependency.getName());
    assertEquals("http://localhost:10191", secondDependency.getRepository());
    assertEquals("0.1.0", secondDependency.getVersion());
    assertEquals("subchart2.enabled,global.subchart2.enabled", secondDependency.getCondition());
    tags = secondDependency.getTags();
    assertNotNull(tags);
    assertEquals(2, tags.size());

    assertFalse(iterator.hasNext());
  }
}
 
Example 56
Project: hadoop-hdfs-fsimage-exporter   File: ConfigTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testReadYml() throws IOException {
    Config config;
    try (Reader reader = new InputStreamReader(
            Thread.currentThread().getContextClassLoader().getResourceAsStream("config.yml"))) {
        config = new Yaml().loadAs(reader, Config.class);
    }

    assertEquals("src/test/resources", config.getFsImagePath());
    assertTrue(config.isSkipPreviouslyParsed());
    assertTrue(!config.isSkipFileDistributionForGroupStats());
    assertTrue(!config.isSkipFileDistributionForUserStats());

    // Paths
    assertTrue(config.hasPaths());
    assertThat(config.getPaths(),
            containsInAnyOrder("/tmp", "/datalake/a.*", "/user/m.*"));
    assertTrue(config.isSkipFileDistributionForPathStats());

    // PathSets
    assertTrue(config.hasPathSets());
    final Map<String, List<String>> pathSets = config.getPathSets();
    assertEquals(2, pathSets.size());
    assertThat(pathSets.get("userMmAndFooAndAsset1"),
            containsInAnyOrder("/datalake/asset3", "/user/mm", "/user/foo"));
    assertThat(pathSets.get("datalakeAsset1and2"),
            containsInAnyOrder("/datalake/asset2", "/datalake/asset1"));
    assertTrue(config.isSkipFileDistributionForPathSetStats());

    // File size distribution
    final List<String> buckets = config.getFileSizeDistributionBuckets();
    assertEquals(buckets, Arrays.asList("0", "42", "1MiB", "32MiB", "64MiB", "128MiB", "1GiB", "12GiB"));
    assertArrayEquals(config.getFileSizeDistributionBucketsAsDoubles(), new double[]{
            0, 42, 1024 * 1024, 32 * 1024 * 1024, 64 * 1024 * 1024, 128 * 1024 * 1024,
            1024L * 1024L * 1024L, 12L * 1024L * 1024L * 1024L
    }, 1e-2);
}
 
Example 57
Project: yaml-format   File: FormatYamlAction.java   Source Code and License 5 votes vote down vote up
private void formatYaml(VirtualFile file) throws Exception {
	WriteCommandAction.runWriteCommandAction(mProject, new Runnable() {
		@Override
		public void run() {
			try {
				file.setBinaryContent(toYaml(new Yaml().load(file.getInputStream())).getBytes(file.getCharset()));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	});
}
 
Example 58
Project: cloud-portal   File: TerraformService.java   Source Code and License 5 votes vote down vote up
@PostConstruct
public void init() {

	try {

		Constructor constructor = new Constructor(VariableConfig.class);

		TypeDescription variableConfigTypeDescription = new TypeDescription(VariableConfig.class);
		variableConfigTypeDescription.putListPropertyType(PROPERTY_VARIABLE_GROUPS, VariableGroup.class);
		constructor.addTypeDescription(variableConfigTypeDescription);

		TypeDescription variableGroupTypeDescription = new TypeDescription(VariableGroup.class);
		variableGroupTypeDescription.putListPropertyType(PROPERTY_VARIABLES, Variable.class);
		constructor.addTypeDescription(variableGroupTypeDescription);

		Yaml yaml = new Yaml(constructor);

		File terraformFolder = resourceService.getClasspathResource(Constants.FOLDER_TERRAFORM);
		if (!terraformFolder.isFile()) {
			File[] providerFolderArray = terraformFolder.listFiles();
			for (File providerFolder : providerFolderArray) {
				File variableFile = new File(new URI(providerFolder.toURI() + File.separator + FILE_VARIABLES_YML));
				if (variableFile.exists()) {
					VariableConfig variableConfig = yaml.loadAs(new FileInputStream(variableFile), VariableConfig.class);
					List<VariableGroup> variableGroupList = variableConfig.getVariableGroups();
					providerDefaults.put(providerFolder.getName(), variableGroupList);
				}

			}
		}
	}
	catch (Exception e) {
		LOG.error(e.getMessage(), e);
	}
}
 
Example 59
Project: SkyDocs   File: Utils.java   Source Code and License 5 votes vote down vote up
/**
 * Decodes a file's header.
 * 
 * @param header The header.
 * 
 * @return A map representing the YAML content key : value.
 */

@SuppressWarnings("unchecked")
public static final Map<String, Object> decodeFileHeader(final String header) {
	if(header == null) {
		return null;
	}
	final Yaml yaml = new Yaml();
	return (Map<String, Object>)yaml.load(header);
}
 
Example 60
Project: TalentZzzz   File: ItemManager.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
public static void init() {
    File item = new File(Talent.instance.getDataFolder(), "items.yml");
    if (!item.exists()) Talent.instance.saveResource("items.yml", true);
    try {
        items.putAll(new Gson().fromJson(new Gson().toJson(new Yaml().load(Files.toString(item, Charset.forName("utf-8")))), Map.class));
    } catch (IOException e) {
        e.printStackTrace();
    }
}