From 16956fa927a08c137ab2cf95cb3b3da5ad81f054 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ond=C5=99ej=20Hru=C5=A1ka?=
Date: Mon, 28 Jul 2014 14:27:38 +0200
Subject: [PATCH] Cleanup and minor javadoc fixes
---
src/mightypork/utils/Convert.java | 76 +-
src/mightypork/utils/MapSort.java | 18 +-
src/mightypork/utils/Reflect.java | 54 +-
src/mightypork/utils/Support.java | 37 +-
src/mightypork/utils/annotations/Alias.java | 11 +-
.../utils/annotations/FactoryMethod.java | 4 +-
src/mightypork/utils/annotations/Stub.java | 2 +-
src/mightypork/utils/config/SimpleConfig.java | 104 +--
.../utils/config/propmgr/Property.java | 28 +-
.../utils/config/propmgr/PropertyManager.java | 138 ++--
.../utils/config/propmgr/PropertyStore.java | 44 +-
.../propmgr/properties/BooleanProperty.java | 18 +-
.../propmgr/properties/DoubleProperty.java | 18 +-
.../propmgr/properties/IntegerProperty.java | 18 +-
.../propmgr/properties/StringProperty.java | 18 +-
.../config/propmgr/store/PropertyFile.java | 70 +-
.../propmgr/store/SortedProperties.java | 114 +--
src/mightypork/utils/eventbus/BusEvent.java | 50 +-
src/mightypork/utils/eventbus/EventBus.java | 215 +++---
.../utils/eventbus/EventChannel.java | 93 +--
.../utils/eventbus/clients/BusNode.java | 40 +-
.../utils/eventbus/clients/ClientHub.java | 24 +-
.../utils/eventbus/clients/ClientList.java | 7 +-
.../eventbus/clients/DelegatingClient.java | 10 +-
.../eventbus/clients/DelegatingList.java | 40 +-
.../eventbus/clients/ToggleableClient.java | 6 +-
.../utils/eventbus/events/DestroyEvent.java | 6 +-
.../utils/eventbus/events/UpdateEvent.java | 15 +-
.../eventbus/events/flags/DelayedEvent.java | 11 +-
.../eventbus/events/flags/DirectEvent.java | 9 +-
.../events/flags/NonConsumableEvent.java | 4 +-
.../events/flags/NonRejectableEvent.java | 4 +-
.../eventbus/events/flags/NotLoggedEvent.java | 9 +-
.../events/flags/SingleReceiverEvent.java | 9 +-
.../exceptions/CorruptDataException.java | 30 +-
.../exceptions/IllegalValueException.java | 30 +-
.../exceptions/KeyAlreadyExistsException.java | 30 +-
.../utils/files/FileSuffixFilter.java | 25 +-
src/mightypork/utils/files/FileTreeDiff.java | 96 +--
src/mightypork/utils/files/FileUtil.java | 64 +-
src/mightypork/utils/files/InstanceLock.java | 16 +-
src/mightypork/utils/files/OsUtils.java | 52 +-
src/mightypork/utils/files/WorkDir.java | 96 +++
.../utils/files/zip/ZipBuilder.java | 65 +-
src/mightypork/utils/files/zip/ZipUtils.java | 92 +--
.../utils/interfaces/Destroyable.java | 4 +-
.../utils/interfaces/Enableable.java | 10 +-
src/mightypork/utils/interfaces/Hideable.java | 8 +-
.../utils/interfaces/Pauseable.java | 14 +-
src/mightypork/utils/interfaces/Pollable.java | 4 +-
.../utils/interfaces/Updateable.java | 6 +-
src/mightypork/utils/ion/Ion.java | 243 ++++---
src/mightypork/utils/ion/IonBinary.java | 12 +-
src/mightypork/utils/ion/IonBundled.java | 12 +-
src/mightypork/utils/ion/IonDataBundle.java | 216 +++---
src/mightypork/utils/ion/IonInput.java | 247 ++++---
src/mightypork/utils/ion/IonMapWrapper.java | 34 +-
src/mightypork/utils/ion/IonOutput.java | 225 +++---
.../utils/ion/IonSequenceWrapper.java | 34 +-
src/mightypork/utils/ion/IonizerBinary.java | 18 +-
src/mightypork/utils/ion/IonizerBundled.java | 18 +-
src/mightypork/utils/logging/Log.java | 172 ++---
.../utils/logging/monitors/LogMonitor.java | 22 +-
.../logging/monitors/LogMonitorStdout.java | 4 +-
.../utils/logging/writers/ArchivingLog.java | 62 +-
.../utils/logging/writers/LogWriter.java | 42 +-
.../utils/logging/writers/SimpleLog.java | 81 +--
src/mightypork/utils/math/AlignX.java | 2 +-
src/mightypork/utils/math/AlignY.java | 2 +-
src/mightypork/utils/math/Calc.java | 181 ++---
src/mightypork/utils/math/Polar.java | 92 +--
src/mightypork/utils/math/Range.java | 129 ++--
src/mightypork/utils/math/algo/Coord.java | 93 +--
src/mightypork/utils/math/algo/Move.java | 37 +-
src/mightypork/utils/math/algo/Moves.java | 62 +-
.../utils/math/algo/floodfill/FloodFill.java | 48 +-
.../math/algo/pathfinding/Heuristic.java | 4 +-
.../math/algo/pathfinding/PathFinder.java | 133 ++--
.../algo/pathfinding/PathFinderProxy.java | 33 +-
.../heuristics/DiagonalHeuristic.java | 2 +-
.../heuristics/ManhattanHeuristic.java | 2 +-
src/mightypork/utils/math/angles/Angles.java | 20 +-
src/mightypork/utils/math/angles/Deg.java | 70 +-
src/mightypork/utils/math/angles/Rad.java | 46 +-
.../utils/math/animation/Animator.java | 90 +--
.../utils/math/animation/AnimatorBounce.java | 40 +-
.../utils/math/animation/AnimatorRewind.java | 34 +-
.../utils/math/animation/Easing.java | 156 ++--
.../utils/math/animation/NumAnimated.java | 228 +++---
.../utils/math/animation/NumAnimatedDeg.java | 31 +-
.../utils/math/animation/NumAnimatedRad.java | 31 +-
.../utils/math/animation/VectAnimated.java | 138 ++--
src/mightypork/utils/math/color/Color.java | 136 ++--
.../utils/math/color/ColorAlphaAdjuster.java | 27 +-
src/mightypork/utils/math/color/ColorHsb.java | 33 +-
src/mightypork/utils/math/color/ColorRgb.java | 27 +-
src/mightypork/utils/math/color/Grad.java | 15 +-
src/mightypork/utils/math/color/GradH.java | 9 +-
src/mightypork/utils/math/color/GradV.java | 9 +-
src/mightypork/utils/math/color/pal/CGA.java | 8 +-
src/mightypork/utils/math/color/pal/CMDR.java | 4 +-
.../utils/math/color/pal/PAL16.java | 12 +-
src/mightypork/utils/math/color/pal/RGB.java | 14 +-
src/mightypork/utils/math/color/pal/ZX.java | 8 +-
.../math/constraints/CachedConstraint.java | 22 +-
.../math/constraints/CachedDigestable.java | 16 +-
.../utils/math/constraints/DigestCache.java | 30 +-
.../utils/math/constraints/Digestable.java | 8 +-
.../utils/math/constraints/num/Num.java | 458 ++++++------
.../utils/math/constraints/num/NumBound.java | 6 +-
.../utils/math/constraints/num/NumConst.java | 156 ++--
.../constraints/num/PluggableNumBound.java | 6 +-
.../math/constraints/num/batch/NumMul.java | 20 +-
.../math/constraints/num/batch/NumSum.java | 20 +-
.../num/caching/AbstractNumCache.java | 47 +-
.../constraints/num/caching/NumCache.java | 21 +-
.../constraints/num/caching/NumDigest.java | 13 +-
.../constraints/num/proxy/NumAdapter.java | 8 +-
.../math/constraints/num/proxy/NumProxy.java | 28 +-
.../math/constraints/num/var/NumMutable.java | 18 +-
.../math/constraints/num/var/NumVar.java | 28 +-
.../constraints/rect/PluggableRectBound.java | 6 +-
.../utils/math/constraints/rect/Rect.java | 612 ++++++++--------
.../math/constraints/rect/RectBound.java | 4 +-
.../math/constraints/rect/RectConst.java | 271 +++----
.../constraints/rect/builders/TiledRect.java | 61 +-
.../rect/caching/AbstractRectCache.java | 39 +-
.../constraints/rect/caching/RectCache.java | 21 +-
.../constraints/rect/caching/RectDigest.java | 22 +-
.../constraints/rect/proxy/RectAdapter.java | 26 +-
.../constraints/rect/proxy/RectProxy.java | 28 +-
.../rect/proxy/RectVectAdapter.java | 21 +-
.../constraints/rect/var/RectMutable.java | 44 +-
.../math/constraints/rect/var/RectVar.java | 27 +-
.../constraints/vect/PluggableVectBound.java | 6 +-
.../utils/math/constraints/vect/Vect.java | 680 +++++++++---------
.../math/constraints/vect/VectBound.java | 4 +-
.../math/constraints/vect/VectConst.java | 216 +++---
.../vect/caching/AbstractVectCache.java | 39 +-
.../constraints/vect/caching/VectCache.java | 19 +-
.../constraints/vect/caching/VectDigest.java | 13 +-
.../constraints/vect/proxy/VectAdapter.java | 18 +-
.../vect/proxy/VectNumAdapter.java | 32 +-
.../constraints/vect/proxy/VectProxy.java | 28 +-
.../constraints/vect/var/VectMutable.java | 40 +-
.../math/constraints/vect/var/VectVar.java | 39 +-
src/mightypork/utils/math/noise/NoiseGen.java | 58 +-
.../math/noise/PerlinNoiseGenerator.java | 245 +++----
.../utils/math/timing/FpsMeter.java | 12 +-
.../utils/math/timing/Profiler.java | 51 +-
.../utils/math/timing/TaskRepeater.java | 27 +-
.../utils/math/timing/TimedTask.java | 22 +-
.../utils/math/timing/TimerDelta.java | 25 +-
.../utils/math/timing/TimerFps.java | 49 +-
.../utils/string/AlphanumComparator.java | 28 +-
.../utils/string/StringProvider.java | 4 +-
src/mightypork/utils/string/StringUtil.java | 38 +-
.../utils/string/StringWrapper.java | 25 +-
.../utils/string/validation/CharFilter.java | 2 +-
.../string/validation/CharFilterRegex.java | 15 +-
.../validation/CharFilterWhitelist.java | 15 +-
.../utils/string/validation/StringFilter.java | 4 +-
src/mightypork/utils/struct/Mutable.java | 37 +-
src/mightypork/utils/struct/Pair.java | 37 +-
src/mightypork/utils/struct/Triad.java | 45 +-
165 files changed, 4872 insertions(+), 4502 deletions(-)
create mode 100644 src/mightypork/utils/files/WorkDir.java
diff --git a/src/mightypork/utils/Convert.java b/src/mightypork/utils/Convert.java
index d75a806..fa2c4ea 100644
--- a/src/mightypork/utils/Convert.java
+++ b/src/mightypork/utils/Convert.java
@@ -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
*/
diff --git a/src/mightypork/utils/MapSort.java b/src/mightypork/utils/MapSort.java
index ca94859..55b9abe 100644
--- a/src/mightypork/utils/MapSort.java
+++ b/src/mightypork/utils/MapSort.java
@@ -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>() {
+ @SuppressWarnings("unchecked")
@Override
public int compare(Entry o1, Entry o2)
{
diff --git a/src/mightypork/utils/Reflect.java b/src/mightypork/utils/Reflect.java
index a16deca..4edd3e2 100644
--- a/src/mightypork/utils/Reflect.java
+++ b/src/mightypork/utils/Reflect.java
@@ -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);
}
-
+
}
diff --git a/src/mightypork/utils/Support.java b/src/mightypork/utils/Support.java
index 8bf4b92..7923fd5 100644
--- a/src/mightypork/utils/Support.java
+++ b/src/mightypork/utils/Support.java
@@ -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.
* Example:
- *
+ *
*
* Object[] array = {
* "one", 1,
@@ -72,10 +72,10 @@ public final class Support {
* "three", 9,
* "four", 16
* };
- *
+ *
* Map<String, Integer> args = parseVarArgs(array);
*
- *
+ *
* @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 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
*/
diff --git a/src/mightypork/utils/annotations/Alias.java b/src/mightypork/utils/annotations/Alias.java
index 7ffd1ad..e830233 100644
--- a/src/mightypork/utils/annotations/Alias.java
+++ b/src/mightypork/utils/annotations/Alias.java
@@ -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();
}
diff --git a/src/mightypork/utils/annotations/FactoryMethod.java b/src/mightypork/utils/annotations/FactoryMethod.java
index a502e90..50cd51a 100644
--- a/src/mightypork/utils/annotations/FactoryMethod.java
+++ b/src/mightypork/utils/annotations/FactoryMethod.java
@@ -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 {
-
+
}
diff --git a/src/mightypork/utils/annotations/Stub.java b/src/mightypork/utils/annotations/Stub.java
index 6e9d7a2..f27eba6 100644
--- a/src/mightypork/utils/annotations/Stub.java
+++ b/src/mightypork/utils/annotations/Stub.java
@@ -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.
* This is a description annotation and has no other function.
- *
+ *
* @author Ondřej Hruška (MightyPork)
*/
@Documented
diff --git a/src/mightypork/utils/config/SimpleConfig.java b/src/mightypork/utils/config/SimpleConfig.java
index 29550ba..70f8f6f 100644
--- a/src/mightypork/utils/config/SimpleConfig.java
+++ b/src/mightypork/utils/config/SimpleConfig.java
@@ -19,14 +19,14 @@ import mightypork.utils.logging.Log;
* empty lines and lines without "=" are ignored
* lines with "=" must have "key = value" format, or a warning is logged.
* 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 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 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 listFromString(String text)
{
final List 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 mapFromString(String text)
{
final LinkedHashMap 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 data, boolean allowNulls) throws IOException
{
final List lines = new ArrayList<>();
-
+
for (final Entry 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 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);
-
+
}
}
diff --git a/src/mightypork/utils/config/propmgr/Property.java b/src/mightypork/utils/config/propmgr/Property.java
index bea041a..f47a5ae 100644
--- a/src/mightypork/utils/config/propmgr/Property.java
+++ b/src/mightypork/utils/config/propmgr/Property.java
@@ -9,7 +9,7 @@ import mightypork.utils.annotations.Stub;
* Property entry for the {@link PropertyManager}.
* Extending this class can be used to add custom property types that are not
* supported by default.
- *
+ *
* @author Ondřej Hruška (MightyPork)
* @param property type
*/
@@ -24,26 +24,28 @@ public abstract class Property {
/**
* 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 {
/**
* 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 {
/**
* Get property value as string (compatible with `fromString())
- *
+ *
* @return property value as string
*/
@Override
@@ -75,7 +77,7 @@ public abstract class Property {
/**
* Get the current property value
- *
+ *
* @return the value
*/
public T getValue()
@@ -87,7 +89,7 @@ public abstract class Property {
/**
* Set property value.
* 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 {
/**
* 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 {
/**
* Get property key
- *
+ *
* @return property key
*/
public String getKey()
diff --git a/src/mightypork/utils/config/propmgr/PropertyManager.java b/src/mightypork/utils/config/propmgr/PropertyManager.java
index 782e39e..a98e051 100644
--- a/src/mightypork/utils/config/propmgr/PropertyManager.java
+++ b/src/mightypork/utils/config/propmgr/PropertyManager.java
@@ -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> entries = new TreeMap<>();
private final TreeMap renameTable = new TreeMap<>();
- private PropertyStore props;
-
-
+ private final PropertyStore props;
+
+
/**
* Create property manager from file path and a header comment.
* 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 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 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 void addProperty(Property 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);
}
-
+
}
diff --git a/src/mightypork/utils/config/propmgr/PropertyStore.java b/src/mightypork/utils/config/propmgr/PropertyStore.java
index be881af..e2cce83 100644
--- a/src/mightypork/utils/config/propmgr/PropertyStore.java
+++ b/src/mightypork/utils/config/propmgr/PropertyStore.java
@@ -9,70 +9,70 @@ import java.util.Collection;
* Interface for a property store (used by {@link PropertyManager}).
* 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();
-
-
+
+
/**
* Save properties to the file / store.
- *
+ *
* @throws IOException if the file cannot be created or written.
*/
void save() throws IOException;
-
-
+
+
/**
* Get a property value
- *
+ *
* @param key property key
* @return value retrieved from the file, or null if none found.
*/
String getProperty(String key);
-
-
+
+
/**
* Set a property value
- *
+ *
* @param key property key
* @param value property value to set
* @param comment property comment. Can be null.
*/
void setProperty(String key, String value, String comment);
-
-
+
+
/**
* Remove a property from the list.
- *
+ *
* @param key property key to remove
*/
void removeProperty(String key);
-
-
+
+
/**
* Clear the property list
*/
void clear();
-
-
+
+
/**
* Get keys collection (can be used for iterating)
- *
+ *
* @return keys collection
*/
public Collection keys();
diff --git a/src/mightypork/utils/config/propmgr/properties/BooleanProperty.java b/src/mightypork/utils/config/propmgr/properties/BooleanProperty.java
index 15bf83b..bf3cfd4 100644
--- a/src/mightypork/utils/config/propmgr/properties/BooleanProperty.java
+++ b/src/mightypork/utils/config/propmgr/properties/BooleanProperty.java
@@ -7,21 +7,23 @@ import mightypork.utils.config.propmgr.Property;
/**
* Boolean property
- *
+ *
* @author Ondřej Hruška (MightyPork)
*/
public class BooleanProperty extends Property {
-
- public BooleanProperty(String key, Boolean defaultValue) {
+
+ public BooleanProperty(String key, Boolean defaultValue)
+ {
super(key, defaultValue);
}
-
-
- public BooleanProperty(String key, Boolean defaultValue, String comment) {
+
+
+ public BooleanProperty(String key, Boolean defaultValue, String comment)
+ {
super(key, defaultValue, comment);
}
-
-
+
+
@Override
public void fromString(String string)
{
diff --git a/src/mightypork/utils/config/propmgr/properties/DoubleProperty.java b/src/mightypork/utils/config/propmgr/properties/DoubleProperty.java
index 97f6d66..71d2f71 100644
--- a/src/mightypork/utils/config/propmgr/properties/DoubleProperty.java
+++ b/src/mightypork/utils/config/propmgr/properties/DoubleProperty.java
@@ -7,21 +7,23 @@ import mightypork.utils.config.propmgr.Property;
/**
* Double property
- *
+ *
* @author Ondřej Hruška (MightyPork)
*/
public class DoubleProperty extends Property {
-
- public DoubleProperty(String key, Double defaultValue) {
+
+ public DoubleProperty(String key, Double defaultValue)
+ {
super(key, defaultValue);
}
-
-
- public DoubleProperty(String key, Double defaultValue, String comment) {
+
+
+ public DoubleProperty(String key, Double defaultValue, String comment)
+ {
super(key, defaultValue, comment);
}
-
-
+
+
@Override
public void fromString(String string)
{
diff --git a/src/mightypork/utils/config/propmgr/properties/IntegerProperty.java b/src/mightypork/utils/config/propmgr/properties/IntegerProperty.java
index 6ad0913..fc9fe7e 100644
--- a/src/mightypork/utils/config/propmgr/properties/IntegerProperty.java
+++ b/src/mightypork/utils/config/propmgr/properties/IntegerProperty.java
@@ -7,21 +7,23 @@ import mightypork.utils.config.propmgr.Property;
/**
* Integer property
- *
+ *
* @author Ondřej Hruška (MightyPork)
*/
public class IntegerProperty extends Property {
-
- public IntegerProperty(String key, Integer defaultValue) {
+
+ public IntegerProperty(String key, Integer defaultValue)
+ {
super(key, defaultValue);
}
-
-
- public IntegerProperty(String key, Integer defaultValue, String comment) {
+
+
+ public IntegerProperty(String key, Integer defaultValue, String comment)
+ {
super(key, defaultValue, comment);
}
-
-
+
+
@Override
public void fromString(String string)
{
diff --git a/src/mightypork/utils/config/propmgr/properties/StringProperty.java b/src/mightypork/utils/config/propmgr/properties/StringProperty.java
index 6032ba1..316693c 100644
--- a/src/mightypork/utils/config/propmgr/properties/StringProperty.java
+++ b/src/mightypork/utils/config/propmgr/properties/StringProperty.java
@@ -7,21 +7,23 @@ import mightypork.utils.config.propmgr.Property;
/**
* String property
- *
+ *
* @author Ondřej Hruška (MightyPork)
*/
public class StringProperty extends Property {
-
- public StringProperty(String key, String defaultValue) {
+
+ public StringProperty(String key, String defaultValue)
+ {
super(key, defaultValue);
}
-
-
- public StringProperty(String key, String defaultValue, String comment) {
+
+
+ public StringProperty(String key, String defaultValue, String comment)
+ {
super(key, defaultValue, comment);
}
-
-
+
+
@Override
public void fromString(String string)
{
diff --git a/src/mightypork/utils/config/propmgr/store/PropertyFile.java b/src/mightypork/utils/config/propmgr/store/PropertyFile.java
index 9bc8360..8fcb4e7 100644
--- a/src/mightypork/utils/config/propmgr/store/PropertyFile.java
+++ b/src/mightypork/utils/config/propmgr/store/PropertyFile.java
@@ -13,50 +13,52 @@ import mightypork.utils.config.propmgr.PropertyStore;
/**
* File based implementation utilizing {@link java.util.Properties}, hacked to
* support UTF-8.
- *
+ *
* @author Ondřej Hruška (MightyPork)
*/
public class PropertyFile implements PropertyStore {
-
+
private String comment;
- private File file;
- private SortedProperties props;
-
-
- public PropertyFile(File file) {
+ private final File file;
+ private final SortedProperties props;
+
+
+ public PropertyFile(File file)
+ {
this.file = file;
this.comment = null;
this.props = new SortedProperties();
}
-
-
- public PropertyFile(File file, String comment) {
+
+
+ public PropertyFile(File file, String comment)
+ {
this.file = file;
this.comment = comment;
this.props = new SortedProperties();
}
-
-
+
+
@Override
public void setComment(String comment)
{
this.comment = comment;
}
-
-
+
+
@Override
public void load()
{
if (!file.exists()) return;
-
- try (FileInputStream in = new FileInputStream(file)) {
+
+ try(FileInputStream in = new FileInputStream(file)) {
props.load(in);
- } catch (IOException e) {
+ } catch (final IOException e) {
// ignore
}
}
-
-
+
+
@Override
public void save() throws IOException
{
@@ -65,55 +67,55 @@ public class PropertyFile implements PropertyStore {
throw new IOException("Cound not create config file.");
}
}
-
- try (FileOutputStream out = new FileOutputStream(file)) {
+
+ try(FileOutputStream out = new FileOutputStream(file)) {
props.store(out, comment);
}
}
-
-
+
+
@Override
public String getProperty(String key)
{
return props.getProperty(key);
}
-
-
+
+
@Override
public void setProperty(String key, String value, String comment)
{
props.setProperty(key, value);
props.setKeyComment(key, comment);
}
-
-
+
+
@Override
public void removeProperty(String key)
{
props.remove(key);
}
-
-
+
+
@Override
public void clear()
{
props.clear();
}
-
-
+
+
@SuppressWarnings("unchecked")
@Override
public Collection keys()
{
-
+
// Set keys = new HashSet<>();
// for (Object o : props.keySet()) {
// keys.add((String) o);
// }
// return keys;
-
+
// we know it is strings.
return (Collection) (Collection>) props.keySet();
}
-
+
}
diff --git a/src/mightypork/utils/config/propmgr/store/SortedProperties.java b/src/mightypork/utils/config/propmgr/store/SortedProperties.java
index bdd085a..093eeb1 100644
--- a/src/mightypork/utils/config/propmgr/store/SortedProperties.java
+++ b/src/mightypork/utils/config/propmgr/store/SortedProperties.java
@@ -1,7 +1,13 @@
package mightypork.utils.config.propmgr.store;
-import java.io.*;
+import java.io.BufferedWriter;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
@@ -13,19 +19,19 @@ import java.util.Vector;
* Uses UTF-8 encoding and each property can have it's own comment.
* FIXME The quality of this class is dubious. It would probably be a good idea
* to rewrite it without using {@link java.util.Properties} at all.
- *
+ *
* @author Ondřej Hruška (MightyPork)
*/
class SortedProperties extends java.util.Properties {
-
+
/** Comments for individual keys */
private final Hashtable 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;
@@ -38,7 +44,7 @@ class SortedProperties extends java.util.Properties {
if (last != current) {
bw.write("# " + comments.substring(last, current));
}
-
+
if (c > '\u00ff') {
uu[2] = hexDigit(c, 12);
uu[3] = hexDigit(c, 8);
@@ -58,13 +64,13 @@ class SortedProperties extends java.util.Properties {
if (last != current) {
bw.write("# " + comments.substring(last, current));
}
-
+
bw.newLine();
bw.newLine();
bw.newLine();
}
-
-
+
+
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public synchronized Enumeration keys()
@@ -77,8 +83,8 @@ class SortedProperties extends java.util.Properties {
Collections.sort(keyList); //sort!
return keyList.elements();
}
-
-
+
+
private static String saveConvert(String theString, boolean escapeSpace, boolean escapeUnicode)
{
final int len = theString.length();
@@ -87,10 +93,10 @@ class SortedProperties extends java.util.Properties {
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)) {
@@ -102,7 +108,7 @@ class SortedProperties extends java.util.Properties {
result.append(ch);
continue;
}
-
+
switch (ch) {
case ' ':
if (x == 0 || escapeSpace) {
@@ -110,27 +116,27 @@ class SortedProperties extends java.util.Properties {
}
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
@@ -138,7 +144,7 @@ class SortedProperties extends java.util.Properties {
result.append('\\');
result.append(ch);
break;
-
+
default:
if (((ch < 0x0020) || (ch > 0x007e)) & escapeUnicode) {
result.append('\\');
@@ -152,14 +158,14 @@ class SortedProperties extends java.util.Properties {
}
}
}
-
+
return result.toString();
}
-
-
+
+
/**
* Set additional comment to a key
- *
+ *
* @param key key for comment
* @param comment the comment
*/
@@ -167,75 +173,75 @@ class SortedProperties extends java.util.Properties {
{
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);
-
+
// separate sections
if (!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");
-
+
// newline before comments
if (!wasNewLine && !firstEntry) {
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);
@@ -243,7 +249,7 @@ class SortedProperties extends java.util.Properties {
result.append(ch);
continue;
}
-
+
result.append('\\');
result.append('u');
result.append(hexDigit(ch, 12));
@@ -253,26 +259,26 @@ class SortedProperties extends java.util.Properties {
}
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();
@@ -282,18 +288,18 @@ class SortedProperties extends java.util.Properties {
if (temp < 0) {
break;
}
-
+
final char c = (char) temp;
sb.append(c);
}
-
+
// discard comments
final String read = sb.toString().replaceAll("(#|;|//|--)[^\n]*\n", "\n");
-
+
final String inputString = escapifyStr(read);
final byte[] bs = inputString.getBytes("ISO-8859-1");
final ByteArrayInputStream bais = new ByteArrayInputStream(bs);
-
+
super.load(bais);
}
}
diff --git a/src/mightypork/utils/eventbus/BusEvent.java b/src/mightypork/utils/eventbus/BusEvent.java
index 4ccf5f1..aba4f5e 100644
--- a/src/mightypork/utils/eventbus/BusEvent.java
+++ b/src/mightypork/utils/eventbus/BusEvent.java
@@ -26,73 +26,73 @@ import mightypork.utils.eventbus.events.flags.SingleReceiverEvent;
* Default sending mode (if not changed by annotations) is queued with
* zero delay.
*
- *
+ *
* @author Ondřej Hruška (MightyPork)
* @param handler type
*/
public abstract class BusEvent {
-
+
private boolean consumed;
private boolean served;
-
-
+
+
/**
* Ask handler to handle this message.
- *
+ *
* @param handler handler instance
*/
protected abstract void handleBy(HANDLER handler);
-
-
+
+
/**
* Consume the event, so no other clients will receive it.
- *
+ *
* @throws UnsupportedOperationException if the {@link NonConsumableEvent}
* annotation is present.
*/
public final void consume()
{
if (consumed) throw new IllegalStateException("Already consumed.");
-
+
if (getClass().isAnnotationPresent(NonConsumableEvent.class)) {
throw new UnsupportedOperationException("Not consumable.");
}
-
+
consumed = true;
}
-
-
+
+
/**
* Deliver to a handler using the handleBy method.
- *
+ *
* @param handler handler instance
*/
final void deliverTo(HANDLER handler)
{
handleBy(handler);
-
+
if (!served) {
if (getClass().isAnnotationPresent(SingleReceiverEvent.class)) {
consumed = true;
}
-
+
served = true;
}
}
-
-
+
+
/**
* Check if the event is consumed. When an event is consumed, no other
* clients will receive it.
- *
+ *
* @return true if consumed
*/
public final boolean isConsumed()
{
return consumed;
}
-
-
+
+
/**
* @return true if the event was served to at least 1 client
*/
@@ -100,8 +100,8 @@ public abstract class BusEvent {
{
return served;
}
-
-
+
+
/**
* Clear "served" and "consumed" flags before dispatching.
*/
@@ -110,11 +110,11 @@ public abstract class BusEvent {
served = false;
consumed = false;
}
-
-
+
+
/**
* Called after all clients have received the event.
- *
+ *
* @param bus event bus instance
*/
public void onDispatchComplete(EventBus bus)
diff --git a/src/mightypork/utils/eventbus/EventBus.java b/src/mightypork/utils/eventbus/EventBus.java
index 53a5ca1..366d3fa 100644
--- a/src/mightypork/utils/eventbus/EventBus.java
+++ b/src/mightypork/utils/eventbus/EventBus.java
@@ -22,75 +22,77 @@ import mightypork.utils.logging.Log;
/**
* An event bus, accommodating multiple EventChannels.
* Channel will be created when an event of type is first encountered.
- *
+ *
* @author Ondřej Hruška (MightyPork)
*/
final public class EventBus implements Destroyable {
-
+
/**
* Queued event holder
*/
private class DelayQueueEntry implements Delayed {
-
+
private final long due;
private final BusEvent> evt;
-
-
- public DelayQueueEntry(double seconds, BusEvent> event) {
+
+
+ public DelayQueueEntry(double seconds, BusEvent> event)
+ {
super();
this.due = System.currentTimeMillis() + (long) (seconds * 1000);
this.evt = event;
}
-
-
+
+
@Override
public int compareTo(Delayed o)
{
return Long.valueOf(getDelay(TimeUnit.MILLISECONDS)).compareTo(o.getDelay(TimeUnit.MILLISECONDS));
}
-
-
+
+
@Override
public long getDelay(TimeUnit unit)
{
return unit.convert(due - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
}
-
-
+
+
public BusEvent> getEvent()
{
return evt;
}
-
+
}
-
+
/**
* Thread handling queued events
*/
private class QueuePollingThread extends Thread {
-
+
public volatile boolean stopped = false;
-
-
- public QueuePollingThread() {
+
+
+ public QueuePollingThread()
+ {
super("Queue Polling Thread");
}
-
-
+
+
@Override
public void run()
{
DelayQueueEntry evt;
-
+
while (!stopped) {
evt = null;
-
+
try {
evt = sendQueue.take();
} catch (final InterruptedException ignored) {
//
}
-
+
if (evt != null) {
try {
dispatch(evt.getEvent());
@@ -100,46 +102,47 @@ final public class EventBus implements Destroyable {
}
}
}
-
+
}
-
+
static final String logMark = "(bus) ";
-
-
+
+
private static Class> getEventListenerClass(BusEvent> event)
{
return Reflect.getGenericParameters(event.getClass())[0];
}
-
+
/** Log detailed messages (debug) */
public boolean detailedLogging = false;
-
+
/** Queue polling thread */
private final QueuePollingThread busThread;
-
+
/** Registered clients */
private final Set