Moved general purpose stuff into util, renamed utils->util

This commit is contained in:
ondra
2014-04-16 14:32:56 +02:00
parent e58156b7ee
commit 6843e746bc
208 changed files with 656 additions and 629 deletions
@@ -0,0 +1,475 @@
package mightypork.util.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map.Entry;
import java.util.TreeMap;
import mightypork.util.math.Range;
import mightypork.util.math.constraints.vect.Vect;
import mightypork.util.math.constraints.vect.VectConst;
import mightypork.util.objects.Convert;
/**
* Property manager with advanced formatting and value checking.<br>
* Methods starting with put are for filling. Most of the others are shortcuts
* to getters.
*
* @author MightyPork
*/
public class PropertyManager {
private abstract class Property<T> {
public String comment;
public String key;
public T value;
public T defaultValue;
public Property(String key, T defaultValue, String comment) {
super();
this.comment = comment;
this.key = key;
this.defaultValue = defaultValue;
this.value = defaultValue;
}
public abstract void parse(String string);
@Override
public String toString()
{
return Convert.toString(value);
}
}
private class BooleanProperty extends Property<Boolean> {
public BooleanProperty(String key, Boolean defaultValue, String comment) {
super(key, defaultValue, comment);
}
@Override
public void parse(String string)
{
value = Convert.toBoolean(string, defaultValue);
}
}
private class IntegerProperty extends Property<Integer> {
public IntegerProperty(String key, Integer defaultValue, String comment) {
super(key, defaultValue, comment);
}
@Override
public void parse(String string)
{
value = Convert.toInteger(string, defaultValue);
}
}
private class DoubleProperty extends Property<Double> {
public DoubleProperty(String key, Double defaultValue, String comment) {
super(key, defaultValue, comment);
}
@Override
public void parse(String string)
{
value = Convert.toDouble(string, defaultValue);
}
}
private class StringProperty extends Property<String> {
public StringProperty(String key, String defaultValue, String comment) {
super(key, defaultValue, comment);
}
@Override
public void parse(String string)
{
value = Convert.toString(string, defaultValue);
}
}
private class RangeProperty extends Property<Range> {
public RangeProperty(String key, Range defaultValue, String comment) {
super(key, defaultValue, comment);
}
@Override
public void parse(String string)
{
value = Convert.toRange(string, defaultValue);
}
}
private class CoordProperty extends Property<Vect> {
public CoordProperty(String key, Vect defaultValue, String comment) {
super(key, defaultValue, comment);
}
@Override
public void parse(String string)
{
value = Convert.toVect(string, defaultValue);
}
}
/** put newline before entry comments */
private boolean cfgNewlineBeforeComments = true;
/** Put newline between sections. */
private boolean cfgSeparateSections = true;
/** Force save, even if nothing changed (used to save changed comments) */
private boolean cfgForceSave;
private final File file;
private String fileComment = "";
private final TreeMap<String, Property<?>> entries;
private final TreeMap<String, String> renameTable;
private final TreeMap<String, String> overrideValues;
private SortedProperties props = new SortedProperties();
/**
* Create property manager from file path and an initial comment.
*
* @param file file with the props
* @param comment the initial comment. Use \n in it if you want.
*/
public PropertyManager(File file, String comment) {
this.file = file;
this.entries = new TreeMap<>();
this.overrideValues = new TreeMap<>();
this.renameTable = new TreeMap<>();
this.fileComment = comment;
}
/**
* Load, fix and write to file.
*/
public void apply()
{
boolean needsSave = false;
if (!file.getParentFile().mkdirs()) {
if (!file.getParentFile().exists()) {
throw new RuntimeException("Cound not create config file.");
}
}
try (FileInputStream fis = new FileInputStream(file)) {
props.load(fis);
} catch (final IOException e) {
needsSave = true;
props = new SortedProperties();
}
props.cfgBlankRowBetweenSections = cfgSeparateSections;
props.cfgBlankRowBeforeComment = cfgNewlineBeforeComments;
final ArrayList<String> keyList = new ArrayList<>();
// rename keys
for (final Entry<String, String> entry : renameTable.entrySet()) {
if (props.getProperty(entry.getKey()) == null) {
continue;
}
props.setProperty(entry.getValue(), props.getProperty(entry.getKey()));
props.remove(entry.getKey());
needsSave = true;
}
// set the override values into the freshly loaded properties file
for (final Entry<String, String> entry : overrideValues.entrySet()) {
props.setProperty(entry.getKey(), entry.getValue());
needsSave = true;
}
// validate entries one by one, replace with default when needed
for (final Property<?> entry : entries.values()) {
keyList.add(entry.key);
final String propOrig = props.getProperty(entry.key);
entry.parse(propOrig);
if (!entry.toString().equals(propOrig)) {
needsSave = true;
}
if (entry.comment != null) {
props.setKeyComment(entry.key, entry.comment);
}
if (propOrig == null || !entry.toString().equals(propOrig)) {
props.setProperty(entry.key, entry.toString());
needsSave = true;
}
}
// removed unused props
for (final String propname : props.keySet().toArray(new String[props.size()])) {
if (!keyList.contains(propname)) {
props.remove(propname);
needsSave = true;
}
}
// save if needed
if (needsSave || cfgForceSave) {
try {
props.store(new FileOutputStream(file), fileComment);
} catch (final IOException ioe) {
ioe.printStackTrace();
}
}
overrideValues.clear();
renameTable.clear();
}
/**
* @param newlineBeforeComments put newline before comments
*/
public void cfgNewlineBeforeComments(boolean newlineBeforeComments)
{
this.cfgNewlineBeforeComments = newlineBeforeComments;
}
/**
* @param separateSections do separate sections by newline
*/
public void cfgSeparateSections(boolean separateSections)
{
this.cfgSeparateSections = separateSections;
}
/**
* @param forceSave save even if unchanged.
*/
public void cfgForceSave(boolean forceSave)
{
this.cfgForceSave = forceSave;
}
/**
* Get a property entry (rarely used)
*
* @param n key
* @return the entry
*/
private Property<?> get(String n)
{
try {
return entries.get(n);
} catch (final Throwable t) {
return null;
}
}
/**
* Get boolean property
*
* @param n key
* @return the boolean found, or false
*/
public Boolean getBoolean(String n)
{
return Convert.toBoolean(get(n).value);
}
/**
* Get numeric property
*
* @param n key
* @return the int found, or null
*/
public Integer getInteger(String n)
{
return Convert.toInteger(get(n).value);
}
/**
* Get numeric property as double
*
* @param n key
* @return the double found, or null
*/
public Double getDouble(String n)
{
return Convert.toDouble(get(n).value);
}
/**
* Get string property
*
* @param n key
* @return the string found, or null
*/
public String getString(String n)
{
return Convert.toString(get(n).value);
}
/**
* Get range property
*
* @param n key
* @return the range found, or null
*/
public Range getRange(String n)
{
return Convert.toRange(get(n).value);
}
/**
* Get coord property
*
* @param n key
* @return the coord found, or null
*/
public VectConst getCoord(String n)
{
return Convert.toVect(get(n).value);
}
/**
* Add a boolean property
*
* @param n key
* @param d default value
* @param comment the in-file comment
*/
public void putBoolean(String n, boolean d, String comment)
{
entries.put(n, new BooleanProperty(n, d, comment));
}
/**
* Add a numeric property (double)
*
* @param n key
* @param d default value
* @param comment the in-file comment
*/
public void putDouble(String n, double d, String comment)
{
entries.put(n, new DoubleProperty(n, d, comment));
}
/**
* Add a numeric property
*
* @param n key
* @param d default value
* @param comment the in-file comment
*/
public void putInteger(String n, int d, String comment)
{
entries.put(n, new IntegerProperty(n, d, comment));
}
/**
* Add a string property
*
* @param n key
* @param d default value
* @param comment the in-file comment
*/
public void putString(String n, String d, String comment)
{
entries.put(n, new StringProperty(n, d, comment));
}
/**
* Add a coord property
*
* @param n key
* @param d default value
* @param comment the in-file comment
*/
public void putCoord(String n, Vect d, String comment)
{
entries.put(n, new CoordProperty(n, d, comment));
}
/**
* Add a range property
*
* @param n key
* @param d default value
* @param comment the in-file comment
*/
public void putRange(String n, Range d, String comment)
{
entries.put(n, new RangeProperty(n, d, comment));
}
/**
* Rename key before doing "apply"; value is preserved
*
* @param oldKey old key
* @param newKey new key
*/
public void renameKey(String oldKey, String newKey)
{
renameTable.put(oldKey, newKey);
return;
}
/**
* Set value saved to certain key; use to save runtime-changed configuration
* values.
*
* @param key key
* @param value the saved value
*/
public void setValue(String key, Object value)
{
overrideValues.put(key, value.toString());
return;
}
}
@@ -0,0 +1,205 @@
package mightypork.util.config;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import mightypork.util.files.FileUtils;
import mightypork.util.logging.Log;
/**
* Utility for parsing simple config files<br>
* # and // mark a comment<br>
* empty lines and lines without "=" are ignored<br>
* lines with "=" must have "key = value" format, or a warning is logged.<br>
* use "NULL" to create empty value.
*
* @author MightyPork
*/
public class SimpleConfig {
/**
* Load list from file
*
* @param file file
* @return map of keys and values
* @throws IOException
*/
public static List<String> listFromFile(File file) throws IOException
{
final String fileText = FileUtils.fileToString(file);
return listFromString(fileText);
}
/**
* Load map from file
*
* @param file file
* @return map of keys and values
* @throws IOException
*/
public static Map<String, String> mapFromFile(File file) throws IOException
{
final String fileText = FileUtils.fileToString(file);
return mapFromString(fileText);
}
/**
* Load list from string
*
* @param text text of the file
* @return map of keys and values
*/
public static List<String> listFromString(String text)
{
final List<String> list = new ArrayList<>();
final String[] groupsLines = text.split("\n");
for (String s : groupsLines) {
// ignore invalid lines
if (s.length() == 0) continue;
if (s.startsWith("#") || s.startsWith("//")) continue;
// NULL value
if (s.equalsIgnoreCase("NULL")) s = null;
if (s != null) s = s.replace("\\n", "\n");
// save extracted key-value pair
list.add(s);
}
return list;
}
/**
* Load map from string
*
* @param text text of the file
* @return map of keys and values
*/
public static Map<String, String> mapFromString(String text)
{
final LinkedHashMap<String, String> pairs = new LinkedHashMap<>();
final String[] groupsLines = text.split("\n");
for (final String s : groupsLines) {
// ignore invalid lines
if (s.length() == 0) continue;
if (s.startsWith("#") || s.startsWith("//")) continue;
if (!s.contains("=")) continue;
// split and trim
String[] parts = s.split("=");
for (int i = 0; i < parts.length; i++) {
parts[i] = parts[i].trim();
}
// check if both parts are valid
if (parts.length == 0) {
Log.w("Bad line in config file: " + s);
continue;
}
if (parts.length == 1) {
parts = new String[] { parts[0], "" };
}
if (parts.length != 2) {
Log.w("Bad line in config file: " + s);
continue;
}
// NULL value
if (parts[0].equalsIgnoreCase("NULL")) parts[0] = null;
if (parts[1].equalsIgnoreCase("NULL")) parts[1] = null;
if (parts[0] != null) parts[0] = parts[0].replace("\\n", "\n");
if (parts[1] != null) parts[1] = parts[1].replace("\\n", "\n");
// save extracted key-value pair
pairs.put(parts[0], parts[1]);
}
return pairs;
}
/**
* Save map to file
*
* @param target
* @param data
* @param allowNulls allow nulls.
* @throws IOException
*/
public static void mapToFile(File target, Map<String, String> data, boolean allowNulls) throws IOException
{
final List<String> lines = new ArrayList<>();
for (final Entry<String, String> e : data.entrySet()) {
String key = e.getKey();
String value = e.getValue();
if (!allowNulls && (key == null || value == null || key.length() == 0 || value.length() == 0)) continue;
if (key == null) key = "NULL";
if (value == null) value = "NULL";
key = key.replace("\n", "\\n");
value = value.replace("\n", "\\n");
lines.add(key + " = " + value);
}
String text = ""; // # File written by SimpleConfig
for (final String s : lines) {
if (text.length() > 0) text += "\n";
text += s;
}
FileUtils.stringToFile(target, text);
}
/**
* Save list to file
*
* @param target
* @param data
* @throws IOException
*/
public static void listToFile(File target, List<String> data) throws IOException
{
String text = ""; // # File written by SimpleConfig
for (String s : data) {
if (text.length() > 0) text += "\n";
if (s == null) s = "NULL";
s = s.replace("\n", "\\n");
text += s;
}
FileUtils.stringToFile(target, text);
}
}
@@ -0,0 +1,303 @@
package mightypork.util.config;
import java.io.*;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
/**
* Properties stored in file, alphabetically sorted.<br>
* Uses UTF-8 encoding and each property can have it's own comment.
*
* @author MightyPork
*/
public class SortedProperties extends java.util.Properties {
/** Option: put empty line before each comment. */
public boolean cfgBlankRowBeforeComment = true;
/**
* Option: Separate sections by newline<br>
* Section = string before first dot in key.
*/
public boolean cfgBlankRowBetweenSections = true;
/** Comments for individual keys */
private final Hashtable<String, String> keyComments = new Hashtable<>();
private static void writeComments(BufferedWriter bw, String comm) throws IOException
{
final String comments = comm.replace("\n\n", "\n \n");
final int len = comments.length();
int current = 0;
int last = 0;
final char[] uu = new char[6];
uu[0] = '\\';
uu[1] = 'u';
while (current < len) {
final char c = comments.charAt(current);
if (c > '\u00ff' || c == '\n' || c == '\r') {
if (last != current) {
bw.write("# " + comments.substring(last, current));
}
if (c > '\u00ff') {
uu[2] = hexDigit(c, 12);
uu[3] = hexDigit(c, 8);
uu[4] = hexDigit(c, 4);
uu[5] = hexDigit(c, 0);
bw.write(new String(uu));
} else {
bw.newLine();
if (c == '\r' && current != len - 1 && comments.charAt(current + 1) == '\n') {
current++;
}
}
last = current + 1;
}
current++;
}
if (last != current) {
bw.write("# " + comments.substring(last, current));
}
bw.newLine();
bw.newLine();
bw.newLine();
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public synchronized Enumeration keys()
{
final Enumeration keysEnum = super.keys();
final Vector keyList = new Vector();
while (keysEnum.hasMoreElements()) {
keyList.add(keysEnum.nextElement());
}
Collections.sort(keyList); //sort!
return keyList.elements();
}
private static String saveConvert(String theString, boolean escapeSpace, boolean escapeUnicode)
{
final int len = theString.length();
int bufLen = len * 2;
if (bufLen < 0) {
bufLen = Integer.MAX_VALUE;
}
final StringBuffer result = new StringBuffer(bufLen);
for (int x = 0; x < len; x++) {
final char ch = theString.charAt(x);
// Handle common case first, selecting largest block that
// avoids the specials below
if ((ch > 61) && (ch < 127)) {
if (ch == '\\') {
result.append('\\');
result.append('\\');
continue;
}
result.append(ch);
continue;
}
switch (ch) {
case ' ':
if (x == 0 || escapeSpace) {
result.append('\\');
}
result.append(' ');
break;
case '\t':
result.append('\\');
result.append('t');
break;
case '\n':
result.append('\\');
result.append('n');
break;
case '\r':
result.append('\\');
result.append('r');
break;
case '\f':
result.append('\\');
result.append('f');
break;
case '=': // Fall through
case ':': // Fall through
case '#': // Fall through
case '!':
result.append('\\');
result.append(ch);
break;
default:
if (((ch < 0x0020) || (ch > 0x007e)) & escapeUnicode) {
result.append('\\');
result.append('u');
result.append(hexDigit(ch, 12));
result.append(hexDigit(ch, 8));
result.append(hexDigit(ch, 4));
result.append(hexDigit(ch, 0));
} else {
result.append(ch);
}
}
}
return result.toString();
}
/**
* Set additional comment to a key
*
* @param key key for comment
* @param comment the comment
*/
public void setKeyComment(String key, String comment)
{
keyComments.put(key, comment);
}
@SuppressWarnings("rawtypes")
@Override
public void store(OutputStream out, String comments) throws IOException
{
final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
final boolean escUnicode = false;
boolean firstEntry = true;
String lastSectionBeginning = "";
if (comments != null) {
writeComments(bw, comments);
}
synchronized (this) {
for (final Enumeration e = keys(); e.hasMoreElements();) {
boolean wasNewLine = false;
String key = (String) e.nextElement();
String val = (String) get(key);
key = saveConvert(key, true, escUnicode);
val = saveConvert(val, false, escUnicode);
if (cfgBlankRowBetweenSections && !lastSectionBeginning.equals(key.split("[.]")[0])) {
if (!firstEntry) {
bw.newLine();
bw.newLine();
}
wasNewLine = true;
lastSectionBeginning = key.split("[.]")[0];
}
if (keyComments.containsKey(key)) {
String cm = keyComments.get(key);
cm = cm.replace("\r", "\n");
cm = cm.replace("\r\n", "\n");
cm = cm.replace("\n\n", "\n \n");
final String[] cmlines = cm.split("\n");
if (!wasNewLine && !firstEntry && cfgBlankRowBeforeComment) {
bw.newLine();
}
for (final String cmline : cmlines) {
bw.write("# " + cmline);
bw.newLine();
}
}
bw.write(key + " = " + val);
bw.newLine();
firstEntry = false;
}
}
bw.flush();
}
private static String escapifyStr(String str)
{
final StringBuilder result = new StringBuilder();
final int len = str.length();
for (int x = 0; x < len; x++) {
final char ch = str.charAt(x);
if (ch <= 0x007e) {
result.append(ch);
continue;
}
result.append('\\');
result.append('u');
result.append(hexDigit(ch, 12));
result.append(hexDigit(ch, 8));
result.append(hexDigit(ch, 4));
result.append(hexDigit(ch, 0));
}
return result.toString();
}
private static char hexDigit(char ch, int offset)
{
final int val = (ch >> offset) & 0xF;
if (val <= 9) {
return (char) ('0' + val);
}
return (char) ('A' + val - 10);
}
@Override
public synchronized void load(InputStream is) throws IOException
{
load(is, "utf-8");
}
public void load(InputStream is, String encoding) throws IOException
{
final StringBuilder sb = new StringBuilder();
final InputStreamReader isr = new InputStreamReader(is, encoding);
while (true) {
final int temp = isr.read();
if (temp < 0) {
break;
}
final char c = (char) temp;
sb.append(c);
}
final String read = sb.toString();
final String inputString = escapifyStr(read);
final byte[] bs = inputString.getBytes("ISO-8859-1");
final ByteArrayInputStream bais = new ByteArrayInputStream(bs);
super.load(bais);
}
}