Some refactoring and cleaning, string utils.

master
Ondřej Hruška 10 years ago
parent 272fb63168
commit 33696050d4
  1. 60
      src/mightypork/utils/Convert.java
  2. 34
      src/mightypork/utils/MapSort.java
  3. 38
      src/mightypork/utils/Reflect.java
  4. 231
      src/mightypork/utils/Str.java
  5. 153
      src/mightypork/utils/Support.java
  6. 2
      src/mightypork/utils/annotations/Alias.java
  7. 2
      src/mightypork/utils/annotations/FactoryMethod.java
  8. 90
      src/mightypork/utils/config/SimpleConfig.java
  9. 36
      src/mightypork/utils/config/propmgr/Property.java
  10. 96
      src/mightypork/utils/config/propmgr/PropertyManager.java
  11. 30
      src/mightypork/utils/config/propmgr/PropertyStore.java
  12. 10
      src/mightypork/utils/config/propmgr/properties/BooleanProperty.java
  13. 10
      src/mightypork/utils/config/propmgr/properties/DoubleProperty.java
  14. 10
      src/mightypork/utils/config/propmgr/properties/IntegerProperty.java
  15. 10
      src/mightypork/utils/config/propmgr/properties/StringProperty.java
  16. 52
      src/mightypork/utils/config/propmgr/store/PropertyFile.java
  17. 102
      src/mightypork/utils/config/propmgr/store/SortedProperties.java
  18. 41
      src/mightypork/utils/eventbus/BusEvent.java
  19. 208
      src/mightypork/utils/eventbus/EventBus.java
  20. 78
      src/mightypork/utils/eventbus/EventChannel.java
  21. 30
      src/mightypork/utils/eventbus/clients/BusNode.java
  22. 18
      src/mightypork/utils/eventbus/clients/ClientHub.java
  23. 2
      src/mightypork/utils/eventbus/clients/ClientList.java
  24. 8
      src/mightypork/utils/eventbus/clients/DelegatingClient.java
  25. 30
      src/mightypork/utils/eventbus/clients/DelegatingList.java
  26. 4
      src/mightypork/utils/eventbus/clients/ToggleableClient.java
  27. 2
      src/mightypork/utils/eventbus/events/DestroyEvent.java
  28. 10
      src/mightypork/utils/eventbus/events/UpdateEvent.java
  29. 2
      src/mightypork/utils/eventbus/events/flags/DelayedEvent.java
  30. 2
      src/mightypork/utils/eventbus/events/flags/NonConsumableEvent.java
  31. 2
      src/mightypork/utils/eventbus/events/flags/NonRejectableEvent.java
  32. 16
      src/mightypork/utils/exceptions/CorruptDataException.java
  33. 16
      src/mightypork/utils/exceptions/IllegalValueException.java
  34. 16
      src/mightypork/utils/exceptions/KeyAlreadyExistsException.java
  35. 18
      src/mightypork/utils/files/FileSuffixFilter.java
  36. 88
      src/mightypork/utils/files/FileTreeDiff.java
  37. 194
      src/mightypork/utils/files/FileUtil.java
  38. 14
      src/mightypork/utils/files/InstanceLock.java
  39. 52
      src/mightypork/utils/files/OsUtils.java
  40. 36
      src/mightypork/utils/files/WorkDir.java
  41. 46
      src/mightypork/utils/files/zip/ZipBuilder.java
  42. 66
      src/mightypork/utils/files/zip/ZipUtils.java
  43. 2
      src/mightypork/utils/interfaces/Destroyable.java
  44. 6
      src/mightypork/utils/interfaces/Enableable.java
  45. 6
      src/mightypork/utils/interfaces/Hideable.java
  46. 12
      src/mightypork/utils/interfaces/Pauseable.java
  47. 2
      src/mightypork/utils/interfaces/Pollable.java
  48. 2
      src/mightypork/utils/interfaces/Updateable.java
  49. 218
      src/mightypork/utils/ion/Ion.java
  50. 6
      src/mightypork/utils/ion/IonBinary.java
  51. 6
      src/mightypork/utils/ion/IonBundled.java
  52. 180
      src/mightypork/utils/ion/IonDataBundle.java
  53. 212
      src/mightypork/utils/ion/IonInput.java
  54. 28
      src/mightypork/utils/ion/IonMapWrapper.java
  55. 204
      src/mightypork/utils/ion/IonOutput.java
  56. 28
      src/mightypork/utils/ion/IonSequenceWrapper.java
  57. 12
      src/mightypork/utils/ion/IonizerBinary.java
  58. 12
      src/mightypork/utils/ion/IonizerBundled.java
  59. 144
      src/mightypork/utils/logging/Log.java
  60. 22
      src/mightypork/utils/logging/monitors/LogMonitor.java
  61. 4
      src/mightypork/utils/logging/monitors/LogMonitorStdout.java
  62. 4
      src/mightypork/utils/logging/writers/ArchivingLog.java
  63. 28
      src/mightypork/utils/logging/writers/LogWriter.java
  64. 72
      src/mightypork/utils/logging/writers/SimpleLog.java
  65. 144
      src/mightypork/utils/math/Calc.java
  66. 74
      src/mightypork/utils/math/Polar.java
  67. 92
      src/mightypork/utils/math/Range.java
  68. 78
      src/mightypork/utils/math/algo/Coord.java
  69. 32
      src/mightypork/utils/math/algo/Move.java
  70. 28
      src/mightypork/utils/math/algo/Moves.java
  71. 44
      src/mightypork/utils/math/algo/floodfill/FloodFill.java
  72. 2
      src/mightypork/utils/math/algo/pathfinding/Heuristic.java
  73. 126
      src/mightypork/utils/math/algo/pathfinding/PathFinder.java
  74. 28
      src/mightypork/utils/math/algo/pathfinding/PathFinderProxy.java
  75. 2
      src/mightypork/utils/math/algo/pathfinding/heuristics/DiagonalHeuristic.java
  76. 2
      src/mightypork/utils/math/algo/pathfinding/heuristics/ManhattanHeuristic.java
  77. 12
      src/mightypork/utils/math/angles/Angles.java
  78. 46
      src/mightypork/utils/math/angles/Deg.java
  79. 30
      src/mightypork/utils/math/angles/Rad.java
  80. 78
      src/mightypork/utils/math/animation/Animator.java
  81. 26
      src/mightypork/utils/math/animation/AnimatorBounce.java
  82. 20
      src/mightypork/utils/math/animation/AnimatorRewind.java
  83. 134
      src/mightypork/utils/math/animation/Easing.java
  84. 170
      src/mightypork/utils/math/animation/NumAnimated.java
  85. 20
      src/mightypork/utils/math/animation/NumAnimatedDeg.java
  86. 20
      src/mightypork/utils/math/animation/NumAnimatedRad.java
  87. 116
      src/mightypork/utils/math/animation/VectAnimated.java
  88. 126
      src/mightypork/utils/math/color/Color.java
  89. 24
      src/mightypork/utils/math/color/ColorAlphaAdjuster.java
  90. 30
      src/mightypork/utils/math/color/ColorHsb.java
  91. 24
      src/mightypork/utils/math/color/ColorRgb.java
  92. 6
      src/mightypork/utils/math/color/Grad.java
  93. 2
      src/mightypork/utils/math/color/GradH.java
  94. 2
      src/mightypork/utils/math/color/GradV.java
  95. 6
      src/mightypork/utils/math/color/pal/CGA.java
  96. 2
      src/mightypork/utils/math/color/pal/CMDR.java
  97. 10
      src/mightypork/utils/math/color/pal/PAL16.java
  98. 12
      src/mightypork/utils/math/color/pal/RGB.java
  99. 6
      src/mightypork/utils/math/color/pal/ZX.java
  100. 18
      src/mightypork/utils/math/constraints/CachedConstraint.java
  101. Some files were not shown because too many files have changed in this diff Show More

