Cleanup and minor javadoc fixes

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

@ -4,14 +4,14 @@ package mightypork.utils;
/**
* Utility for converting Object to data types; Can also convert strings to data
* types.
*
*
* @author Ondřej Hruška (MightyPork)
*/
public class Convert {
/**
* Get INTEGER
*
*
* @param o object
* @param def default value
* @return integer
@ -26,11 +26,11 @@ public class Convert {
} catch (final NumberFormatException e) {}
return def;
}
/**
* Get DOUBLE
*
*
* @param o object
* @param def default value
* @return double
@ -45,11 +45,11 @@ public class Convert {
} catch (final NumberFormatException e) {}
return def;
}
/**
* Get FLOAT
*
*
* @param o object
* @param def default value
* @return float
@ -62,11 +62,11 @@ public class Convert {
} catch (final NumberFormatException e) {}
return def;
}
/**
* Get BOOLEAN
*
*
* @param o object
* @param def default value
* @return 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,26 +85,26 @@ 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
*
*
* @param o object
* @param def default value
* @return String
@ -113,22 +113,22 @@ 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 Class<?>) {
return Support.str(o);
}
return o.toString();
}
/**
* Get INTEGER
*
*
* @param o object
* @return integer
*/
@ -136,11 +136,11 @@ public class Convert {
{
return toInteger(o, 0);
}
/**
* Get DOUBLE
*
*
* @param o object
* @return double
*/
@ -148,11 +148,11 @@ public class Convert {
{
return toDouble(o, 0d);
}
/**
* Get FLOAT
*
*
* @param o object
* @return float
*/
@ -160,11 +160,11 @@ public class Convert {
{
return toFloat(o, 0f);
}
/**
* Get BOOLEAN
*
*
* @param o object
* @return boolean
*/
@ -172,11 +172,11 @@ public class Convert {
{
return toBoolean(o, false);
}
/**
* Get STRING
*
*
* @param o object
* @return String
*/

@ -1,20 +1,25 @@
package mightypork.utils;
import java.util.*;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* Map sorting utils
*
*
* @author Ondřej Hruška (MightyPork)
*/
public class MapSort {
/**
* Sort a map by keys, maintaining key-value pairs, using natural order.
*
*
* @param map map to be sorted
* @return linked hash map with sorted entries
*/
@ -27,7 +32,7 @@ public class MapSort {
/**
* Sort a map by keys, maintaining key-value pairs.
*
*
* @param map map to be sorted
* @param comparator a comparator, or null for natural ordering
* @return linked hash map with sorted entries
@ -61,7 +66,7 @@ public class MapSort {
/**
* Sort a map by values, maintaining key-value pairs, using natural order.
*
*
* @param map map to be sorted
* @return linked hash map with sorted entries
*/
@ -74,7 +79,7 @@ public class MapSort {
/**
* Sort a map by values, maintaining key-value pairs.
*
*
* @param map map to be sorted
* @param comparator a comparator, or null for natural ordering
* @return linked hash map with sorted entries
@ -85,6 +90,7 @@ public class MapSort {
Collections.sort(entries, new Comparator<Map.Entry<K, V>>() {
@SuppressWarnings("unchecked")
@Override
public int compare(Entry<K, V> o1, Entry<K, V> o2)
{

@ -10,14 +10,14 @@ import java.lang.reflect.Type;
/**
* Miscelanous reflection-related utilities
*
*
* @author Ondřej Hruška (MightyPork)
*/
public class Reflect {
/**
* Get annotation of given type from an object
*
*
* @param tested the examined object
* @param annotation annotation we want
* @return the anotation on that object, or null
@ -26,11 +26,11 @@ public class Reflect {
{
return tested.getClass().getAnnotation(annotation);
}
/**
* Check if an object has an annotation of given trype
*
*
* @param tested the examined object
* @param annotation annotation we want
* @return true if the annotation is present on the object
@ -39,48 +39,58 @@ public class Reflect {
{
return tested.getClass().isAnnotationPresent(annotation);
}
/**
* Get generic parameters of a class
*
*
* @param clazz the examined class
* @return parameter types
*/
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.");
}
/**
* Get value of a public static final field. If the modifiers don't match,
* an exception is thrown.
*
* @param objClass the class
* @param fieldName field to retrieve
* @return the field value
* @throws ReflectiveOperationException if the field is not constant, or if
* the value could not be retrieved.
*/
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 RuntimeException("The " + fieldName + " field of " + Support.str(objClass) + " must be static and final!");
throw new ReflectiveOperationException("The " + fieldName + " field of " + Support.str(objClass) + " must be static and final!");
}
fld.setAccessible(true);
return fld.get(null);
}
}

@ -14,14 +14,14 @@ import mightypork.utils.annotations.Alias;
/**
* Miscelanous utilities
*
*
* @author Ondřej Hruška (MightyPork)
*/
public final class Support {
/**
* Create a new thread of the runnable, and start it.
*
*
* @param r runnable
* @return the thread started
*/
@ -35,7 +35,7 @@ public final class Support {
/**
* Pick first non-null option
*
*
* @param options options
* @return the selected option
*/
@ -51,7 +51,7 @@ public final class Support {
/**
* Get current time/date for given format.
*
*
* @param format format, according to {@link DateFormat}.
* @return the formatted time/date
*/
@ -64,7 +64,7 @@ public final class Support {
/**
* Parse array of vararg key, value pairs to a LinkedHashMap.<br>
* Example:
*
*
* <pre>
* Object[] array = {
* &quot;one&quot;, 1,
@ -72,10 +72,10 @@ public final class Support {
* &quot;three&quot;, 9,
* &quot;four&quot;, 16
* };
*
*
* Map&lt;String, Integer&gt; args = parseVarArgs(array);
* </pre>
*
*
* @param args varargs
* @return LinkedHashMap
* @throws ClassCastException in case of incompatible type in the array
@ -107,7 +107,7 @@ public final class Support {
/**
* Get if an Object is in array (using equals)
*
*
* @param needle checked Object
* @param haystack array of Objects
* @return is in array
@ -123,7 +123,7 @@ public final class Support {
/**
* Get if string is in array
*
*
* @param needle checked string
* @param case_sensitive case sensitive comparision
* @param haystack array of possible values
@ -144,7 +144,7 @@ public final class Support {
/**
* Make enumeration iterable
*
*
* @param enumeration enumeration
* @return iterable wrapper
*/
@ -155,7 +155,7 @@ public final class Support {
/**
* Helper class for iterationg over an {@link Enumeration}
*
*
* @author Ondřej Hruška (MightyPork)
* @param <T> target element type (will be cast)
*/
@ -167,7 +167,8 @@ public final class Support {
/**
* @param enumeration the iterated enumeration
*/
public IterableEnumerationWrapper(Enumeration<? extends T> enumeration) {
public IterableEnumerationWrapper(Enumeration<? extends T> enumeration)
{
this.enumeration = enumeration;
}
@ -205,9 +206,9 @@ public final class Support {
/**
* Convert a class to string, preserving name and outer class, but excluding
* path.
*
* @param cls
* @return
*
* @param cls the class
* @return class name
*/
public static String str(Class<?> cls)
{
@ -236,7 +237,7 @@ public final class Support {
/**
* Convert double to string, remove the mess at the end.
*
*
* @param d double
* @return string
*/
@ -253,7 +254,7 @@ public final class Support {
/**
* Convert float to string, remove the mess at the end.
*
*
* @param f float
* @return string
*/
@ -270,7 +271,7 @@ public final class Support {
/**
* 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
*/

@ -1,13 +1,18 @@
package mightypork.utils.annotations;
import java.lang.annotation.*;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Specify pretty name to be used when logging / converting class name to
* string.
*
*
* @author Ondřej Hruška (MightyPork)
*/
@Retention(RetentionPolicy.RUNTIME)
@ -15,6 +20,6 @@ import java.lang.annotation.*;
@Documented
@Target(ElementType.TYPE)
public @interface Alias {
String name();
}

@ -11,12 +11,12 @@ import java.lang.annotation.Target;
/**
* Marks a static factory method. This is a description annotation and has no
* other function.
*
*
* @author Ondřej Hruška (MightyPork)
*/
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.METHOD)
@Documented
public @interface FactoryMethod {
}

@ -12,7 +12,7 @@ import java.lang.annotation.Target;
* Marked method can be safely overriden; it's left blank (or with default
* implementation) as a convenience.<br>
* This is a description annotation and has no other function.
*
*
* @author Ondřej Hruška (MightyPork)
*/
@Documented

@ -19,14 +19,14 @@ import mightypork.utils.logging.Log;
* 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 Ondřej Hruška (MightyPork)
*/
public class SimpleConfig {
/**
* Load list from file
*
*
* @param file file
* @return map of keys and values
* @throws IOException
@ -34,14 +34,14 @@ 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
*
*
* @param file file
* @return map of keys and values
* @throws IOException
@ -49,98 +49,98 @@ 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
*
*
* @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.
@ -149,38 +149,38 @@ 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
*
*
* @param target
* @param data
* @throws IOException
@ -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);
}
}

@ -9,7 +9,7 @@ import mightypork.utils.annotations.Stub;
* Property entry for the {@link PropertyManager}.<br>
* Extending this class can be used to add custom property types that are not
* supported by default.
*
*
* @author Ondřej Hruška (MightyPork)
* @param <T> property type
*/
@ -24,26 +24,28 @@ public abstract class Property<T> {
/**
* Create a property without comment
*
*
* @param key key in the config file
* @param defaultValue defualt property value (used as fallback when
* parsing)
*/
public Property(String key, T defaultValue) {
public Property(String key, T defaultValue)
{
this(key, defaultValue, null);
}
/**
* Create a property with a comment
*
*
* @param key key in the config file
* @param defaultValue defualt property value (used as fallback when
* parsing)
* @param defaultValue default property value, used as fallback when
* parsing. Initially the value is assigned to defaultValue.
* @param comment optional property comment included above the property in
* the config file. Can be null.
*/
public Property(String key, T defaultValue, String comment) {
public Property(String key, T defaultValue, String comment)
{
this.comment = comment;
this.key = key;
this.value = defaultValue;
@ -54,7 +56,7 @@ public abstract class Property<T> {
/**
* Parse a string representation of the value into this property. If the
* value cannot be decoded, use the default value instead.
*
*
* @param string property value as string
*/
public abstract void fromString(String string);
@ -62,7 +64,7 @@ public abstract class Property<T> {
/**
* Get property value as string (compatible with `fromString())
*
*
* @return property value as string
*/
@Override
@ -75,7 +77,7 @@ public abstract class Property<T> {
/**
* Get the current property value
*
*
* @return the value
*/
public T getValue()
@ -87,7 +89,7 @@ public abstract class Property<T> {
/**
* Set property value.<br>
* Uses Object to allow setValue(Object) method in {@link PropertyManager}
*
*
* @param value value to set.
* @throws ClassCastException in case of incompatible type.
*/
@ -100,7 +102,7 @@ public abstract class Property<T> {
/**
* Get property comment.
*
*
* @return the comment text (can be null if no comment is defined)
*/
public String getComment()
@ -111,7 +113,7 @@ public abstract class Property<T> {
/**
* Get property key
*
*
* @return property key
*/
public String getKey()

@ -18,95 +18,97 @@ import mightypork.utils.logging.Log;
/**
* Property manager with advanced formatting and value checking.
*
*
* @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 PropertyStore props;
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.
*
*
* @param file property file
* @param comment header comment.
*/
public PropertyManager(File file, String comment) {
public PropertyManager(File file, String comment)
{
this(new PropertyFile(file, comment));
}
/**
* Create property manager based on provided {@link PropertyStore}
*
*
* @param props a property store implementation backing this property
* manager
*/
public PropertyManager(PropertyStore props) {
public PropertyManager(PropertyStore props)
{
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)
*
*
* @param k key
* @return the entry
*/
@ -119,11 +121,11 @@ public class PropertyManager {
return null;
}
}
/**
* Get boolean property
*
*
* @param k key
* @return the boolean found, or false
*/
@ -131,11 +133,11 @@ public class PropertyManager {
{
return Convert.toBoolean(getProperty(k).getValue());
}
/**
* Get numeric property
*
*
* @param k key
* @return the int found, or null
*/
@ -143,11 +145,11 @@ public class PropertyManager {
{
return Convert.toInteger(getProperty(k).getValue());
}
/**
* Get numeric property as double
*
*
* @param k key
* @return the double found, or null
*/
@ -155,11 +157,11 @@ public class PropertyManager {
{
return Convert.toDouble(getProperty(k).getValue());
}
/**
* Get string property
*
*
* @param k key
* @return the string found, or null
*/
@ -167,11 +169,11 @@ public class PropertyManager {
{
return Convert.toString(getProperty(k).getValue());
}
/**
* Get arbitrary property. Make sure it's of the right type!
*
*
* @param k key
* @return the prioperty found
*/
@ -184,11 +186,11 @@ public class PropertyManager {
return null;
}
}
/**
* Add a boolean property
*
*
* @param k key
* @param d default value
* @param comment the in-file comment
@ -197,11 +199,11 @@ public class PropertyManager {
{
addProperty(new BooleanProperty(k, d, comment));
}
/**
* Add a numeric property (double)
*
*
* @param k key
* @param d default value
* @param comment the in-file comment
@ -210,11 +212,11 @@ public class PropertyManager {
{
addProperty(new DoubleProperty(k, d, comment));
}
/**
* Add a numeric property
*
*
* @param k key
* @param d default value
* @param comment the in-file comment
@ -223,11 +225,11 @@ public class PropertyManager {
{
addProperty(new IntegerProperty(k, d, comment));
}
/**
* Add a string property
*
*
* @param k key
* @param d default value
* @param comment the in-file comment
@ -236,22 +238,22 @@ public class PropertyManager {
{
addProperty(new StringProperty(k, d, comment));
}
/**
* Add a generic property (can be used with custom property types)
*
*
* @param prop property to add
*/
public <T> void addProperty(Property<T> prop)
{
entries.put(prop.getKey(), prop);
}
/**
* Rename key before loading; value is preserved
*
*
* @param oldKey old key
* @param newKey new key
*/
@ -260,11 +262,11 @@ public class PropertyManager {
renameTable.put(oldKey, newKey);
return;
}
/**
* Set value saved to certain key.
*
*
* @param key key
* @param value the saved value
*/
@ -272,16 +274,16 @@ public class PropertyManager {
{
getProperty(key).setValue(value);
}
/**
* Set heading comment of the property store.
*
*
* @param fileComment comment text (can be multi-line)
*/
public void setFileComment(String fileComment)
{
props.setComment(fileComment);
}
}

@ -9,70 +9,70 @@ import java.util.Collection;
* Interface for a property store (used by {@link PropertyManager}).<br>
* Due to this abstraction, different kind of property storage can be used, not
* only a file.
*
*
* @author Ondřej Hruška (MightyPork)
*/
public interface PropertyStore {
/**
* Set a header comment
*
*
* @param comment the comment text (can be multi-line)
*/
void setComment(String comment);
/**
* Load properties from the file / store. If the file does not exist or is
* inaccessible, nothing is loaded.
*/
void load();