package de.srsoftware.belegscanner; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * JSON-based Configuration manager for the Application. * * @author Stephan Richter * */ public class Configuration { private static final Logger LOG = LoggerFactory.getLogger(Configuration.class); private File file; private JSONObject json = new JSONObject(); /** * Create/Load configuration for the application. * @param appName * @throws IOException */ public Configuration(String appName) throws IOException { String home = System.getProperty("user.home"); String fileName = new StringBuilder().append(home).append(File.separator).append(".config").append(File.separator).append(appName).append(File.separator).append("config.json").toString(); file = new File(fileName); if (file.exists()) { LOG.info("{} found, loading…",file); FileReader in = new FileReader(file); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(buffer); in.transferTo(writer); writer.close(); String jsonString = buffer.toString(StandardCharsets.UTF_8); LOG.debug("Loaded json: {}",jsonString); json = jsonString.startsWith("{") ? new JSONObject(jsonString) : new JSONObject(); in.close(); } else { LOG.info("{} not found, creating new config.",file); json = new JSONObject(); } } /** * Write contents of the configuration object to the underlying file. * @throws IOException */ public void save() throws IOException { LOG.debug("Trying to save config…"); File dir = file.getParentFile(); if (!dir.exists()) dir.mkdirs(); FileWriter out = new FileWriter(file); json.write(out, 2, 0); out.close(); } /** * Load an JSON array from the configuration * @param key Search path in the form path.to.array * @return */ public JSONArray getOrCreateArray(String key) { LOG.debug("requesting {} from config.",key); String[] parts = key.split("\\."); JSONObject localJson = json; boolean update = false; JSONArray result = null; for (int i=0; i * @param key Search path in the form path.to.array * @return null, if no such path is found */ @SuppressWarnings("unchecked") public T get(String key) { LOG.debug("requesting {} from config.",key); String[] parts = key.split("\\."); JSONObject localJson = json; for (int i=0; i * @param key Search path in the form path.to.array * @param preset Content for the path, if it does not exist * @return preset, if no such path is found */ @SuppressWarnings("unchecked") public T getOrCreate(String key, T preset) { LOG.debug("requesting {} from config.",key); String[] parts = key.split("\\."); JSONObject localJson = json; boolean update = false; Object result = preset; for (int i=0; i