@ -8,7 +8,7 @@ package mightypork.utils;
* @author Ondřej Hruška (MightyPork)
*/
public class Convert {
/**
* Get INTEGER
*
@ -26,8 +26,8 @@ public class Convert {
} catch (final NumberFormatException e) {}
return def;
}
/**
* Get DOUBLE
*
@ -45,8 +45,8 @@ public class Convert {
} catch (final NumberFormatException e) {}
return def;
}
/**
* Get FLOAT
*
@ -62,8 +62,8 @@ public class Convert {
} catch (final NumberFormatException e) {}
return def;
}
/**
* Get BOOLEAN
*
@ -76,7 +76,7 @@ public class Convert {
if (o == null) return def;
if (o instanceof Boolean) return ((Boolean) o).booleanValue();
if (o instanceof Number) return ((Number) o).intValue() != 0;
if (o instanceof String) {
final String s = ((String) o).trim().toLowerCase();
if (s.equals("0")) return false;
@ -85,23 +85,23 @@ public class Convert {
final double n = Double.parseDouble(s);
return n != 0;
} catch (final NumberFormatException e) {}
if (s.equals("true")) return true;
if (s.equals("yes")) return true;
if (s.equals("y")) return true;
if (s.equals("a")) return true;
if (s.equals("enabled")) return true;
if (s.equals("false")) return false;
if (s.equals("no")) return false;
if (s.equals("n")) return false;
if (s.equals("disabled")) return true;
}
return def;
}
/**
* Get STRING
*
@ -113,19 +113,19 @@ public class Convert {
{
if (o == null) return def;
if (o instanceof String) return ((String) o);
if (o instanceof Float) return Support.str((float) o);
if (o instanceof Double) return Support.str((double) o);
if (o instanceof Float) return Str.val((float) o);
if (o instanceof Double) return Str.val((double) o);
if (o instanceof Class<?>) {
return Support.str(o);
return Str.val(o);
}
return o.toString();
}
/**
* Get INTEGER
*
@ -136,8 +136,8 @@ public class Convert {
{
return toInteger(o, 0);
}
/**
* Get DOUBLE
*
@ -148,8 +148,8 @@ public class Convert {
{
return toDouble(o, 0d);
}
/**
* Get FLOAT
*
@ -160,8 +160,8 @@ public class Convert {
{
return toFloat(o, 0f);
}
/**
* Get BOOLEAN
*
@ -172,8 +172,8 @@ public class Convert {
{
return toBoolean(o, false);
}
/**
* Get STRING
*

@ -16,7 +16,7 @@ import java.util.Map.Entry;
* @author Ondřej Hruška (MightyPork)
*/
public class MapSort {
/**
* Sort a map by keys, maintaining key-value pairs, using natural order.
*
@ -28,8 +28,8 @@ public class MapSort {
{
return byKeys(map, null);
}
/**
* Sort a map by keys, maintaining key-value pairs.
*
@ -41,10 +41,10 @@ public class MapSort {
public static <K, V> LinkedHashMap<K, V> byKeys(Map<K, V> map, Comparator<K> comparator)
{
final List<K> keys = new LinkedList<>(map.keySet());
if (comparator == null) {
comparator = new Comparator<K>() {
@Override
public int compare(K arg0, K arg1)
{
@ -52,18 +52,18 @@ public class MapSort {
}
};
}
Collections.sort(keys, comparator);
final LinkedHashMap<K, V> sortedMap = new LinkedHashMap<>();
for (final K key : keys) {
sortedMap.put(key, map.get(key));
}
return sortedMap;
}
/**
* Sort a map by values, maintaining key-value pairs, using natural order.
*
@ -75,8 +75,8 @@ public class MapSort {
{
return byValues(map, null);
}
/**
* Sort a map by values, maintaining key-value pairs.
*
@ -87,9 +87,9 @@ public class MapSort {
public static <K, V> LinkedHashMap<K, V> byValues(Map<K, V> map, final Comparator<V> comparator)
{
final List<Map.Entry<K, V>> entries = new LinkedList<>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<K, V>>() {
@SuppressWarnings("unchecked")
@Override
public int compare(Entry<K, V> o1, Entry<K, V> o2)
@ -98,13 +98,13 @@ public class MapSort {
return comparator.compare(o1.getValue(), o2.getValue());
}
});
final LinkedHashMap<K, V> sortedMap = new LinkedHashMap<>();
for (final Map.Entry<K, V> entry : entries) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
}

@ -14,7 +14,7 @@ import java.lang.reflect.Type;
* @author Ondřej Hruška (MightyPork)
*/
public class Reflect {
/**
* Get annotation of given type from an object
*
@ -26,8 +26,8 @@ public class Reflect {
{
return tested.getClass().getAnnotation(annotation);
}
/**
* Check if an object has an annotation of given trype
*
@ -39,8 +39,8 @@ public class Reflect {
{
return tested.getClass().isAnnotationPresent(annotation);
}
/**
* Get generic parameters of a class
*
@ -50,25 +50,25 @@ public class Reflect {
public static Class<?>[] getGenericParameters(Class<?> clazz)
{
// BEHOLD, MAGIC!
final Type evtc = clazz.getGenericSuperclass();
if (evtc instanceof ParameterizedType) {
final Type[] types = ((ParameterizedType) evtc).getActualTypeArguments();
final Class<?>[] classes = new Class<?>[types.length];
for (int i = 0; i < types.length; i++) {
classes[i] = (Class<?>) types[i];
}
return classes;
}
throw new RuntimeException(Support.str(clazz) + " is not generic.");
throw new RuntimeException(Str.val(clazz) + " is not generic.");
}
/**
* Get value of a public static final field. If the modifiers don't match,
* an exception is thrown.
@ -82,15 +82,15 @@ public class Reflect {
public static Object getConstantFieldValue(Class<?> objClass, String fieldName) throws ReflectiveOperationException
{
final Field fld = objClass.getDeclaredField(fieldName);
final int modif = fld.getModifiers();
if (!Modifier.isFinal(modif) || !Modifier.isStatic(modif)) {
throw new ReflectiveOperationException("The " + fieldName + " field of " + Support.str(objClass) + " must be static and final!");
throw new ReflectiveOperationException("The " + fieldName + " field of " + Str.val(objClass) + " must be static and final!");
}
fld.setAccessible(true);
return fld.get(null);
}
}

@ -0,0 +1,231 @@
package mightypork.utils;
import mightypork.utils.annotations.Alias;
import mightypork.utils.math.AlignX;
/**
* General purpose string utilities
*
* @author Ondřej Hruška (MightyPork)
*/
public class Str {
public static String fromLastDot(String s)
{
return fromLast(s, '.');
}
public static String toLastDot(String s)
{
return toLast(s, '.');
}
public static String fromLast(String s, char c)
{
if (s == null) return null;
if (s.lastIndexOf(c) == -1) return "";
return s.substring(s.lastIndexOf(c) + 1, s.length());
}
public static String toLast(String s, char c)
{
if (s == null) return null;
if (s.lastIndexOf(c) == -1) return s;
return s.substring(0, s.lastIndexOf(c));
}
public static String fromFirst(String s, char c)
{
if (s == null) return null;
if (s.indexOf(c) == -1) return "";
return s.substring(s.indexOf(c) + 1, s.length());
}
public static String toFirst(String s, char c)
{
if (s == null) return null;
if (s.indexOf(c) == -1) return s;
return s.substring(0, s.indexOf(c));
}
public static String fromEnd(String s, int chars)
{
return s.substring(s.length() - chars, s.length());
}
public static String fromStart(String s, int chars)
{
return s.substring(0, chars);
}
public static String pad(String s, int length)
{
return pad(s, length, AlignX.LEFT);
}
public static String pad(String s, int length, AlignX align)
{
return pad(s, length, align, ' ');
}
public static String pad(String s, int length, AlignX align, char fill)
{
final String filling = repeat("" + fill, length);
switch (align) {
case LEFT:
s += filling;
return fromStart(s, length);
case RIGHT:
s += filling;
return fromEnd(s, length);
case CENTER:
if (s.length() >= length) return s;
s = filling + s + filling;
final int cut = (int) (s.length() / 2D - length / 2D);
return s.substring(cut, s.length() - cut);
}
throw new IllegalArgumentException("Impossible error.");
}
/**
* Repeat a string
*
* @param repeated string
* @param count
* @return output
*/
public static String repeat(String repeated, int count)
{
String s = "";
for (int i = 0; i < count; i++)
s += repeated;
return s;
}
public static boolean isValidFilenameChar(char ch)
{
return isValidFilenameString(Character.toString(ch));
}
public static boolean isValidFilenameString(String filename)
{
return filename.matches("[a-zA-Z0-9 +\\-.,_%@#!]+");
}
public static String ellipsisStart(String orig, int length)
{
if (orig.length() > length) {
orig = "\u2026" + orig.substring(length, orig.length());
}
return orig;
}
public static String ellipsisEnd(String orig, int length)
{
if (orig.length() > length) {
orig = orig.substring(0, length - 1) + "\u2026";
}
return orig;
}
/**
* Convert a class to string, preserving name and outer class, but excluding
* path.
*
* @param cls the class
* @return class name
*/
public static String val(Class<?> cls)
{
final Alias ln = cls.getAnnotation(Alias.class);
if (ln != null) {
return ln.name();
}
String name = cls.getName();
String sep = "";
if (name.contains("$")) {
name = name.substring(name.lastIndexOf("$") + 1);
sep = "$";
} else {
name = name.substring(name.lastIndexOf(".") + 1);
sep = ".";
}
final Class<?> enclosing = cls.getEnclosingClass();
return (enclosing == null ? "" : Str.val(enclosing) + sep) + name;
}
/**
* Convert double to string, remove the mess at the end.
*
* @param d double
* @return string
*/
public static String val(Double d)
{
String s = d.toString();
s = s.replace(',', '.');
s = s.replaceAll("([0-9]+\\.[0-9]+)00+[0-9]+", "$1");
s = s.replaceAll("0+$", "");
s = s.replaceAll("\\.$", "");
return s;
}
/**
* Convert object to string. If the object overrides toString(), it is
* caled. Otherwise it's class name is converted to string.
*
* @param o object
* @return string representation
*/
public static String val(Object o)
{
if (o == null) return "<null>";
boolean hasToString = false;
try {
hasToString = (o.getClass().getMethod("toString").getDeclaringClass() != Object.class);
} catch (final Throwable t) {
// oh well..
}
if (hasToString) {
return o.toString();
} else {
return val(o.getClass());
}
}
}

@ -9,8 +9,6 @@ import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import mightypork.utils.annotations.Alias;
/**
* Miscelanous utilities
@ -18,7 +16,7 @@ import mightypork.utils.annotations.Alias;
* @author Ondřej Hruška (MightyPork)
*/
public final class Support {
/**
* Create a new thread of the runnable, and start it.
*
@ -31,8 +29,8 @@ public final class Support {
t.start();
return t;
}
/**
* Pick first non-null option
*
@ -44,11 +42,11 @@ public final class Support {
for (final Object o : options) {
if (o != null) return o;
}
return null; // all null
}
/**
* Get current time/date for given format.
*
@ -59,8 +57,8 @@ public final class Support {
{
return (new SimpleDateFormat(format)).format(new Date());
}
/**
* Parse array of vararg key, value pairs to a LinkedHashMap.<br>
* Example:
@ -85,11 +83,11 @@ public final class Support {
public static <K, V> Map<K, V> parseVarArgs(Object... args) throws ClassCastException, IllegalArgumentException
{
final LinkedHashMap<K, V> attrs = new LinkedHashMap<>();
if (args.length % 2 != 0) {
throw new IllegalArgumentException("Odd number of elements in varargs map!");
}
K key = null;
for (final Object o : args) {
if (key == null) {
@ -100,11 +98,11 @@ public final class Support {
key = null;
}
}
return attrs;
}
/**
* Get if an Object is in array (using equals)
*
@ -119,8 +117,8 @@ public final class Support {
}
return false;
}
/**
* Get if string is in array
*
@ -140,8 +138,8 @@ public final class Support {
return false;
}
}
/**
* Make enumeration iterable
*
@ -152,7 +150,7 @@ public final class Support {
{
return new IterableEnumerationWrapper<>(enumeration);
}
/**
* Helper class for iterationg over an {@link Enumeration}
*
@ -160,10 +158,10 @@ public final class Support {
* @param <T> target element type (will be cast)
*/
private static class IterableEnumerationWrapper<T> implements Iterable<T> {
private final Enumeration<? extends T> enumeration;
/**
* @param enumeration the iterated enumeration
*/
@ -171,27 +169,27 @@ public final class Support {
{
this.enumeration = enumeration;
}
@Override
public Iterator<T> iterator()
{
return new Iterator<T>() {
@Override
public boolean hasNext()
{
return enumeration.hasMoreElements();
}
@Override
public T next()
{
return enumeration.nextElement();
}
@Override
public void remove()
{
@ -199,99 +197,6 @@ public final class Support {
}
};
}
}
/**
* Convert a class to string, preserving name and outer class, but excluding
* path.
*
* @param cls the class
* @return class name
*/
public static String str(Class<?> cls)
{
final Alias ln = cls.getAnnotation(Alias.class);
if (ln != null) {
return ln.name();
}
String name = cls.getName();
String sep = "";
if (name.contains("$")) {
name = name.substring(name.lastIndexOf("$") + 1);
sep = "$";
} else {
name = name.substring(name.lastIndexOf(".") + 1);
sep = ".";
}
final Class<?> enclosing = cls.getEnclosingClass();
return (enclosing == null ? "" : Support.str(enclosing) + sep) + name;
}
/**
* Convert double to string, remove the mess at the end.
*
* @param d double
* @return string
*/
public static String str(Double d)
{
String s = d.toString();
s = s.replace(',', '.');
s = s.replaceAll("([0-9]+\\.[0-9]+)00+[0-9]+", "$1");
s = s.replaceAll("0+$", "");
s = s.replaceAll("\\.$", "");
return s;
}
/**
* Convert float to string, remove the mess at the end.
*
* @param f float
* @return string
*/
public static String str(Float f)
{
String s = f.toString();
s = s.replaceAll("([0-9]+\\.[0-9]+)00+[0-9]+", "$1");
s = s.replaceAll("0+$", "");
s = s.replaceAll("\\.$", "");
return s;
}
/**
* Convert object to string. If the object overrides toString(), it is
* caled. Otherwise it's class name is converted to string.
*
* @param o object
* @return string representation
*/
public static String str(Object o)
{
if (o == null) return "<null>";
boolean hasToString = false;
try {
hasToString = (o.getClass().getMethod("toString").getDeclaringClass() != Object.class);
} catch (final Throwable t) {
// oh well..
}
if (hasToString) {
return o.toString();
} else {
return str(o.getClass());
}
}
}

@ -20,6 +20,6 @@ import java.lang.annotation.Target;
@Documented
@Target(ElementType.TYPE)
public @interface Alias {
String name();
}

@ -18,5 +18,5 @@ import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Documented
public @interface FactoryMethod {
}

@ -23,7 +23,7 @@ import mightypork.utils.logging.Log;
* @author Ondřej Hruška (MightyPork)
*/
public class SimpleConfig {
/**
* Load list from file
*
@ -34,11 +34,11 @@ public class SimpleConfig {
public static List<String> listFromFile(File file) throws IOException
{
final String fileText = FileUtil.fileToString(file);
return listFromString(fileText);
}
/**
* Load map from file
*
@ -49,11 +49,11 @@ public class SimpleConfig {
public static Map<String, String> mapFromFile(File file) throws IOException
{
final String fileText = FileUtil.fileToString(file);
return mapFromString(fileText);
}
/**
* Load list from string
*
@ -63,27 +63,27 @@ public class SimpleConfig {
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
*
@ -93,51 +93,51 @@ public class SimpleConfig {
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
*
@ -149,35 +149,35 @@ public class SimpleConfig {
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;
}
FileUtil.stringToFile(target, text);
}
/**
* Save list to file
*
@ -188,18 +188,18 @@ public class SimpleConfig {
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;
}
FileUtil.stringToFile(target, text);
}
}

@ -14,14 +14,14 @@ import mightypork.utils.annotations.Stub;
* @param <T> property type
*/
public abstract class Property<T> {
protected final String comment;
protected final String key;
protected T value;
protected final T defaultValue;
/**
* Create a property without comment
*
@ -33,8 +33,8 @@ public abstract class Property<T> {
{
this(key, defaultValue, null);
}
/**
* Create a property with a comment
*
@ -51,8 +51,8 @@ public abstract class Property<T> {
this.value = defaultValue;
this.defaultValue = defaultValue;
}
/**
* Parse a string representation of the value into this property. If the
* value cannot be decoded, use the default value instead.
@ -60,8 +60,8 @@ public abstract class Property<T> {
* @param string property value as string
*/
public abstract void fromString(String string);
/**
* Get property value as string (compatible with `fromString())
*
@ -73,8 +73,8 @@ public abstract class Property<T> {
{
return Convert.toString(value, Convert.toString(defaultValue));
}
/**
* Get the current property value
*
@ -84,8 +84,8 @@ public abstract class Property<T> {
{
return value;
}
/**
* Set property value.<br>
* Uses Object to allow setValue(Object) method in {@link PropertyManager}
@ -98,8 +98,8 @@ public abstract class Property<T> {
{
this.value = (T) value;
}
/**
* Get property comment.
*
@ -109,8 +109,8 @@ public abstract class Property<T> {
{
return comment;
}
/**
* Get property key
*

@ -22,12 +22,12 @@ import mightypork.utils.logging.Log;
* @author Ondřej Hruška (MightyPork)
*/
public class PropertyManager {
private final TreeMap<String, Property<?>> entries = new TreeMap<>();
private final TreeMap<String, String> renameTable = new TreeMap<>();
private final PropertyStore props;
/**
* Create property manager from file path and a header comment.<br>
* This is the same as using a {@link PropertyFile} store.
@ -39,8 +39,8 @@ public class PropertyManager {
{
this(new PropertyFile(file, comment));
}
/**
* Create property manager based on provided {@link PropertyStore}
*
@ -51,61 +51,61 @@ public class PropertyManager {
{
this.props = props;
}
/**
* Load from file
*/
public void load()
{
props.load();
// rename keys (useful if keys change but value is to be kept)
for (final Entry<String, String> entry : renameTable.entrySet()) {
final String value = props.getProperty(entry.getKey());
if (value == null) continue;
final String oldKey = entry.getKey();
final String newKey = entry.getValue();
props.removeProperty(oldKey);
props.setProperty(newKey, value, entries.get(newKey).getComment());
}
for (final Property<?> entry : entries.values()) {
entry.fromString(props.getProperty(entry.getKey()));
}
}
public void save()
{
try {
final ArrayList<String> keyList = new ArrayList<>();
// validate entries one by one, replace with default when needed
for (final Property<?> entry : entries.values()) {
keyList.add(entry.getKey());
props.setProperty(entry.getKey(), entry.toString(), entry.getComment());
}
// removed unused props
for (final String key : props.keys()) {
if (!keyList.contains(key)) {
props.removeProperty(key);
}
}
props.save();
} catch (final IOException ioe) {
ioe.printStackTrace();
}
}
/**
* Get a property entry (rarely used)
*
@ -121,8 +121,8 @@ public class PropertyManager {
return null;
}
}
/**
* Get boolean property
*
@ -133,8 +133,8 @@ public class PropertyManager {
{
return Convert.toBoolean(getProperty(k).getValue());
}
/**
* Get numeric property
*</