Skip to content

Instantly share code, notes, and snippets.

@zach-m
Last active November 5, 2017 09:52
Show Gist options
  • Save zach-m/a281f32c838dd9e79b9ee20320683998 to your computer and use it in GitHub Desktop.
Save zach-m/a281f32c838dd9e79b9ee20320683998 to your computer and use it in GitHub Desktop.
package com.tectonica;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.nodes.Tag;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
* This is a general purpose YAML-based configuration file. To use it, add this to your <code>pom.xml</code>:
* <pre>
* &lt;dependency&gt;
* &lt;groupId&gt;org.yaml&lt;/groupId&gt;
* &lt;artifactId&gt;snakeyaml&lt;/artifactId&gt;
* &lt;version&gt;1.19&lt;/version&gt;
* &lt;/dependency&gt;
* </pre>
* <p>
* Use {@link #get()} to retrieve the in-memory copy of the configuration object. If you change it, be sure to call
* {@link #save()} after all changes are done.
*
* @author Zach Melamed
* @since 11/5/2017
*/
public class Config {
private static final File configFile = new File(System.getProperty("user.home"), ".my-app");
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// CONFIGURATION MEMBERS + DEFAULT VALUES
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public double width = 1000.0;
public double height = 700.0;
public Double x = null; // implementation allows NULL, means auto-detect
public Double y = null; // implementation allows NULL, means auto-detect
public String csvFile = "./src/test/resources";
public String referenceFolder = "";
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// APIs
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private static final Yaml yaml = new Yaml(new Constructor(Config.class));
private static Config config = null;
public static Config get() {
if (config == null) {
load();
}
return config;
}
public static void save() {
try (FileWriter writer = new FileWriter(configFile)) {
writer.write(yaml.dumpAs(config, Tag.MAP, DumperOptions.FlowStyle.BLOCK));
} catch (IOException e) {
e.printStackTrace();
}
}
private static void load() {
try (FileReader reader = new FileReader(configFile)) {
config = yaml.loadAs(reader, Config.class);
if (config == null) { // empty file
config = new Config();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment