152 changed files with 2054 additions and 1456 deletions
+14 -14
View File
@@ -4,14 +4,14 @@ package mightypork.utils;
/** /**
* Utility for converting Object to data types; Can also convert strings to data * Utility for converting Object to data types; Can also convert strings to data
* types. * types.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class Convert { public class Convert {
/** /**
* Get INTEGER * Get INTEGER
* *
* @param o object * @param o object
* @param def default value * @param def default value
* @return integer * @return integer
@@ -30,7 +30,7 @@ public class Convert {
/** /**
* Get DOUBLE * Get DOUBLE
* *
* @param o object * @param o object
* @param def default value * @param def default value
* @return double * @return double
@@ -49,7 +49,7 @@ public class Convert {
/** /**
* Get FLOAT * Get FLOAT
* *
* @param o object * @param o object
* @param def default value * @param def default value
* @return float * @return float
@@ -66,7 +66,7 @@ public class Convert {
/** /**
* Get BOOLEAN * Get BOOLEAN
* *
* @param o object * @param o object
* @param def default value * @param def default value
* @return boolean * @return boolean
@@ -104,7 +104,7 @@ public class Convert {
/** /**
* Get STRING * Get STRING
* *
* @param o object * @param o object
* @param def default value * @param def default value
* @return String * @return String
@@ -114,12 +114,12 @@ public class Convert {
if (o == null) return def; if (o == null) return def;
if (o instanceof String) return ((String) o); if (o instanceof String) return ((String) o);
if (o instanceof Float) return Support.str((float) o); if (o instanceof Float) return Str.val((float) o);
if (o instanceof Double) return Support.str((double) o); if (o instanceof Double) return Str.val((double) o);
if (o instanceof Class<?>) { if (o instanceof Class<?>) {
return Support.str(o); return Str.val(o);
} }
return o.toString(); return o.toString();
@@ -128,7 +128,7 @@ public class Convert {
/** /**
* Get INTEGER * Get INTEGER
* *
* @param o object * @param o object
* @return integer * @return integer
*/ */
@@ -140,7 +140,7 @@ public class Convert {
/** /**
* Get DOUBLE * Get DOUBLE
* *
* @param o object * @param o object
* @return double * @return double
*/ */
@@ -152,7 +152,7 @@ public class Convert {
/** /**
* Get FLOAT * Get FLOAT
* *
* @param o object * @param o object
* @return float * @return float
*/ */
@@ -164,7 +164,7 @@ public class Convert {
/** /**
* Get BOOLEAN * Get BOOLEAN
* *
* @param o object * @param o object
* @return boolean * @return boolean
*/ */
@@ -176,7 +176,7 @@ public class Convert {
/** /**
* Get STRING * Get STRING
* *
* @param o object * @param o object
* @return String * @return String
*/ */
+57 -28
View File
@@ -12,70 +12,99 @@ import java.util.Map.Entry;
/** /**
* Map sorting utils * Map sorting utils
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class MapSort { 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
*/
@SuppressWarnings({ "rawtypes" })
public static <K extends Comparable, V> LinkedHashMap<K, V> byKeys(Map<K, V> map)
{
return byKeys(map, null);
}
/** /**
* Sort a map by keys, maintaining key-value pairs. * Sort a map by keys, maintaining key-value pairs.
* *
* @param map map to be sorted * @param map map to be sorted
* @param comparator a comparator, or null for natural ordering * @param comparator a comparator, or null for natural ordering
* @return linked hash map with sorted entries * @return linked hash map with sorted entries
*/ */
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({ "unchecked" })
public static <K extends Comparable, V extends Comparable> Map<K, V> sortByKeys(Map<K, V> map, final Comparator<K> comparator) public static <K, V> LinkedHashMap<K, V> byKeys(Map<K, V> map, Comparator<K> comparator)
{ {
final List<K> keys = new LinkedList<>(map.keySet()); final List<K> keys = new LinkedList<>(map.keySet());
if (comparator == null) { if (comparator == null) {
Collections.sort(keys); comparator = new Comparator<K>() {
} else {
Collections.sort(keys, comparator); @Override
public int compare(K arg0, K arg1)
{
return ((Comparable<K>) arg0).compareTo(arg1);
}
};
} }
// LinkedHashMap will keep the keys in the order they are inserted Collections.sort(keys, comparator);
// which is currently sorted on natural ordering
final Map<K, V> sortedMap = new LinkedHashMap<>(); final LinkedHashMap<K, V> sortedMap = new LinkedHashMap<>();
for (final K key : keys) { for (final K key : keys) {
sortedMap.put(key, map.get(key)); sortedMap.put(key, map.get(key));
} }
return sortedMap; return sortedMap;
} }
/**
* 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
*/
@SuppressWarnings("rawtypes")
public static <K, V extends Comparable> LinkedHashMap<K, V> byValues(Map<K, V> map)
{
return byValues(map, null);
}
/** /**
* Sort a map by values, maintaining key-value pairs. * Sort a map by values, maintaining key-value pairs.
* *
* @param map map to be sorted * @param map map to be sorted
* @param comparator a comparator, or null for natural ordering * @param comparator a comparator, or null for natural ordering
* @return linked hash map with sorted entries * @return linked hash map with sorted entries
*/ */
@SuppressWarnings("rawtypes") public static <K, V> LinkedHashMap<K, V> byValues(Map<K, V> map, final Comparator<V> comparator)
public static <K extends Comparable, V extends Comparable> Map<K, V> sortByValues(Map<K, V> map, final Comparator<V> comparator)
{ {
final List<Map.Entry<K, V>> entries = new LinkedList<>(map.entrySet()); final List<Map.Entry<K, V>> entries = new LinkedList<>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<K, V>>() { Collections.sort(entries, new Comparator<Map.Entry<K, V>>() {
@SuppressWarnings("unchecked")
@Override @Override
public int compare(Entry<K, V> o1, Entry<K, V> o2) public int compare(Entry<K, V> o1, Entry<K, V> o2)
{ {
if (comparator == null) return o1.getValue().compareTo(o2.getValue()); if (comparator == null) return ((Comparable<V>) o1.getValue()).compareTo(o2.getValue());
return comparator.compare(o1.getValue(), o2.getValue()); return comparator.compare(o1.getValue(), o2.getValue());
} }
}); });
// LinkedHashMap will keep the keys in the order they are inserted final LinkedHashMap<K, V> sortedMap = new LinkedHashMap<>();
// which is currently sorted on natural ordering
final Map<K, V> sortedMap = new LinkedHashMap<>();
for (final Map.Entry<K, V> entry : entries) { for (final Map.Entry<K, V> entry : entries) {
sortedMap.put(entry.getKey(), entry.getValue()); sortedMap.put(entry.getKey(), entry.getValue());
} }
return sortedMap; return sortedMap;
} }
} }
+16 -6
View File
@@ -10,14 +10,14 @@ import java.lang.reflect.Type;
/** /**
* Miscelanous reflection-related utilities * Miscelanous reflection-related utilities
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class Reflect { public class Reflect {
/** /**
* Get annotation of given type from an object * Get annotation of given type from an object
* *
* @param tested the examined object * @param tested the examined object
* @param annotation annotation we want * @param annotation annotation we want
* @return the anotation on that object, or null * @return the anotation on that object, or null
@@ -30,7 +30,7 @@ public class Reflect {
/** /**
* Check if an object has an annotation of given trype * Check if an object has an annotation of given trype
* *
* @param tested the examined object * @param tested the examined object
* @param annotation annotation we want * @param annotation annotation we want
* @return true if the annotation is present on the object * @return true if the annotation is present on the object
@@ -43,7 +43,7 @@ public class Reflect {
/** /**
* Get generic parameters of a class * Get generic parameters of a class
* *
* @param clazz the examined class * @param clazz the examined class
* @return parameter types * @return parameter types
*/ */
@@ -65,10 +65,20 @@ public class Reflect {
return classes; 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.
*
* @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 public static Object getConstantFieldValue(Class<?> objClass, String fieldName) throws ReflectiveOperationException
{ {
final Field fld = objClass.getDeclaredField(fieldName); final Field fld = objClass.getDeclaredField(fieldName);
@@ -76,7 +86,7 @@ public class Reflect {
final int modif = fld.getModifiers(); final int modif = fld.getModifiers();
if (!Modifier.isFinal(modif) || !Modifier.isStatic(modif)) { 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 " + Str.val(objClass) + " must be static and final!");
} }
fld.setAccessible(true); fld.setAccessible(true);
+231
View File
@@ -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());
}
}
}
+40 -136
View File
@@ -9,19 +9,17 @@ import java.util.Iterator;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import mightypork.utils.annotations.Alias;
/** /**
* Miscelanous utilities * Miscelanous utilities
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public final class Support { public final class Support {
/** /**
* Create a new thread of the runnable, and start it. * Create a new thread of the runnable, and start it.
* *
* @param r runnable * @param r runnable
* @return the thread started * @return the thread started
*/ */
@@ -31,11 +29,11 @@ public final class Support {
t.start(); t.start();
return t; return t;
} }
/** /**
* Pick first non-null option * Pick first non-null option
* *
* @param options options * @param options options
* @return the selected option * @return the selected option
*/ */
@@ -44,14 +42,14 @@ public final class Support {
for (final Object o : options) { for (final Object o : options) {
if (o != null) return o; if (o != null) return o;
} }
return null; // all null return null; // all null
} }
/** /**
* Get current time/date for given format. * Get current time/date for given format.
* *
* @param format format, according to {@link DateFormat}. * @param format format, according to {@link DateFormat}.
* @return the formatted time/date * @return the formatted time/date
*/ */
@@ -59,12 +57,12 @@ public final class Support {
{ {
return (new SimpleDateFormat(format)).format(new Date()); return (new SimpleDateFormat(format)).format(new Date());
} }
/** /**
* Parse array of vararg key, value pairs to a LinkedHashMap.<br> * Parse array of vararg key, value pairs to a LinkedHashMap.<br>
* Example: * Example:
* *
* <pre> * <pre>
* Object[] array = { * Object[] array = {
* &quot;one&quot;, 1, * &quot;one&quot;, 1,
@@ -72,10 +70,10 @@ public final class Support {
* &quot;three&quot;, 9, * &quot;three&quot;, 9,
* &quot;four&quot;, 16 * &quot;four&quot;, 16
* }; * };
* *
* Map&lt;String, Integer&gt; args = parseVarArgs(array); * Map&lt;String, Integer&gt; args = parseVarArgs(array);
* </pre> * </pre>
* *
* @param args varargs * @param args varargs
* @return LinkedHashMap * @return LinkedHashMap
* @throws ClassCastException in case of incompatible type in the array * @throws ClassCastException in case of incompatible type in the array
@@ -85,11 +83,11 @@ public final class Support {
public static <K, V> Map<K, V> parseVarArgs(Object... args) throws ClassCastException, IllegalArgumentException public static <K, V> Map<K, V> parseVarArgs(Object... args) throws ClassCastException, IllegalArgumentException
{ {
final LinkedHashMap<K, V> attrs = new LinkedHashMap<>(); final LinkedHashMap<K, V> attrs = new LinkedHashMap<>();
if (args.length % 2 != 0) { if (args.length % 2 != 0) {
throw new IllegalArgumentException("Odd number of elements in varargs map!"); throw new IllegalArgumentException("Odd number of elements in varargs map!");
} }
K key = null; K key = null;
for (final Object o : args) { for (final Object o : args) {
if (key == null) { if (key == null) {
@@ -100,14 +98,14 @@ public final class Support {
key = null; key = null;
} }
} }
return attrs; return attrs;
} }
/** /**
* Get if an Object is in array (using equals) * Get if an Object is in array (using equals)
* *
* @param needle checked Object * @param needle checked Object
* @param haystack array of Objects * @param haystack array of Objects
* @return is in array * @return is in array
@@ -119,11 +117,11 @@ public final class Support {
} }
return false; return false;
} }
/** /**
* Get if string is in array * Get if string is in array
* *
* @param needle checked string * @param needle checked string
* @param case_sensitive case sensitive comparision * @param case_sensitive case sensitive comparision
* @param haystack array of possible values * @param haystack array of possible values
@@ -140,11 +138,11 @@ public final class Support {
return false; return false;
} }
} }
/** /**
* Make enumeration iterable * Make enumeration iterable
* *
* @param enumeration enumeration * @param enumeration enumeration
* @return iterable wrapper * @return iterable wrapper
*/ */
@@ -152,19 +150,18 @@ public final class Support {
{ {
return new IterableEnumerationWrapper<>(enumeration); return new IterableEnumerationWrapper<>(enumeration);
} }
/** /**
* Helper class for iterationg over an {@link Enumeration} * Helper class for iterationg over an {@link Enumeration}
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
* @param <T> target element type (will be cast) * @param <T> target element type (will be cast)
*/ */
private static class IterableEnumerationWrapper<T> implements Iterable<T> { private static class IterableEnumerationWrapper<T> implements Iterable<T> {
private final Enumeration<? extends T> enumeration; private final Enumeration<? extends T> enumeration;
/** /**
* @param enumeration the iterated enumeration * @param enumeration the iterated enumeration
*/ */
@@ -172,27 +169,27 @@ public final class Support {
{ {
this.enumeration = enumeration; this.enumeration = enumeration;
} }
@Override @Override
public Iterator<T> iterator() public Iterator<T> iterator()
{ {
return new Iterator<T>() { return new Iterator<T>() {
@Override @Override
public boolean hasNext() public boolean hasNext()
{ {
return enumeration.hasMoreElements(); return enumeration.hasMoreElements();
} }
@Override @Override
public T next() public T next()
{ {
return enumeration.nextElement(); return enumeration.nextElement();
} }
@Override @Override
public void remove() public void remove()
{ {
@@ -200,99 +197,6 @@ public final class Support {
} }
}; };
} }
}
/**
* Convert a class to string, preserving name and outer class, but excluding
* path.
*
* @param cls
* @return
*/
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());
}
} }
} }
+1 -1
View File
@@ -12,7 +12,7 @@ import java.lang.annotation.Target;
/** /**
* Specify pretty name to be used when logging / converting class name to * Specify pretty name to be used when logging / converting class name to
* string. * string.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@@ -11,7 +11,7 @@ import java.lang.annotation.Target;
/** /**
* Marks a static factory method. This is a description annotation and has no * Marks a static factory method. This is a description annotation and has no
* other function. * other function.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
@Retention(RetentionPolicy.SOURCE) @Retention(RetentionPolicy.SOURCE)
@@ -12,12 +12,12 @@ import java.lang.annotation.Target;
* Marked method can be safely overriden; it's left blank (or with default * Marked method can be safely overriden; it's left blank (or with default
* implementation) as a convenience.<br> * implementation) as a convenience.<br>
* This is a description annotation and has no other function. * This is a description annotation and has no other function.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
@Documented @Documented
@Retention(RetentionPolicy.SOURCE) @Retention(RetentionPolicy.SOURCE)
@Target(value = { ElementType.METHOD }) @Target(value = { ElementType.METHOD })
public @interface DefaultImpl { public @interface Stub {
// //
} }
@@ -1,4 +1,4 @@
package mightypork.utils.files.config; package mightypork.utils.config;
import java.io.File; import java.io.File;
@@ -9,7 +9,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import mightypork.utils.files.FileUtils; import mightypork.utils.files.FileUtil;
import mightypork.utils.logging.Log; import mightypork.utils.logging.Log;
@@ -19,21 +19,21 @@ import mightypork.utils.logging.Log;
* empty lines and lines without "=" are ignored<br> * empty lines and lines without "=" are ignored<br>
* lines with "=" must have "key = value" format, or a warning is logged.<br> * lines with "=" must have "key = value" format, or a warning is logged.<br>
* use "NULL" to create empty value. * use "NULL" to create empty value.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class SimpleConfig { public class SimpleConfig {
/** /**
* Load list from file * Load list from file
* *
* @param file file * @param file file
* @return map of keys and values * @return map of keys and values
* @throws IOException * @throws IOException
*/ */
public static List<String> listFromFile(File file) throws IOException public static List<String> listFromFile(File file) throws IOException
{ {
final String fileText = FileUtils.fileToString(file); final String fileText = FileUtil.fileToString(file);
return listFromString(fileText); return listFromString(fileText);
} }
@@ -41,14 +41,14 @@ public class SimpleConfig {
/** /**
* Load map from file * Load map from file
* *
* @param file file * @param file file
* @return map of keys and values * @return map of keys and values
* @throws IOException * @throws IOException
*/ */
public static Map<String, String> mapFromFile(File file) throws IOException public static Map<String, String> mapFromFile(File file) throws IOException
{ {
final String fileText = FileUtils.fileToString(file); final String fileText = FileUtil.fileToString(file);
return mapFromString(fileText); return mapFromString(fileText);
} }
@@ -56,7 +56,7 @@ public class SimpleConfig {
/** /**
* Load list from string * Load list from string
* *
* @param text text of the file * @param text text of the file
* @return map of keys and values * @return map of keys and values
*/ */
@@ -86,7 +86,7 @@ public class SimpleConfig {
/** /**
* Load map from string * Load map from string
* *
* @param text text of the file * @param text text of the file
* @return map of keys and values * @return map of keys and values
*/ */
@@ -140,7 +140,7 @@ public class SimpleConfig {
/** /**
* Save map to file * Save map to file
* *
* @param target * @param target
* @param data * @param data
* @param allowNulls allow nulls. * @param allowNulls allow nulls.
@@ -173,14 +173,14 @@ public class SimpleConfig {
text += s; text += s;
} }
FileUtils.stringToFile(target, text); FileUtil.stringToFile(target, text);
} }
/** /**
* Save list to file * Save list to file
* *
* @param target * @param target
* @param data * @param data
* @throws IOException * @throws IOException
@@ -199,7 +199,7 @@ public class SimpleConfig {
text += s; text += s;
} }
FileUtils.stringToFile(target, text); FileUtil.stringToFile(target, text);
} }
} }
@@ -0,0 +1,123 @@
package mightypork.utils.config.propmgr;
import mightypork.utils.Convert;
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
*/
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
*
* @param key key in the config file
* @param defaultValue defualt property value (used as fallback when
* parsing)
*/
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 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)
{
this.comment = comment;
this.key = key;
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.
*
* @param string property value as string
*/
public abstract void fromString(String string);
/**
* Get property value as string (compatible with `fromString())
*
* @return property value as string
*/
@Override
@Stub
public String toString()
{
return Convert.toString(value, Convert.toString(defaultValue));
}
/**
* Get the current property value
*
* @return the value
*/
public T getValue()
{
return value;
}
/**
* 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.
*/
@SuppressWarnings("unchecked")
public void setValue(Object value)
{
this.value = (T) value;
}
/**
* Get property comment.
*
* @return the comment text (can be null if no comment is defined)
*/
public String getComment()
{
return comment;
}
/**
* Get property key
*
* @return property key
*/
public String getKey()
{
return key;
}
}
@@ -0,0 +1,289 @@
package mightypork.utils.config.propmgr;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map.Entry;
import java.util.TreeMap;
import mightypork.utils.Convert;
import mightypork.utils.config.propmgr.properties.BooleanProperty;
import mightypork.utils.config.propmgr.properties.DoubleProperty;
import mightypork.utils.config.propmgr.properties.IntegerProperty;
import mightypork.utils.config.propmgr.properties.StringProperty;
import mightypork.utils.config.propmgr.store.PropertyFile;
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 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)
{
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)
{
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
*/
public Property<?> getProperty(String k)
{
try {
return entries.get(k);
} catch (final Exception e) {
Log.w(e);
return null;
}
}
/**
* Get boolean property
*
* @param k key
* @return the boolean found, or false
*/
public Boolean getBoolean(String k)
{
return Convert.toBoolean(getProperty(k).getValue());
}
/**
* Get numeric property
*
* @param k key
* @return the int found, or null
*/
public Integer getInteger(String k)
{
return Convert.toInteger(getProperty(k).getValue());
}
/**
* Get numeric property as double
*
* @param k key
* @return the double found, or null
*/
public Double getDouble(String k)
{
return Convert.toDouble(getProperty(k).getValue());
}
/**
* Get string property
*
* @param k key
* @return the string found, or null
*/
public String getString(String k)
{
return Convert.toString(getProperty(k).getValue());
}
/**
* Get arbitrary property. Make sure it's of the right type!
*
* @param k key
* @return the prioperty found
*/
@SuppressWarnings("unchecked")
public <T> T getValue(String k)
{
try {
return ((Property<T>) getProperty(k)).getValue();
} catch (final ClassCastException e) {
return null;
}
}
/**
* Add a boolean property
*
* @param k key
* @param d default value
* @param comment the in-file comment
*/
public void addBoolean(String k, boolean d, String comment)
{
addProperty(new BooleanProperty(k, d, comment));
}
/**
* Add a numeric property (double)
*
* @param k key
* @param d default value
* @param comment the in-file comment
*/
public void addDouble(String k, double d, String comment)
{
addProperty(new DoubleProperty(k, d, comment));
}
/**
* Add a numeric property
*
* @param k key
* @param d default value
* @param comment the in-file comment
*/
public void addInteger(String k, int d, String comment)
{
addProperty(new IntegerProperty(k, d, comment));
}
/**
* Add a string property
*
* @param k key
* @param d default value
* @param comment the in-file comment
*/
public void addString(String k, String d, String comment)
{
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
*/
public void renameKey(String oldKey, String newKey)
{
renameTable.put(oldKey, newKey);
return;
}
/**
* Set value saved to certain key.
*
* @param key key
* @param value the saved value
*/
public void setValue(String key, Object value)
{
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);
}
}
@@ -0,0 +1,79 @@
package mightypork.utils.config.propmgr;
import java.io.IOException;
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();
/**
* 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<String> keys();
}
@@ -0,0 +1,32 @@
package mightypork.utils.config.propmgr.properties;
import mightypork.utils.Convert;
import mightypork.utils.config.propmgr.Property;
/**
* Boolean property
*
* @author Ondřej Hruška (MightyPork)
*/
public class BooleanProperty extends Property<Boolean> {
public BooleanProperty(String key, Boolean defaultValue)
{
super(key, defaultValue);
}
public BooleanProperty(String key, Boolean defaultValue, String comment)
{
super(key, defaultValue, comment);
}
@Override
public void fromString(String string)
{
setValue(Convert.toBoolean(string, defaultValue));
}
}
@@ -0,0 +1,32 @@
package mightypork.utils.config.propmgr.properties;
import mightypork.utils.Convert;
import mightypork.utils.config.propmgr.Property;
/**
* Double property
*
* @author Ondřej Hruška (MightyPork)
*/
public class DoubleProperty extends Property<Double> {
public DoubleProperty(String key, Double defaultValue)
{
super(key, defaultValue);
}
public DoubleProperty(String key, Double defaultValue, String comment)
{
super(key, defaultValue, comment);
}
@Override
public void fromString(String string)
{
setValue(Convert.toDouble(string, defaultValue));
}
}
@@ -0,0 +1,32 @@
package mightypork.utils.config.propmgr.properties;
import mightypork.utils.Convert;
import mightypork.utils.config.propmgr.Property;
/**
* Integer property
*
* @author Ondřej Hruška (MightyPork)
*/
public class IntegerProperty extends Property<Integer> {
public IntegerProperty(String key, Integer defaultValue)
{
super(key, defaultValue);
}
public IntegerProperty(String key, Integer defaultValue, String comment)
{
super(key, defaultValue, comment);
}
@Override
public void fromString(String string)
{
setValue(Convert.toInteger(string, defaultValue));
}
}
@@ -0,0 +1,32 @@
package mightypork.utils.config.propmgr.properties;
import mightypork.utils.Convert;
import mightypork.utils.config.propmgr.Property;
/**
* String property
*
* @author Ondřej Hruška (MightyPork)
*/
public class StringProperty extends Property<String> {
public StringProperty(String key, String defaultValue)
{
super(key, defaultValue);
}
public StringProperty(String key, String defaultValue, String comment)
{
super(key, defaultValue, comment);
}
@Override
public void fromString(String string)
{
setValue(Convert.toString(string, defaultValue));
}
}
@@ -0,0 +1,121 @@
package mightypork.utils.config.propmgr.store;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
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 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)
{
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)) {
props.load(in);
} catch (final IOException e) {
// ignore
}
}
@Override
public void save() throws IOException
{
if (!file.getParentFile().mkdirs()) {
if (!file.getParentFile().exists()) {
throw new IOException("Cound not create config 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<String> keys()
{
// Set<String> keys = new HashSet<>();
// for (Object o : props.keySet()) {
// keys.add((String) o);
// }
// return keys;
// we know it is strings.
return (Collection<String>) (Collection<?>) props.keySet();
}
}
@@ -1,4 +1,4 @@
package mightypork.utils.files.config; package mightypork.utils.config.propmgr.store;
import java.io.BufferedWriter; import java.io.BufferedWriter;
@@ -16,20 +16,13 @@ import java.util.Vector;
/** /**
* Properties stored in file, alphabetically sorted.<br> * Properties stored in file, alphabetically sorted.<br>
* Uses UTF-8 encoding and each property can have it's own comment. * Uses UTF-8 encoding and each property can have it's own comment.<br>
* * 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) * @author Ondřej Hruška (MightyPork)
*/ */
public class SortedProperties extends java.util.Properties { class SortedProperties extends java.util.Properties {
/** Option: put empty line before each comment. */
public boolean cfgBlankRowBeforeComment = true;
/**
* Option: Separate sections by newline<br>
* Section = string before first dot in key.
*/
public boolean cfgBlankRowBetweenSections = true;
/** Comments for individual keys */ /** Comments for individual keys */
private final Hashtable<String, String> keyComments = new Hashtable<>(); private final Hashtable<String, String> keyComments = new Hashtable<>();
@@ -172,7 +165,7 @@ public class SortedProperties extends java.util.Properties {
/** /**
* Set additional comment to a key * Set additional comment to a key
* *
* @param key key for comment * @param key key for comment
* @param comment the comment * @param comment the comment
*/ */
@@ -205,7 +198,8 @@ public class SortedProperties extends java.util.Properties {
key = saveConvert(key, true, escUnicode); key = saveConvert(key, true, escUnicode);
val = saveConvert(val, false, escUnicode); val = saveConvert(val, false, escUnicode);
if (cfgBlankRowBetweenSections && !lastSectionBeginning.equals(key.split("[.]")[0])) { // separate sections
if (!lastSectionBeginning.equals(key.split("[.]")[0])) {
if (!firstEntry) { if (!firstEntry) {
bw.newLine(); bw.newLine();
bw.newLine(); bw.newLine();
@@ -223,7 +217,8 @@ public class SortedProperties extends java.util.Properties {
final String[] cmlines = cm.split("\n"); final String[] cmlines = cm.split("\n");
if (!wasNewLine && !firstEntry && cfgBlankRowBeforeComment) { // newline before comments
if (!wasNewLine && !firstEntry) {
bw.newLine(); bw.newLine();
} }
@@ -298,6 +293,7 @@ public class SortedProperties extends java.util.Properties {
sb.append(c); sb.append(c);
} }
// discard comments
final String read = sb.toString().replaceAll("(#|;|//|--)[^\n]*\n", "\n"); final String read = sb.toString().replaceAll("(#|;|//|--)[^\n]*\n", "\n");
final String inputString = escapifyStr(read); final String inputString = escapifyStr(read);
@@ -1,16 +0,0 @@
package mightypork.utils.eventbus;
/**
* Access to an {@link EventBus} instance
*
* @author Ondřej Hruška (MightyPork)
*/
public interface BusAccess {
/**
* @return event bus
*/
EventBus getEventBus();
}
+31 -28
View File
@@ -1,6 +1,7 @@
package mightypork.utils.eventbus; package mightypork.utils.eventbus;
import mightypork.utils.annotations.Stub;
import mightypork.utils.eventbus.events.flags.DelayedEvent; import mightypork.utils.eventbus.events.flags.DelayedEvent;
import mightypork.utils.eventbus.events.flags.DirectEvent; import mightypork.utils.eventbus.events.flags.DirectEvent;
import mightypork.utils.eventbus.events.flags.NonConsumableEvent; import mightypork.utils.eventbus.events.flags.NonConsumableEvent;
@@ -26,82 +27,82 @@ import mightypork.utils.eventbus.events.flags.SingleReceiverEvent;
* Default sending mode (if not changed by annotations) is <i>queued</i> with * Default sending mode (if not changed by annotations) is <i>queued</i> with
* zero delay. * zero delay.
* </p> * </p>
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
* @param <HANDLER> handler type * @param <HANDLER> handler type
*/ */
public abstract class BusEvent<HANDLER> { public abstract class BusEvent<HANDLER> {
private boolean consumed; private boolean consumed;
private boolean served; private boolean served;
/** /**
* Ask handler to handle this message. * Ask handler to handle this message.
* *
* @param handler handler instance * @param handler handler instance
*/ */
protected abstract void handleBy(HANDLER handler); protected abstract void handleBy(HANDLER handler);
/** /**
* Consume the event, so no other clients will receive it. * Consume the event, so no other clients will receive it.
* *
* @throws UnsupportedOperationException if the {@link NonConsumableEvent} * @throws UnsupportedOperationException if the {@link NonConsumableEvent}
* annotation is present. * annotation is present.
*/ */
public final void consume() public final void consume()
{ {
if (consumed) throw new IllegalStateException("Already consumed."); if (consumed) throw new IllegalStateException("Already consumed.");
if (getClass().isAnnotationPresent(NonConsumableEvent.class)) { if (getClass().isAnnotationPresent(NonConsumableEvent.class)) {
throw new UnsupportedOperationException("Not consumable."); throw new UnsupportedOperationException("Not consumable.");
} }
consumed = true; consumed = true;
} }
/** /**
* Deliver to a handler using the handleBy method. * Deliver to a handler using the handleBy method.
* *
* @param handler handler instance * @param handler handler instance
*/ */
final void deliverTo(HANDLER handler) final void deliverTo(HANDLER handler)
{ {
handleBy(handler); handleBy(handler);
if (!served) { if (!served) {
if (getClass().isAnnotationPresent(SingleReceiverEvent.class)) { if (getClass().isAnnotationPresent(SingleReceiverEvent.class)) {
consumed = true; consumed = true;
} }
served = true; served = true;
} }
} }
/** /**
* Check if the event is consumed. Consumed event is not served to other * Check if the event is consumed. When an event is consumed, no other
* clients. * clients will receive it.
* *
* @return true if consumed * @return true if consumed
*/ */
public final boolean isConsumed() public final boolean isConsumed()
{ {
return consumed; return consumed;
} }
/** /**
* @return true if the event was served to at least 1 client * @return true if the event was served to at least 1 client
*/ */
final boolean wasServed() public final boolean wasServed()
{ {
return served; return served;
} }
/** /**
* Clear "served" and "consumed" flags before dispatching. * Clear "served" and "consumed" flags before dispatching.
*/ */
@@ -110,14 +111,16 @@ public abstract class BusEvent<HANDLER> {
served = false; served = false;
consumed = false; consumed = false;
} }
/** /**
* Called after all clients have received the event. * Called after all clients have received the event.
* *
* @param bus event bus instance * @param bus event bus instance
*/ */
@Stub
public void onDispatchComplete(EventBus bus) public void onDispatchComplete(EventBus bus)
{ {
//
} }
} }
+22 -29
View File
@@ -10,7 +10,7 @@ import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import mightypork.utils.Reflect; import mightypork.utils.Reflect;
import mightypork.utils.Support; import mightypork.utils.Str;
import mightypork.utils.eventbus.clients.DelegatingClient; import mightypork.utils.eventbus.clients.DelegatingClient;
import mightypork.utils.eventbus.events.flags.DelayedEvent; import mightypork.utils.eventbus.events.flags.DelayedEvent;
import mightypork.utils.eventbus.events.flags.DirectEvent; import mightypork.utils.eventbus.events.flags.DirectEvent;
@@ -22,10 +22,10 @@ import mightypork.utils.logging.Log;
/** /**
* An event bus, accommodating multiple EventChannels.<br> * An event bus, accommodating multiple EventChannels.<br>
* Channel will be created when an event of type is first encountered. * Channel will be created when an event of type is first encountered.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
final public class EventBus implements Destroyable, BusAccess { final public class EventBus implements Destroyable {
/** /**
* Queued event holder * Queued event holder
@@ -158,7 +158,7 @@ final public class EventBus implements Destroyable, BusAccess {
/** /**
* Send based on annotation * Send based on annotation
* *
* @param event event * @param event event
*/ */
public void send(BusEvent<?> event) public void send(BusEvent<?> event)
@@ -182,7 +182,7 @@ final public class EventBus implements Destroyable, BusAccess {
/** /**
* Add event to a queue * Add event to a queue
* *
* @param event event * @param event event
*/ */
public void sendQueued(BusEvent<?> event) public void sendQueued(BusEvent<?> event)
@@ -195,7 +195,7 @@ final public class EventBus implements Destroyable, BusAccess {
/** /**
* Add event to a queue, scheduled for given time. * Add event to a queue, scheduled for given time.
* *
* @param event event * @param event event
* @param delay delay before event is dispatched * @param delay delay before event is dispatched
*/ */
@@ -206,7 +206,7 @@ final public class EventBus implements Destroyable, BusAccess {
final DelayQueueEntry dm = new DelayQueueEntry(delay, event); final DelayQueueEntry dm = new DelayQueueEntry(delay, event);
if (shallLog(event)) { if (shallLog(event)) {
Log.f3(logMark + "Qu [" + Support.str(event) + "]" + (delay == 0 ? "" : (", delay: " + delay + "s"))); Log.f3(logMark + "Qu [" + Str.val(event) + "]" + (delay == 0 ? "" : (", delay: " + delay + "s")));
} }
sendQueue.add(dm); sendQueue.add(dm);
@@ -217,14 +217,14 @@ final public class EventBus implements Destroyable, BusAccess {
* Send immediately.<br> * Send immediately.<br>
* Should be used for real-time events that require immediate response, such * Should be used for real-time events that require immediate response, such
* as timing events. * as timing events.
* *
* @param event event * @param event event
*/ */
public void sendDirect(BusEvent<?> event) public void sendDirect(BusEvent<?> event)
{ {
assertLive(); assertLive();
if (shallLog(event)) Log.f3(logMark + "Di [" + Support.str(event) + "]"); if (shallLog(event)) Log.f3(logMark + "Di [" + Str.val(event) + "]");
dispatch(event); dispatch(event);
} }
@@ -234,7 +234,7 @@ final public class EventBus implements Destroyable, BusAccess {
{ {
assertLive(); assertLive();
if (shallLog(event)) Log.f3(logMark + "Di->sub [" + Support.str(event) + "]"); if (shallLog(event)) Log.f3(logMark + "Di->sub [" + Str.val(event) + "]");
doDispatch(delegatingClient.getChildClients(), event); doDispatch(delegatingClient.getChildClients(), event);
} }
@@ -243,7 +243,7 @@ final public class EventBus implements Destroyable, BusAccess {
/** /**
* Connect a client to the bus. The client will be connected to all current * Connect a client to the bus. The client will be connected to all current
* and future channels, until removed from the bus. * and future channels, until removed from the bus.
* *
* @param client the client * @param client the client
*/ */
public void subscribe(Object client) public void subscribe(Object client)
@@ -254,13 +254,13 @@ final public class EventBus implements Destroyable, BusAccess {
clients.add(client); clients.add(client);
if (detailedLogging) Log.f3(logMark + "Client joined: " + Support.str(client)); if (detailedLogging) Log.f3(logMark + "Client joined: " + Str.val(client));
} }
/** /**
* Disconnect a client from the bus. * Disconnect a client from the bus.
* *
* @param client the client * @param client the client
*/ */
public void unsubscribe(Object client) public void unsubscribe(Object client)
@@ -269,7 +269,7 @@ final public class EventBus implements Destroyable, BusAccess {
clients.remove(client); clients.remove(client);
if (detailedLogging) Log.f3(logMark + "Client left: " + Support.str(client)); if (detailedLogging) Log.f3(logMark + "Client left: " + Str.val(client));
} }
@@ -278,7 +278,7 @@ final public class EventBus implements Destroyable, BusAccess {
{ {
try { try {
if (detailedLogging) { if (detailedLogging) {
Log.f3(logMark + "Setting up channel for new event type: " + Support.str(event.getClass())); Log.f3(logMark + "Setting up channel for new event type: " + Str.val(event.getClass()));
} }
final Class<?> listener = getEventListenerClass(event); final Class<?> listener = getEventListenerClass(event);
@@ -290,13 +290,13 @@ final public class EventBus implements Destroyable, BusAccess {
//channels.flush(); //channels.flush();
if (detailedLogging) { if (detailedLogging) {
Log.f3(logMark + "Created new channel: " + Support.str(event.getClass()) + " -> " + Support.str(listener)); Log.f3(logMark + "Created new channel: " + Str.val(event.getClass()) + " -> " + Str.val(listener));
} }
return true; return true;
} else { } else {
Log.w(logMark + "Could not create channel for event " + Support.str(event.getClass())); Log.w(logMark + "Could not create channel for event " + Str.val(event.getClass()));
} }
} catch (final Throwable t) { } catch (final Throwable t) {
@@ -309,7 +309,7 @@ final public class EventBus implements Destroyable, BusAccess {
/** /**
* Make sure the bus is not destroyed. * Make sure the bus is not destroyed.
* *
* @throws IllegalStateException if the bus is dead. * @throws IllegalStateException if the bus is dead.
*/ */
private void assertLive() throws IllegalStateException private void assertLive() throws IllegalStateException
@@ -322,7 +322,7 @@ final public class EventBus implements Destroyable, BusAccess {
* Send immediately.<br> * Send immediately.<br>
* Should be used for real-time events that require immediate response, such * Should be used for real-time events that require immediate response, such
* as timing events. * as timing events.
* *
* @param event event * @param event event
*/ */
private synchronized void dispatch(BusEvent<?> event) private synchronized void dispatch(BusEvent<?> event)
@@ -336,7 +336,7 @@ final public class EventBus implements Destroyable, BusAccess {
/** /**
* Send to a set of clients * Send to a set of clients
* *
* @param clients clients * @param clients clients
* @param event event * @param event event
*/ */
@@ -362,8 +362,8 @@ final public class EventBus implements Destroyable, BusAccess {
break; break;
} }
if (!accepted) Log.e(logMark + "Not accepted by any channel: " + Support.str(event)); if (!accepted) Log.e(logMark + "Not accepted by any channel: " + Str.val(event));
if (!event.wasServed() && shallLog(event)) Log.w(logMark + "Not delivered: " + Support.str(event)); if (!event.wasServed() && shallLog(event)) Log.w(logMark + "Not delivered: " + Str.val(event));
} }
@@ -375,11 +375,4 @@ final public class EventBus implements Destroyable, BusAccess {
return true; return true;
} }
@Override
public EventBus getEventBus()
{
return this; // just for compatibility use-case
}
} }
+12 -12
View File
@@ -5,7 +5,7 @@ import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import mightypork.utils.Reflect; import mightypork.utils.Reflect;
import mightypork.utils.Support; import mightypork.utils.Str;
import mightypork.utils.eventbus.clients.DelegatingClient; import mightypork.utils.eventbus.clients.DelegatingClient;
import mightypork.utils.eventbus.clients.ToggleableClient; import mightypork.utils.eventbus.clients.ToggleableClient;
import mightypork.utils.eventbus.events.flags.NonRejectableEvent; import mightypork.utils.eventbus.events.flags.NonRejectableEvent;
@@ -14,7 +14,7 @@ import mightypork.utils.logging.Log;
/** /**
* Event delivery channel, module of {@link EventBus} * Event delivery channel, module of {@link EventBus}
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
* @param <EVENT> event type * @param <EVENT> event type
* @param <CLIENT> client (subscriber) type * @param <CLIENT> client (subscriber) type
@@ -27,7 +27,7 @@ class EventChannel<EVENT extends BusEvent<CLIENT>, CLIENT> {
/** /**
* Create a channel * Create a channel
* *
* @param eventClass event class * @param eventClass event class
* @param clientClass client class * @param clientClass client class
*/ */
@@ -46,7 +46,7 @@ class EventChannel<EVENT extends BusEvent<CLIENT>, CLIENT> {
/** /**
* Try to broadcast a event.<br> * Try to broadcast a event.<br>
* If event is of wrong type, <code>false</code> is returned. * If event is of wrong type, <code>false</code> is returned.
* *
* @param event a event to be sent * @param event a event to be sent
* @param clients collection of clients * @param clients collection of clients
*/ */
@@ -60,7 +60,7 @@ class EventChannel<EVENT extends BusEvent<CLIENT>, CLIENT> {
/** /**
* Send the event * Send the event
* *
* @param event sent event * @param event sent event
* @param clients subscribing clients * @param clients subscribing clients
* @param processed clients already processed * @param processed clients already processed
@@ -76,7 +76,7 @@ class EventChannel<EVENT extends BusEvent<CLIENT>, CLIENT> {
// avoid executing more times // avoid executing more times
if (processed.contains(client)) { if (processed.contains(client)) {
Log.w(EventBus.logMark + "Client already served: " + Support.str(client)); Log.w(EventBus.logMark + "Client already served: " + Str.val(client));
continue; continue;
} }
processed.add(client); processed.add(client);
@@ -110,7 +110,7 @@ class EventChannel<EVENT extends BusEvent<CLIENT>, CLIENT> {
/** /**
* Send an event to a client. * Send an event to a client.
* *
* @param client target client * @param client target client
* @param event event to send * @param event event to send
*/ */
@@ -125,7 +125,7 @@ class EventChannel<EVENT extends BusEvent<CLIENT>, CLIENT> {
/** /**
* Check if the given event can be broadcasted by this channel * Check if the given event can be broadcasted by this channel
* *
* @param event event object * @param event event object
* @return can be broadcasted * @return can be broadcasted
*/ */
@@ -137,7 +137,7 @@ class EventChannel<EVENT extends BusEvent<CLIENT>, CLIENT> {
/** /**
* Create an instance for given types * Create an instance for given types
* *
* @param eventClass event class * @param eventClass event class
* @param clientClass client class * @param clientClass client class
* @return the broadcaster * @return the broadcaster
@@ -150,7 +150,7 @@ class EventChannel<EVENT extends BusEvent<CLIENT>, CLIENT> {
/** /**
* Check if client is of channel type * Check if client is of channel type
* *
* @param client client * @param client client
* @return is of type * @return is of type
*/ */
@@ -162,7 +162,7 @@ class EventChannel<EVENT extends BusEvent<CLIENT>, CLIENT> {
/** /**
* Check if the channel is compatible with given * Check if the channel is compatible with given
* *
* @param client client * @param client client
* @return is supported * @return is supported
*/ */
@@ -203,6 +203,6 @@ class EventChannel<EVENT extends BusEvent<CLIENT>, CLIENT> {
@Override @Override
public String toString() public String toString()
{ {
return "{ " + Support.str(eventClass) + " => " + Support.str(clientClass) + " }"; return "{ " + Str.val(eventClass) + " => " + Str.val(clientClass) + " }";
} }
} }
@@ -5,34 +5,22 @@ import java.util.Collection;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.Set; import java.util.Set;
import mightypork.utils.eventbus.BusAccess;
import mightypork.utils.eventbus.EventBus; import mightypork.utils.eventbus.EventBus;
/** /**
* Client that can be attached to the {@link EventBus}, or added as a child * Client that can be attached to the {@link EventBus}, or added as a child
* client to another {@link DelegatingClient} * client to another {@link DelegatingClient}
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public abstract class BusNode implements BusAccess, ClientHub { public abstract class BusNode implements ClientHub {
private final BusAccess busAccess;
private final Set<Object> clients = new LinkedHashSet<>(); private final Set<Object> clients = new LinkedHashSet<>();
private boolean listening = true; private boolean listening = true;
private boolean delegating = true; private boolean delegating = true;
/**
* @param busAccess access to bus
*/
public BusNode(BusAccess busAccess)
{
this.busAccess = busAccess;
}
@Override @Override
public Collection<Object> getChildClients() public Collection<Object> getChildClients()
{ {
@@ -56,23 +44,19 @@ public abstract class BusNode implements BusAccess, ClientHub {
/** /**
* Add a child subscriber to the {@link EventBus}.<br> * Add a child subscriber to the {@link EventBus}.<br>
* *
* @param client * @param client
*/ */
@Override @Override
public void addChildClient(Object client) public void addChildClient(Object client)
{ {
if (client instanceof RootBusNode) {
throw new IllegalArgumentException("Cannot nest RootBusNode.");
}
clients.add(client); clients.add(client);
} }
/** /**
* Remove a child subscriber * Remove a child subscriber
* *
* @param client subscriber to remove * @param client subscriber to remove
*/ */
@Override @Override
@@ -86,7 +70,7 @@ public abstract class BusNode implements BusAccess, ClientHub {
/** /**
* Set whether events should be received. * Set whether events should be received.
* *
* @param listening receive events * @param listening receive events
*/ */
public void setListening(boolean listening) public void setListening(boolean listening)
@@ -97,19 +81,11 @@ public abstract class BusNode implements BusAccess, ClientHub {
/** /**
* Set whether events should be passed on to child nodes * Set whether events should be passed on to child nodes
* *
* @param delegating * @param delegating
*/ */
public void setDelegating(boolean delegating) public void setDelegating(boolean delegating)
{ {
this.delegating = delegating; this.delegating = delegating;
} }
@Override
public EventBus getEventBus()
{
return busAccess.getEventBus();
}
} }
@@ -8,7 +8,7 @@ import mightypork.utils.eventbus.EventBus;
/** /**
* Common methods for client hubs (ie delegating vlient implementations) * Common methods for client hubs (ie delegating vlient implementations)
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public interface ClientHub extends DelegatingClient, ToggleableClient { public interface ClientHub extends DelegatingClient, ToggleableClient {
@@ -27,7 +27,7 @@ public interface ClientHub extends DelegatingClient, ToggleableClient {
/** /**
* Add a child subscriber to the {@link EventBus}.<br> * Add a child subscriber to the {@link EventBus}.<br>
* *
* @param client * @param client
*/ */
public void addChildClient(Object client); public void addChildClient(Object client);
@@ -35,7 +35,7 @@ public interface ClientHub extends DelegatingClient, ToggleableClient {
/** /**
* Remove a child subscriber * Remove a child subscriber
* *
* @param client subscriber to remove * @param client subscriber to remove
*/ */
void removeChildClient(Object client); void removeChildClient(Object client);
@@ -7,7 +7,7 @@ import java.util.ArrayList;
/** /**
* Array-list with varargs constructor, intended to wrap fre clients for * Array-list with varargs constructor, intended to wrap fre clients for
* delegating client. * delegating client.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class ClientList extends ArrayList<Object> { public class ClientList extends ArrayList<Object> {
@@ -18,5 +18,4 @@ public class ClientList extends ArrayList<Object> {
super.add(c); super.add(c);
} }
} }
} }
@@ -8,7 +8,7 @@ import java.util.Collection;
* Client containing child clients. According to the contract, if the collection * Client containing child clients. According to the contract, if the collection
* of clients is ordered, the clients will be served in that order. In any case, * of clients is ordered, the clients will be served in that order. In any case,
* the {@link DelegatingClient} itself will be served beforehand. * the {@link DelegatingClient} itself will be served beforehand.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public interface DelegatingClient { public interface DelegatingClient {
@@ -8,20 +8,33 @@ import mightypork.utils.interfaces.Enableable;
/** /**
* List of clients, that can be used as a delegating client. * List of clients, that can be used as a delegating client.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class DelegatingList extends ClientList implements DelegatingClient, Enableable { public class DelegatingList extends ClientList implements DelegatingClient, Enableable, ToggleableClient {
private boolean enabled = true; private boolean enabled = true;
/**
* Delegating list with initial clients
*
* @param clients initial list members (clients)
*/
public DelegatingList(Object... clients) public DelegatingList(Object... clients)
{ {
super(clients); super(clients);
} }
/**
* Empty delegating list.
*/
public DelegatingList()
{
}
@Override @Override
public Collection<?> getChildClients() public Collection<?> getChildClients()
{ {
@@ -36,6 +49,13 @@ public class DelegatingList extends ClientList implements DelegatingClient, Enab
} }
@Override
public boolean isListening()
{
return isEnabled();
}
@Override @Override
public void setEnabled(boolean yes) public void setEnabled(boolean yes)
{ {
@@ -1,45 +0,0 @@
package mightypork.utils.eventbus.clients;
import mightypork.utils.annotations.DefaultImpl;
import mightypork.utils.eventbus.BusAccess;
import mightypork.utils.interfaces.Destroyable;
/**
* Bus node that should be directly attached to the bus.
*
* @author Ondřej Hruška (MightyPork)
*/
public abstract class RootBusNode extends BusNode implements Destroyable {
/**
* @param busAccess access to bus
*/
public RootBusNode(BusAccess busAccess)
{
super(busAccess);
getEventBus().subscribe(this);
}
@Override
public final void destroy()
{
deinit();
getEventBus().unsubscribe(this);
}
/**
* Deinitialize the subsystem<br>
* (called during destruction)
*/
@DefaultImpl
protected void deinit()
{
}
}
@@ -3,7 +3,7 @@ package mightypork.utils.eventbus.clients;
/** /**
* Client that can toggle receiving messages. * Client that can toggle receiving messages.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public interface ToggleableClient { public interface ToggleableClient {
@@ -4,22 +4,24 @@ package mightypork.utils.eventbus.events;
import mightypork.utils.eventbus.BusEvent; import mightypork.utils.eventbus.BusEvent;
import mightypork.utils.eventbus.events.flags.DirectEvent; import mightypork.utils.eventbus.events.flags.DirectEvent;
import mightypork.utils.eventbus.events.flags.NonConsumableEvent; import mightypork.utils.eventbus.events.flags.NonConsumableEvent;
import mightypork.utils.eventbus.events.flags.NonRejectableEvent;
import mightypork.utils.interfaces.Destroyable; import mightypork.utils.interfaces.Destroyable;
/** /**
* Invoke destroy() method of all subscribers. Used to deinit a system. * Invoke destroy() method of all subscribers. Used to deinit a system.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
@DirectEvent @DirectEvent
@NonConsumableEvent @NonConsumableEvent
@NonRejectableEvent
public class DestroyEvent extends BusEvent<Destroyable> { public class DestroyEvent extends BusEvent<Destroyable> {
@Override @Override
public void handleBy(Destroyable handler) public void handleBy(Destroyable handler)
{ {
handler.destroy(); handler.destroy();
} }
} }
@@ -10,7 +10,7 @@ import mightypork.utils.interfaces.Updateable;
/** /**
* Delta timing update event. Not logged. * Delta timing update event. Not logged.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
@NotLoggedEvent @NotLoggedEvent
@@ -11,7 +11,7 @@ import java.lang.annotation.Target;
/** /**
* Event that should be queued with given delay (default: 0); * Event that should be queued with given delay (default: 0);
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@@ -11,7 +11,7 @@ import java.lang.annotation.Target;
/** /**
* Event that should not be queued. * Event that should not be queued.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@@ -10,7 +10,7 @@ import java.lang.annotation.Target;
/** /**
* Event that cannot be consumed * Event that cannot be consumed
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@@ -10,7 +10,7 @@ import java.lang.annotation.Target;
/** /**
* Event that is forcibly delivered to all clients (bypass Toggleable etc) * Event that is forcibly delivered to all clients (bypass Toggleable etc)
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@@ -12,7 +12,7 @@ import java.lang.annotation.Target;
/** /**
* Event that's not worth logging, unless there was an error with it.<br> * Event that's not worth logging, unless there was an error with it.<br>
* Useful for common events that would otherwise clutter the log. * Useful for common events that would otherwise clutter the log.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@@ -11,7 +11,7 @@ import java.lang.annotation.Target;
/** /**
* Handled only by the first client, then discarded. * Handled only by the first client, then discarded.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@@ -6,7 +6,7 @@ import java.io.IOException;
/** /**
* Thrown when data could not be read successfully. * Thrown when data could not be read successfully.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class CorruptDataException extends IOException { public class CorruptDataException extends IOException {
@@ -4,7 +4,7 @@ package mightypork.utils.exceptions;
/** /**
* Thrown when a invalid value is given to a method, or found in a data object / * Thrown when a invalid value is given to a method, or found in a data object /
* file etc * file etc
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class IllegalValueException extends RuntimeException { public class IllegalValueException extends RuntimeException {
@@ -3,7 +3,7 @@ package mightypork.utils.exceptions;
/** /**
* Thrown by a map-like class when the key specified is already taken. * Thrown by a map-like class when the key specified is already taken.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class KeyAlreadyExistsException extends RuntimeException { public class KeyAlreadyExistsException extends RuntimeException {
@@ -7,7 +7,7 @@ import java.io.FileFilter;
/** /**
* File filter for certain suffixes * File filter for certain suffixes
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class FileSuffixFilter implements FileFilter { public class FileSuffixFilter implements FileFilter {
@@ -18,7 +18,7 @@ public class FileSuffixFilter implements FileFilter {
/** /**
* Suffix filter * Suffix filter
* *
* @param suffixes var-args allowed suffixes, case insensitive * @param suffixes var-args allowed suffixes, case insensitive
*/ */
public FileSuffixFilter(String... suffixes) public FileSuffixFilter(String... suffixes)
+2 -2
View File
@@ -73,10 +73,10 @@ public class FileTreeDiff {
ck2.reset(); ck2.reset();
try(FileInputStream in1 = new FileInputStream(pair.a); try(FileInputStream in1 = new FileInputStream(pair.a);
FileInputStream in2 = new FileInputStream(pair.b)) { FileInputStream in2 = new FileInputStream(pair.b)) {
try(CheckedInputStream cin1 = new CheckedInputStream(in1, ck1); try(CheckedInputStream cin1 = new CheckedInputStream(in1, ck1);
CheckedInputStream cin2 = new CheckedInputStream(in2, ck2)) { CheckedInputStream cin2 = new CheckedInputStream(in2, ck2)) {
while (true) { while (true) {
final int read1 = cin1.read(BUFFER); final int read1 = cin1.read(BUFFER);
@@ -17,16 +17,17 @@ import java.io.UnsupportedEncodingException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import mightypork.utils.Str;
import mightypork.utils.logging.Log; import mightypork.utils.logging.Log;
import mightypork.utils.string.StringUtil;
import mightypork.utils.string.validation.StringFilter; import mightypork.utils.string.validation.StringFilter;
public class FileUtils { public class FileUtil {
/** /**
* Copy directory recursively. * Copy directory recursively.
* *
* @param source source file * @param source source file
* @param target target file * @param target target file
* @throws IOException on error * @throws IOException on error
@@ -39,7 +40,7 @@ public class FileUtils {
/** /**
* Copy directory recursively - advanced variant. * Copy directory recursively - advanced variant.
* *
* @param source source file * @param source source file
* @param target target file * @param target target file
* @param filter filter accepting only files and dirs to be copied * @param filter filter accepting only files and dirs to be copied
@@ -73,7 +74,7 @@ public class FileUtils {
/** /**
* List directory recursively * List directory recursively
* *
* @param source source file * @param source source file
* @param filter filter accepting only files and dirs to be copied (or null) * @param filter filter accepting only files and dirs to be copied (or null)
* @param files list of the found files * @param files list of the found files
@@ -99,7 +100,7 @@ public class FileUtils {
/** /**
* Copy file using streams. Make sure target directory exists! * Copy file using streams. Make sure target directory exists!
* *
* @param source source file * @param source source file
* @param target target file * @param target target file
* @throws IOException on error * @throws IOException on error
@@ -117,7 +118,7 @@ public class FileUtils {
/** /**
* Copy bytes from input to output stream, leaving out stream open * Copy bytes from input to output stream, leaving out stream open
* *
* @param in input stream * @param in input stream
* @param out output stream * @param out output stream
* @throws IOException on error * @throws IOException on error
@@ -142,7 +143,7 @@ public class FileUtils {
/** /**
* Improved delete * Improved delete
* *
* @param path deleted path * @param path deleted path
* @param recursive recursive delete * @param recursive recursive delete
* @return success * @return success
@@ -166,7 +167,7 @@ public class FileUtils {
/** /**
* Read entire file to a string. * Read entire file to a string.
* *
* @param file file * @param file file
* @return file contents * @return file contents
* @throws IOException * @throws IOException
@@ -182,19 +183,19 @@ public class FileUtils {
/** /**
* Get files in a folder (create folder if needed) * Get files in a folder (create folder if needed)
* *
* @param dir folder * @param dir folder
* @return list of files * @return list of files
*/ */
public static List<File> listDirectory(File dir) public static List<File> listDirectory(File dir)
{ {
return FileUtils.listDirectory(dir, null); return FileUtil.listDirectory(dir, null);
} }
/** /**
* Get files in a folder (create folder if needed) * Get files in a folder (create folder if needed)
* *
* @param dir folder * @param dir folder
* @param filter file filter * @param filter file filter
* @return list of files * @return list of files
@@ -215,7 +216,7 @@ public class FileUtils {
/** /**
* Remove extension. * Remove extension.
* *
* @param file file * @param file file
* @return filename without extension * @return filename without extension
*/ */
@@ -233,13 +234,13 @@ public class FileUtils {
public static String getExtension(String file) public static String getExtension(String file)
{ {
return StringUtil.fromLastChar(file, '.'); return Str.fromLast(file, '.');
} }
/** /**
* Remove extension. * Remove extension.
* *
* @param filename * @param filename
* @return filename and extension * @return filename and extension
*/ */
@@ -248,13 +249,13 @@ public class FileUtils {
String ext, name; String ext, name;
try { try {
ext = StringUtil.fromLastDot(filename); ext = Str.fromLastDot(filename);
} catch (final StringIndexOutOfBoundsException e) { } catch (final StringIndexOutOfBoundsException e) {
ext = ""; ext = "";
} }
try { try {
name = StringUtil.toLastDot(filename); name = Str.toLastDot(filename);
} catch (final StringIndexOutOfBoundsException e) { } catch (final StringIndexOutOfBoundsException e) {
name = ""; name = "";
Log.w("Error extracting extension from file " + filename); Log.w("Error extracting extension from file " + filename);
@@ -266,7 +267,7 @@ public class FileUtils {
/** /**
* Read entire input stream to a string, and close it. * Read entire input stream to a string, and close it.
* *
* @param in input stream * @param in input stream
* @return file contents * @return file contents
*/ */
@@ -278,7 +279,7 @@ public class FileUtils {
/** /**
* Read input stream to a string, and close it. * Read input stream to a string, and close it.
* *
* @param in input stream * @param in input stream
* @param lines max number of lines (-1 to disable limit) * @param lines max number of lines (-1 to disable limit)
* @return file contents * @return file contents
@@ -335,16 +336,23 @@ public class FileUtils {
public static InputStream getResource(String path) public static InputStream getResource(String path)
{ {
final InputStream in = FileUtils.class.getResourceAsStream(path); final InputStream in = FileUtil.class.getResourceAsStream(path);
if (in != null) return in; if (in != null) return in;
try { try {
return new FileInputStream(new File(".", path)); return new FileInputStream(new File(".", path));
} catch (final FileNotFoundException e) { } catch (final FileNotFoundException e) {
// error
Log.w("Could not open resource stream: " + path); try {
return null; return new FileInputStream(WorkDir.getFile(path));
} catch (final FileNotFoundException e2) {
Log.w("Could not open resource stream, file not found: " + path);
return null;
}
} }
} }
@@ -352,13 +360,13 @@ public class FileUtils {
public static String getResourceAsString(String path) public static String getResourceAsString(String path)
{ {
return streamToString(FileUtils.class.getResourceAsStream(path)); return streamToString(getResource(path));
} }
/** /**
* Save string to file * Save string to file
* *
* @param file file * @param file file
* @param text string * @param text string
* @throws IOException on error * @throws IOException on error
@@ -394,29 +402,29 @@ public class FileUtils {
public static String getBasename(String name) public static String getBasename(String name)
{ {
return StringUtil.toLastChar(StringUtil.fromLastChar(name, '/'), '.'); return Str.toLast(Str.fromLast(name, '/'), '.');
} }
public static String getFilename(String name) public static String getFilename(String name)
{ {
return StringUtil.fromLastChar(name, '/'); return Str.fromLast(name, '/');
} }
/** /**
* Copy resource to file * Copy resource to file
* *
* @param resname resource name * @param resname resource name
* @param file out file * @param file out file
* @throws IOException * @throws IOException
*/ */
public static void resourceToFile(String resname, File file) throws IOException public static void resourceToFile(String resname, File file) throws IOException
{ {
try(InputStream in = FileUtils.getResource(resname); try(InputStream in = FileUtil.getResource(resname);
OutputStream out = new FileOutputStream(file)) { OutputStream out = new FileOutputStream(file)) {
FileUtils.copyStream(in, out); FileUtil.copyStream(in, out);
} }
} }
@@ -424,14 +432,14 @@ public class FileUtils {
/** /**
* Get resource as string, safely closing streams. * Get resource as string, safely closing streams.
* *
* @param resname resource name * @param resname resource name
* @return resource as string, empty string on failure * @return resource as string, empty string on failure
* @throws IOException on fail * @throws IOException on fail
*/ */
public static String resourceToString(String resname) throws IOException public static String resourceToString(String resname) throws IOException
{ {
try(InputStream in = FileUtils.getResource(resname)) { try(InputStream in = FileUtil.getResource(resname)) {
return streamToString(in); return streamToString(in);
} }
} }
+1 -1
View File
@@ -9,7 +9,7 @@ import java.nio.channels.FileLock;
/** /**
* Instance lock (avoid running twice) * Instance lock (avoid running twice)
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class InstanceLock { public class InstanceLock {
+96
View File
@@ -0,0 +1,96 @@
package mightypork.utils.files;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import mightypork.utils.logging.Log;
/**
* Working directory helper.
*
* @author Ondřej Hruška (MightyPork)
*/
public class WorkDir {
private static File baseDir = new File(".");
private static Map<String, String> namedPaths = new HashMap<>();
/**
* Initialize the workdir for the given root path
*
* @param workdir workdir root path
*/
public static void setBaseDir(File workdir)
{
WorkDir.baseDir = workdir;
}
/**
* Add a path alias (dir or file), relative to the workdir.
*
* @param alias path alias
* @param path path relative to workdir
*/
public static void addPath(String alias, String path)
{
namedPaths.put(alias, path);
}
/**
* Get workdir folder, create if not exists.
*
* @param path dir path relative to workdir
* @return dir file
*/
public static File getDir(String path)
{
if (namedPaths.containsKey(path)) path = namedPaths.get(path);
final File f = new File(baseDir, path);
if (!f.exists()) {
if (!f.mkdirs()) {
Log.w("Could not create a directory: " + f + " (path: " + path + ")");
}
}
return f;
}
/**
* Get workdir file, create parent if not exists.
*
* @param path dir path relative to workdir
* @return dir file
*/
public static File getFile(String path)
{
if (namedPaths.containsKey(path)) path = namedPaths.get(path);
final File f = new File(baseDir, path);
// create the parent dir
if (!f.getParent().equals(baseDir)) {
f.getParentFile().mkdirs();
}
return f;
}
/**
* @return the workdir File
*/
public static File getBaseDir()
{
return baseDir;
}
}
@@ -1,71 +0,0 @@
package mightypork.utils.files.config;
import mightypork.utils.Convert;
public abstract class Property<T extends Object> {
private final String comment;
private final String key;
private T value;
private final T defaultValue;
public Property(String key, T defaultValue, String comment)
{
super();
this.comment = comment;
this.key = key;
this.value = defaultValue;
this.defaultValue = defaultValue;
}
public final void parse(String string)
{
setValue(decode(string, defaultValue));
}
public abstract T decode(String string, T defval);
public String encode(T value)
{
return Convert.toString(value, Convert.toString(defaultValue));
}
@Override
public final String toString()
{
return encode(value);
}
public T getValue()
{
return value;
}
@SuppressWarnings("unchecked")
public void setValue(Object value)
{
this.value = (T) value;
}
public String getComment()
{
return comment;
}
public String getKey()
{
return key;
}
}
@@ -1,377 +0,0 @@
package mightypork.utils.files.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map.Entry;
import java.util.TreeMap;
import mightypork.utils.Convert;
import mightypork.utils.logging.Log;
/**
* Property manager with advanced formatting and value checking.
*
* @author Ondřej Hruška (MightyPork)
*/
public class PropertyManager {
private class BooleanProperty extends Property<Boolean> {
public BooleanProperty(String key, Boolean defaultValue, String comment)
{
super(key, defaultValue, comment);
}
@Override
public Boolean decode(String string, Boolean defval)
{
return Convert.toBoolean(string, defval);
}
}
private class IntegerProperty extends Property<Integer> {
public IntegerProperty(String key, Integer defaultValue, String comment)
{
super(key, defaultValue, comment);
}
@Override
public Integer decode(String string, Integer defval)
{
return Convert.toInteger(string, defval);
}
}
private class DoubleProperty extends Property<Double> {
public DoubleProperty(String key, Double defaultValue, String comment)
{
super(key, defaultValue, comment);
}
@Override
public Double decode(String string, Double defval)
{
return Convert.toDouble(string, defval);
}
}
private class StringProperty extends Property<String> {
public StringProperty(String key, String defaultValue, String comment)
{
super(key, defaultValue, comment);
}
@Override
public String decode(String string, String defval)
{
return Convert.toString(string, defval);
}
}
/** put newline before entry comments */
private boolean cfgNewlineBeforeComments = true;
/** Put newline between sections. */
private boolean cfgSeparateSections = true;
private final File file;
private String fileComment = "";
private final TreeMap<String, Property<?>> entries;
private final TreeMap<String, String> renameTable;
private SortedProperties props = new SortedProperties();
/**
* Create property manager from file path and an initial comment.
*
* @param file file with the props
* @param comment the initial comment. Use \n in it if you want.
*/
public PropertyManager(File file, String comment)
{
this.file = file;
this.entries = new TreeMap<>();
this.renameTable = new TreeMap<>();
this.fileComment = comment;
}
/**
* Load, fix and write to file.
*/
public void load()
{
if (!file.getParentFile().mkdirs()) {
if (!file.getParentFile().exists()) {
throw new RuntimeException("Cound not create config file.");
}
}
try(FileInputStream fis = new FileInputStream(file)) {
props.load(fis);
} catch (final IOException e) {
props = new SortedProperties();
}
props.cfgBlankRowBetweenSections = cfgSeparateSections;
props.cfgBlankRowBeforeComment = cfgNewlineBeforeComments;
// rename keys
for (final Entry<String, String> entry : renameTable.entrySet()) {
final String pr = props.getProperty(entry.getKey());
if (pr == null) continue;
props.remove(entry.getKey());
props.setProperty(entry.getValue(), pr);
}
for (final Property<?> entry : entries.values()) {
entry.parse(props.getProperty(entry.getKey()));
}
renameTable.clear();
}
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());
if (entry.getComment() != null) {
props.setKeyComment(entry.getKey(), entry.getComment());
}
props.setProperty(entry.getKey(), entry.toString());
}
// removed unused props
for (final String propname : props.keySet().toArray(new String[props.size()])) {
if (!keyList.contains(propname)) {
props.remove(propname);
}
}
try(FileOutputStream fos = new FileOutputStream(file)) {
props.store(fos, fileComment);
}
} catch (final IOException ioe) {
ioe.printStackTrace();
}
}
/**
* @param newlineBeforeComments put newline before comments
*/
public void cfgNewlineBeforeComments(boolean newlineBeforeComments)
{
this.cfgNewlineBeforeComments = newlineBeforeComments;
}
/**
* @param separateSections do separate sections by newline
*/
public void cfgSeparateSections(boolean separateSections)
{
this.cfgSeparateSections = separateSections;
}
/**
* Get a property entry (rarely used)
*
* @param k key
* @return the entry
*/
public Property<?> getProperty(String k)
{
try {
return entries.get(k);
} catch (final Exception e) {
Log.w(e);
return null;
}
}
/**
* Get boolean property
*
* @param k key
* @return the boolean found, or false
*/
public Boolean getBoolean(String k)
{
return Convert.toBoolean(getProperty(k).getValue());
}
/**
* Get numeric property
*
* @param k key
* @return the int found, or null
*/
public Integer getInteger(String k)
{
return Convert.toInteger(getProperty(k).getValue());
}
/**
* Get numeric property as double
*
* @param k key
* @return the double found, or null
*/
public Double getDouble(String k)
{
return Convert.toDouble(getProperty(k).getValue());
}
/**
* Get string property
*
* @param k key
* @return the string found, or null
*/
public String getString(String k)
{
return Convert.toString(getProperty(k).getValue());
}
/**
* Get arbitrary property. Make sure it's of the right type!
*
* @param k key
* @return the prioperty found
*/
@SuppressWarnings("unchecked")
public <T> T getValue(String k)
{
try {
return ((Property<T>) getProperty(k)).getValue();
} catch (final ClassCastException e) {
return null;
}
}
/**
* Add a boolean property
*
* @param k key
* @param d default value
* @param comment the in-file comment
*/
public void putBoolean(String k, boolean d, String comment)
{
putProperty(new BooleanProperty(k, d, comment));
}
/**
* Add a numeric property (double)
*
* @param k key
* @param d default value
* @param comment the in-file comment
*/
public void putDouble(String k, double d, String comment)
{
putProperty(new DoubleProperty(k, d, comment));
}
/**
* Add a numeric property
*
* @param k key
* @param d default value
* @param comment the in-file comment
*/
public void putInteger(String k, int d, String comment)
{
putProperty(new IntegerProperty(k, d, comment));
}
/**
* Add a string property
*
* @param k key
* @param d default value
* @param comment the in-file comment
*/
public void putString(String k, String d, String comment)
{
putProperty(new StringProperty(k, d, comment));
}
/**
* Add a range property
*
* @param prop property to put
*/
public <T> void putProperty(Property<T> prop)
{
entries.put(prop.getKey(), prop);
}
/**
* Rename key before loading; value is preserved
*
* @param oldKey old key
* @param newKey new key
*/
public void renameKey(String oldKey, String newKey)
{
renameTable.put(oldKey, newKey);
return;
}
/**
* Set value saved to certain key.
*
* @param key key
* @param value the saved value
*/
public void setValue(String key, Object value)
{
getProperty(key).setValue(value);
}
public void setFileComment(String fileComment)
{
this.fileComment = fileComment;
}
}
+12 -12
View File
@@ -10,13 +10,13 @@ import java.util.HashSet;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;
import mightypork.utils.files.FileUtils; import mightypork.utils.files.FileUtil;
import mightypork.utils.logging.Log; import mightypork.utils.logging.Log;
/** /**
* Class for building a zip file * Class for building a zip file
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class ZipBuilder { public class ZipBuilder {
@@ -41,7 +41,7 @@ public class ZipBuilder {
/** /**
* Add stream to a path * Add stream to a path
* *
* @param path path * @param path path
* @param in stream * @param in stream
* @throws IOException * @throws IOException
@@ -57,13 +57,13 @@ public class ZipBuilder {
out.putNextEntry(new ZipEntry(path)); out.putNextEntry(new ZipEntry(path));
FileUtils.copyStream(in, out); FileUtil.copyStream(in, out);
} }
/** /**
* Add string as a file * Add string as a file
* *
* @param path path * @param path path
* @param text text to write * @param text text to write
* @throws IOException * @throws IOException
@@ -76,15 +76,15 @@ public class ZipBuilder {
out.putNextEntry(new ZipEntry(path)); out.putNextEntry(new ZipEntry(path));
try(InputStream in = FileUtils.stringToStream(text)) { try(InputStream in = FileUtil.stringToStream(text)) {
FileUtils.copyStream(in, out); FileUtil.copyStream(in, out);
} }
} }
/** /**
* Add resource obtained via FileUtils.getResource() * Add resource obtained via FileUtils.getResource()
* *
* @param path path * @param path path
* @param resPath resource path * @param resPath resource path
* @throws IOException * @throws IOException
@@ -97,15 +97,15 @@ public class ZipBuilder {
out.putNextEntry(new ZipEntry(path)); out.putNextEntry(new ZipEntry(path));
try(InputStream in = FileUtils.getResource(resPath)) { try(InputStream in = FileUtil.getResource(resPath)) {
FileUtils.copyStream(in, out); FileUtil.copyStream(in, out);
} }
} }
/** /**
* Normalize path * Normalize path
* *
* @param path original path * @param path original path
* @return normalized path * @return normalized path
*/ */
@@ -121,7 +121,7 @@ public class ZipBuilder {
/** /**
* Close the zip stream * Close the zip stream
* *
* @throws IOException * @throws IOException
*/ */
public void close() throws IOException public void close() throws IOException
+13 -13
View File
@@ -13,14 +13,14 @@ import java.util.List;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
import mightypork.utils.files.FileUtils; import mightypork.utils.files.FileUtil;
import mightypork.utils.logging.Log; import mightypork.utils.logging.Log;
import mightypork.utils.string.validation.StringFilter; import mightypork.utils.string.validation.StringFilter;
/** /**
* Utilities for manipulating zip files * Utilities for manipulating zip files
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class ZipUtils { public class ZipUtils {
@@ -30,7 +30,7 @@ public class ZipUtils {
/** /**
* Extract zip file to target directory * Extract zip file to target directory
* *
* @param file zip file * @param file zip file
* @param outputDir target directory * @param outputDir target directory
* @param filter string filter (will be used to test entry names (paths)) * @param filter string filter (will be used to test entry names (paths))
@@ -47,7 +47,7 @@ public class ZipUtils {
/** /**
* Extract zip file to target directory * Extract zip file to target directory
* *
* @param zip open zip file * @param zip open zip file
* @param outputDir target directory * @param outputDir target directory
* @param filter string filter (will be used to test entry names (paths)) * @param filter string filter (will be used to test entry names (paths))
@@ -88,7 +88,7 @@ public class ZipUtils {
/** /**
* Read zip entries and add their paths to a list * Read zip entries and add their paths to a list
* *
* @param zipFile open zip file * @param zipFile open zip file
* @return list of entry names * @return list of entry names
* @throws IOException on error * @throws IOException on error
@@ -103,7 +103,7 @@ public class ZipUtils {
/** /**
* Read zip entries and add their paths to a list * Read zip entries and add their paths to a list
* *
* @param zip open zip file * @param zip open zip file
* @return list of entry names * @return list of entry names
* @throws IOException on error * @throws IOException on error
@@ -129,7 +129,7 @@ public class ZipUtils {
/** /**
* Extract one zip entry to target file * Extract one zip entry to target file
* *
* @param zip open zip file * @param zip open zip file
* @param entry entry from the zip file * @param entry entry from the zip file
* @param destFile destination file ((NOT directory!) * @param destFile destination file ((NOT directory!)
@@ -140,18 +140,18 @@ public class ZipUtils {
if (!destFile.getParentFile().mkdirs()) throw new IOException("Could not create output directory."); if (!destFile.getParentFile().mkdirs()) throw new IOException("Could not create output directory.");
try(InputStream in = zip.getInputStream(entry); try(InputStream in = zip.getInputStream(entry);
BufferedInputStream is = new BufferedInputStream(in); BufferedInputStream is = new BufferedInputStream(in);
FileOutputStream fos = new FileOutputStream(destFile); FileOutputStream fos = new FileOutputStream(destFile);
BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE)) { BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE)) {
FileUtils.copyStream(is, dest); FileUtil.copyStream(is, dest);
} }
} }
/** /**
* Load zip entry to String * Load zip entry to String
* *
* @param zip open zip file * @param zip open zip file
* @param entry entry from the zip file * @param entry entry from the zip file
* @return loaded string * @return loaded string
@@ -162,7 +162,7 @@ public class ZipUtils {
BufferedInputStream is = null; BufferedInputStream is = null;
try { try {
is = new BufferedInputStream(zip.getInputStream(entry)); is = new BufferedInputStream(zip.getInputStream(entry));
final String s = FileUtils.streamToString(is); final String s = FileUtil.streamToString(is);
return s; return s;
} finally { } finally {
try { try {
@@ -3,7 +3,7 @@ package mightypork.utils.interfaces;
/** /**
* Object that can be destroyed (free resources etc) * Object that can be destroyed (free resources etc)
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public interface Destroyable { public interface Destroyable {
@@ -5,14 +5,14 @@ package mightypork.utils.interfaces;
* Can be enabled or disabled.<br> * Can be enabled or disabled.<br>
* Implementations should take appropriate action (ie. stop listening to events, * Implementations should take appropriate action (ie. stop listening to events,
* updating etc.) * updating etc.)
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public interface Enableable { public interface Enableable {
/** /**
* Change enabled state * Change enabled state
* *
* @param yes enabled * @param yes enabled
*/ */
public void setEnabled(boolean yes); public void setEnabled(boolean yes);
@@ -0,0 +1,15 @@
package mightypork.utils.interfaces;
/**
* Element that can be hidden or visible
*
* @author Ondřej Hruška (MightyPork)
*/
public interface Hideable {
void setVisible(boolean yes);
boolean isVisible();
}
@@ -3,7 +3,7 @@ package mightypork.utils.interfaces;
/** /**
* Can be paused & resumed * Can be paused & resumed
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public interface Pauseable { public interface Pauseable {
@@ -3,7 +3,7 @@ package mightypork.utils.interfaces;
/** /**
* Can be asked to update it's state * Can be asked to update it's state
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public interface Pollable { public interface Pollable {
@@ -3,14 +3,14 @@ package mightypork.utils.interfaces;
/** /**
* Uses delta timing * Uses delta timing
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public interface Updateable { public interface Updateable {
/** /**
* Update item state based on elapsed time * Update item state based on elapsed time
* *
* @param delta time elapsed since last update, in seconds * @param delta time elapsed since last update, in seconds
*/ */
public void update(double delta); public void update(double delta);
+19 -21
View File
@@ -13,12 +13,12 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import mightypork.utils.Reflect; import mightypork.utils.Reflect;
import mightypork.utils.Support; import mightypork.utils.Str;
/** /**
* Universal data storage system (main API class) * Universal data storage system (main API class)
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class Ion { public class Ion {
@@ -85,7 +85,6 @@ public class Ion {
/** Array of arbitrary objects */ /** Array of arbitrary objects */
public static final int OBJECT_ARRAY = 26; public static final int OBJECT_ARRAY = 26;
/** Ionizables<Mark, Class> */ /** Ionizables<Mark, Class> */
private static Map<Integer, Class<?>> markToClass = new HashMap<>(); private static Map<Integer, Class<?>> markToClass = new HashMap<>();
private static Map<Class<?>, Integer> classToMark = new HashMap<>(); private static Map<Class<?>, Integer> classToMark = new HashMap<>();
@@ -109,7 +108,7 @@ public class Ion {
/** /**
* Register a type for writing/loading. * Register a type for writing/loading.
* *
* @param mark binary ION mark * @param mark binary ION mark
* @param objClass class of the registered object * @param objClass class of the registered object
*/ */
@@ -117,7 +116,7 @@ public class Ion {
{ {
if (!IonBinary.class.isAssignableFrom(objClass)) { if (!IonBinary.class.isAssignableFrom(objClass)) {
if (!IonBundled.class.isAssignableFrom(objClass)) { if (!IonBundled.class.isAssignableFrom(objClass)) {
throw new IllegalArgumentException("Cannot register directly: " + Support.str(objClass)); throw new IllegalArgumentException("Cannot register directly: " + Str.val(objClass));
} }
} }
@@ -129,14 +128,14 @@ public class Ion {
/** /**
* Try to register a type using a static final ION_MARK int field. * Try to register a type using a static final ION_MARK int field.
* *
* @param objClass type class * @param objClass type class
*/ */
public static void register(Class<?> objClass) public static void register(Class<?> objClass)
{ {
if (!IonBinary.class.isAssignableFrom(objClass)) { if (!IonBinary.class.isAssignableFrom(objClass)) {
if (!IonBundled.class.isAssignableFrom(objClass)) { if (!IonBundled.class.isAssignableFrom(objClass)) {
throw new IllegalArgumentException("Cannot register directly: " + Support.str(objClass)); throw new IllegalArgumentException("Cannot register directly: " + Str.val(objClass));
} }
} }
@@ -162,14 +161,14 @@ public class Ion {
registerUsingMark(mark, objClass); registerUsingMark(mark, objClass);
} catch (final Exception e) { } catch (final Exception e) {
throw new RuntimeException("Could not register " + Support.str(objClass) + " using an ION_MARK field.", e); throw new RuntimeException("Could not register " + Str.val(objClass) + " using an ION_MARK field.", e);
} }
} }
/** /**
* Register new binary ionizer. * Register new binary ionizer.
* *
* @param mark binary ION mark * @param mark binary ION mark
* @param ionizer ionizer * @param ionizer ionizer
*/ */
@@ -185,7 +184,7 @@ public class Ion {
/** /**
* Register new bundled ionizer. * Register new bundled ionizer.
* *
* @param mark binary ION mark * @param mark binary ION mark
* @param ionizer ionizer * @param ionizer ionizer
*/ */
@@ -224,7 +223,7 @@ public class Ion {
} }
if (classToMark.containsKey(objClass)) { if (classToMark.containsKey(objClass)) {
throw new IllegalArgumentException(Support.str(objClass) + " is already registered."); throw new IllegalArgumentException(Str.val(objClass) + " is already registered.");
} }
} }
@@ -298,7 +297,7 @@ public class Ion {
/** /**
* Get ion input * Get ion input
* *
* @param path file path to read * @param path file path to read
* @return input * @return input
* @throws IOException * @throws IOException
@@ -311,7 +310,7 @@ public class Ion {
/** /**
* Get ion input * Get ion input
* *
* @param file file to read * @param file file to read
* @return input * @return input
* @throws IOException * @throws IOException
@@ -325,7 +324,7 @@ public class Ion {
/** /**
* Get ion output * Get ion output
* *
* @param path file path to write * @param path file path to write
* @return output * @return output
* @throws IOException * @throws IOException
@@ -338,7 +337,7 @@ public class Ion {
/** /**
* Get ion output * Get ion output
* *
* @param file file to write * @param file file to write
* @return output * @return output
* @throws IOException * @throws IOException
@@ -364,7 +363,7 @@ public class Ion {
/** /**
* Try to unwrap an object from bundle. The object class must have implicit * Try to unwrap an object from bundle. The object class must have implicit
* accessible constructor. * accessible constructor.
* *
* @param bundle unwrapped bundle * @param bundle unwrapped bundle
* @param objClass class of desired object * @param objClass class of desired object
* @return the object unwrapped * @return the object unwrapped
@@ -377,7 +376,7 @@ public class Ion {
inst.load(bundle); inst.load(bundle);
return inst; return inst;
} catch (InstantiationException | IllegalAccessException e) { } catch (InstantiationException | IllegalAccessException e) {
throw new IOException("Could not instantiate " + Support.str(objClass) + "."); throw new IOException("Could not instantiate " + Str.val(objClass) + ".");
} }
} }
@@ -477,13 +476,13 @@ public class Ion {
/** /**
* Make sure object is registered in the table. * Make sure object is registered in the table.
* *
* @throws IOException if not registered or class mismatch * @throws IOException if not registered or class mismatch
*/ */
static void assertRegistered(Object obj) static void assertRegistered(Object obj)
{ {
if (!isRegistered(obj)) { if (!isRegistered(obj)) {
throw new RuntimeException("Type not registered: " + Support.str(obj.getClass())); throw new RuntimeException("Type not registered: " + Str.val(obj.getClass()));
} }
} }
@@ -496,8 +495,7 @@ public class Ion {
{ {
final List<Integer> toRemove = new ArrayList<>(); final List<Integer> toRemove = new ArrayList<>();
// remove direct
// remove direct
for (final Integer mark : markToClass.keySet()) { for (final Integer mark : markToClass.keySet()) {
if (!isMarkReserved(mark)) { if (!isMarkReserved(mark)) {
toRemove.add(mark); toRemove.add(mark);
+3 -3
View File
@@ -7,14 +7,14 @@ import java.io.IOException;
/** /**
* Binary ion object. If a class implements both binary and bundled, then binary * Binary ion object. If a class implements both binary and bundled, then binary
* will be preferred by both IonInput and IonOutput. * will be preferred by both IonInput and IonOutput.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public interface IonBinary { public interface IonBinary {
/** /**
* Load data from the input stream. * Load data from the input stream.
* *
* @param in input stream * @param in input stream
* @throws IOException * @throws IOException
*/ */
@@ -24,7 +24,7 @@ public interface IonBinary {
/** /**
* Store data to output stream (in such way that the load method will later * Store data to output stream (in such way that the load method will later
* be able to read it). * be able to read it).
* *
* @param out Output stream * @param out Output stream
* @throws IOException * @throws IOException
*/ */
+3 -3
View File
@@ -4,14 +4,14 @@ package mightypork.utils.ion;
/** /**
* Bundled ion object. If a class implements both binary and bundled, then * Bundled ion object. If a class implements both binary and bundled, then
* binary will be preferred by both IonInput and IonOutput. * binary will be preferred by both IonInput and IonOutput.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public interface IonBundled { public interface IonBundled {
/** /**
* Load this object from the data bundle * Load this object from the data bundle
* *
* @param in bundle to load from * @param in bundle to load from
*/ */
void load(IonDataBundle in); void load(IonDataBundle in);
@@ -19,7 +19,7 @@ public interface IonBundled {
/** /**
* Save this object to the data bundle * Save this object to the data bundle
* *
* @param out bundle to save into * @param out bundle to save into
*/ */
void save(IonDataBundle out); void save(IonDataBundle out);
+18 -18
View File
@@ -12,7 +12,7 @@ import java.util.Map;
/** /**
* Ion data bundle - simplified Map with facilities for storing maps and * Ion data bundle - simplified Map with facilities for storing maps and
* sequences. * sequences.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class IonDataBundle implements IonBinary { public class IonDataBundle implements IonBinary {
@@ -22,7 +22,7 @@ public class IonDataBundle implements IonBinary {
/** /**
* Clear & fill a provided bundle with elements from a bundle value * Clear & fill a provided bundle with elements from a bundle value
* *
* @param key key * @param key key
* @param filled bundle to fill * @param filled bundle to fill
*/ */
@@ -39,7 +39,7 @@ public class IonDataBundle implements IonBinary {
/** /**
* Check if a key is used in the bundle * Check if a key is used in the bundle
* *
* @param key key to check * @param key key to check
* @return true if this key is used in the bundle * @return true if this key is used in the bundle
*/ */
@@ -51,7 +51,7 @@ public class IonDataBundle implements IonBinary {
/** /**
* Check if a value is contained in the bundle * Check if a value is contained in the bundle
* *
* @param value value to check * @param value value to check
* @return true if this value is contained in the bundle * @return true if this value is contained in the bundle
*/ */
@@ -63,7 +63,7 @@ public class IonDataBundle implements IonBinary {
/** /**
* Get a map value * Get a map value
* *
* @param key key * @param key key
* @return a new Map with elements from that value * @return a new Map with elements from that value
*/ */
@@ -75,7 +75,7 @@ public class IonDataBundle implements IonBinary {
/** /**
* Clear & fill the provided map with elements from a map value * Clear & fill the provided map with elements from a map value
* *
* @param key key * @param key key
* @param filled Map to fill * @param filled Map to fill
*/ */
@@ -91,7 +91,7 @@ public class IonDataBundle implements IonBinary {
/** /**
* Get a sequence value * Get a sequence value
* *
* @param key key * @param key key
* @return a new Collection with elements from that value * @return a new Collection with elements from that value
*/ */
@@ -103,7 +103,7 @@ public class IonDataBundle implements IonBinary {
/** /**
* Clear & fill the provided Collection with elements from a sequence value * Clear & fill the provided Collection with elements from a sequence value
* *
* @param key key * @param key key
* @param filled Collection to fill * @param filled Collection to fill
* @return the filled collection * @return the filled collection
@@ -122,7 +122,7 @@ public class IonDataBundle implements IonBinary {
/** /**
* Load a bundled object from a bundle value.<br> * Load a bundled object from a bundle value.<br>
* The object does not have to be registered. * The object does not have to be registered.
* *
* @param key key * @param key key
* @param loaded loaded object * @param loaded loaded object
* @return the loaded object * @return the loaded object
@@ -141,7 +141,7 @@ public class IonDataBundle implements IonBinary {
/** /**
* Save a bundled object to a bundle value.<br> * Save a bundled object to a bundle value.<br>
* The object does not have to be registered. * The object does not have to be registered.
* *
* @param key key * @param key key
* @param saved saved object * @param saved saved object
*/ */
@@ -155,7 +155,7 @@ public class IonDataBundle implements IonBinary {
/** /**
* Get value, or fallback (if none found of with bad type). * Get value, or fallback (if none found of with bad type).
* *
* @param key * @param key
* @param fallback value * @param fallback value
* @return value * @return value
@@ -174,7 +174,7 @@ public class IonDataBundle implements IonBinary {
/** /**
* Get value, or null (if none found of with bad type). * Get value, or null (if none found of with bad type).
* *
* @param key * @param key
* @return value * @return value
*/ */
@@ -302,7 +302,7 @@ public class IonDataBundle implements IonBinary {
/** /**
* Put a sequence to the bundle. * Put a sequence to the bundle.
* *
* @param key key * @param key key
* @param c value (Collection) * @param c value (Collection)
*/ */
@@ -315,7 +315,7 @@ public class IonDataBundle implements IonBinary {
/** /**
* Put a map to the bundle. * Put a map to the bundle.
* *
* @param key key * @param key key
* @param m value (Map) * @param m value (Map)
*/ */
@@ -342,7 +342,7 @@ public class IonDataBundle implements IonBinary {
/** /**
* Get number of elements in the bundle * Get number of elements in the bundle
* *
* @return size * @return size
*/ */
public int size() public int size()
@@ -353,7 +353,7 @@ public class IonDataBundle implements IonBinary {
/** /**
* Check whether the bundle is empty * Check whether the bundle is empty
* *
* @return true if empty * @return true if empty
*/ */
public boolean isEmpty() public boolean isEmpty()
@@ -373,7 +373,7 @@ public class IonDataBundle implements IonBinary {
/** /**
* Remove a value by key * Remove a value by key
* *
* @param key key to remove * @param key key to remove
* @return the removed object * @return the removed object
*/ */
@@ -385,7 +385,7 @@ public class IonDataBundle implements IonBinary {
/** /**
* Put all from another bundle * Put all from another bundle
* *
* @param anotherBundle another bundle * @param anotherBundle another bundle
*/ */
public void putAll(IonDataBundle anotherBundle) public void putAll(IonDataBundle anotherBundle)
+10 -12
View File
@@ -19,7 +19,7 @@ import mightypork.utils.exceptions.CorruptDataException;
/** /**
* Ion input stream * Ion input stream
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class IonInput implements Closeable { public class IonInput implements Closeable {
@@ -45,7 +45,7 @@ public class IonInput implements Closeable {
/** /**
* Read int 0-255. Suitable when the int was written using * Read int 0-255. Suitable when the int was written using
* <code>writeIntByte()</code> method. * <code>writeIntByte()</code> method.
* *
* @return int * @return int
* @throws IOException * @throws IOException
*/ */
@@ -58,7 +58,7 @@ public class IonInput implements Closeable {
/** /**
* Read an int 0-65535. Suitable when the int was written using * Read an int 0-65535. Suitable when the int was written using
* <code>writeIntShort()</code> method. * <code>writeIntShort()</code> method.
* *
* @return int * @return int
* @throws IOException * @throws IOException
*/ */
@@ -273,7 +273,7 @@ public class IonInput implements Closeable {
* If, however, an object of invalid or different type is found, an * If, however, an object of invalid or different type is found, an
* exception will be thrown. * exception will be thrown.
* </p> * </p>
* *
* @param def default value. * @param def default value.
* @return the loaded object * @return the loaded object
* @throws CorruptDataException * @throws CorruptDataException
@@ -292,7 +292,7 @@ public class IonInput implements Closeable {
/** /**
* Read single object, preceded by a mark. * Read single object, preceded by a mark.
* *
* @return the loaded object * @return the loaded object
* @throws IOException * @throws IOException
*/ */
@@ -300,7 +300,6 @@ public class IonInput implements Closeable {
{ {
final int mark = readMark(); final int mark = readMark();
try { try {
if (Ion.isMarkForBinary(mark)) { if (Ion.isMarkForBinary(mark)) {
@@ -308,7 +307,6 @@ public class IonInput implements Closeable {
loaded = (IonBinary) Ion.getClassForMark(mark).newInstance(); loaded = (IonBinary) Ion.getClassForMark(mark).newInstance();
loaded.load(this); loaded.load(this);
return loaded; return loaded;
} }
@@ -413,7 +411,7 @@ public class IonInput implements Closeable {
/** /**
* Reads mark and returns true if the mark is ENTRY, false if the mark is * Reads mark and returns true if the mark is ENTRY, false if the mark is
* END. Throws an exception otherwise. * END. Throws an exception otherwise.
* *
* @return mark was ENTRY * @return mark was ENTRY
* @throws IOException when the mark is neither ENTRY or END. * @throws IOException when the mark is neither ENTRY or END.
*/ */
@@ -429,7 +427,7 @@ public class IonInput implements Closeable {
/** /**
* Read a sequence of elements into an ArrayList * Read a sequence of elements into an ArrayList
* *
* @return the collection * @return the collection
* @throws IOException * @throws IOException
*/ */
@@ -441,7 +439,7 @@ public class IonInput implements Closeable {
/** /**
* Load entries into a collection. The collection is cleaned first. * Load entries into a collection. The collection is cleaned first.
* *
* @param filled collection to populate * @param filled collection to populate
* @return the collection * @return the collection
* @throws IOException * @throws IOException
@@ -463,7 +461,7 @@ public class IonInput implements Closeable {
/** /**
* Read element pairs into a HashMap * Read element pairs into a HashMap
* *
* @return the map * @return the map
* @throws IOException * @throws IOException
*/ */
@@ -475,7 +473,7 @@ public class IonInput implements Closeable {
/** /**
* Load data into a map. The map is cleaned first. * Load data into a map. The map is cleaned first.
* *
* @param filled filled map * @param filled filled map
* @return the map * @return the map
* @throws IOException * @throws IOException
+3 -4
View File
@@ -16,7 +16,7 @@ import java.util.Map.Entry;
/** /**
* Ion output stream * Ion output stream
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class IonOutput implements Closeable { public class IonOutput implements Closeable {
@@ -203,7 +203,7 @@ public class IonOutput implements Closeable {
/** /**
* Write array of objects. Works with all that is supported by writeObject() * Write array of objects. Works with all that is supported by writeObject()
* *
* @param arr array to write * @param arr array to write
* @throws IOException on IO error or on invalid object type. * @throws IOException on IO error or on invalid object type.
*/ */
@@ -268,7 +268,7 @@ public class IonOutput implements Closeable {
/** /**
* Write an object. Supported are built-in types and types registered to * Write an object. Supported are built-in types and types registered to
* Ion. * Ion.
* *
* @param obj obj to write * @param obj obj to write
* @throws IOException on IO error or invalid object type. * @throws IOException on IO error or invalid object type.
*/ */
@@ -299,7 +299,6 @@ public class IonOutput implements Closeable {
return; return;
} }
if (Ion.isObjectIndirectBundled(obj)) { if (Ion.isObjectIndirectBundled(obj)) {
final IonizerBundled<?> ionizer = Ion.getIonizerBundledForClass(obj.getClass()); final IonizerBundled<?> ionizer = Ion.getIonizerBundledForClass(obj.getClass());
+9 -6
View File
@@ -1,35 +1,38 @@
package mightypork.utils.ion; package mightypork.utils.ion;
import java.io.IOException; import java.io.IOException;
/** /**
* External ionizer using a IonOutput / IonInput - can be used if the data type * External ionizer using a IonOutput / IonInput - can be used if the data type
* cannot be modified to implement the proper interface * cannot be modified to implement the proper interface
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
* @param <T> * @param <T>
*/ */
public abstract class IonizerBinary<T> { public abstract class IonizerBinary<T> {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final void _save(Object object, IonOutput out) throws IOException{ final void _save(Object object, IonOutput out) throws IOException
save((T)object, out); {
save((T) object, out);
} }
/** /**
* Save an object to ion output * Save an object to ion output
* *
* @param object object to save * @param object object to save
* @param out ion output * @param out ion output
* @throws IOException * @throws IOException
*/ */
public abstract void save(T object, IonOutput out) throws IOException; public abstract void save(T object, IonOutput out) throws IOException;
/** /**
* Load an object from ion input * Load an object from ion input
* *
* @param in ion input * @param in ion input
* @return the loaded object * @return the loaded object
*/ */
+7 -5
View File
@@ -4,20 +4,22 @@ package mightypork.utils.ion;
/** /**
* External ionizer using a data bundle - can be used if the data type cannot be * External ionizer using a data bundle - can be used if the data type cannot be
* modified to implement the proper interface * modified to implement the proper interface
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
* @param <T> * @param <T>
*/ */
public abstract class IonizerBundled<T> { public abstract class IonizerBundled<T> {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final void _save(Object object, IonDataBundle out) { final void _save(Object object, IonDataBundle out)
save((T)object, out); {
save((T) object, out);
} }
/** /**
* Save an object to data bundle * Save an object to data bundle
* *
* @param object object to save * @param object object to save
* @param out bundle to save to * @param out bundle to save to
*/ */
@@ -26,7 +28,7 @@ public abstract class IonizerBundled<T> {
/** /**
* Load an object from a bundle * Load an object from a bundle
* *
* @param in bundle to load from * @param in bundle to load from
* @return the loaded object * @return the loaded object
*/ */
+24 -18
View File
@@ -7,18 +7,18 @@ import java.io.StringWriter;
import java.util.HashMap; import java.util.HashMap;
import java.util.logging.Level; import java.util.logging.Level;
import mightypork.utils.Str;
import mightypork.utils.annotations.FactoryMethod; import mightypork.utils.annotations.FactoryMethod;
import mightypork.utils.logging.monitors.LogMonitor; import mightypork.utils.logging.monitors.LogMonitor;
import mightypork.utils.logging.monitors.LogMonitorStdout; import mightypork.utils.logging.monitors.LogMonitorStdout;
import mightypork.utils.logging.writers.ArchivingLog; import mightypork.utils.logging.writers.ArchivingLog;
import mightypork.utils.logging.writers.LogWriter; import mightypork.utils.logging.writers.LogWriter;
import mightypork.utils.logging.writers.SimpleLog; import mightypork.utils.logging.writers.SimpleLog;
import mightypork.utils.string.StringUtil;
/** /**
* A log. * A log.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class Log { public class Log {
@@ -34,7 +34,7 @@ public class Log {
/** /**
* Create a logger. If another with the name already exists, it'll be * Create a logger. If another with the name already exists, it'll be
* retrieved instead of creating a new one. * retrieved instead of creating a new one.
* *
* @param logName log name (used for filename, should be application-unique) * @param logName log name (used for filename, should be application-unique)
* @param logFile log file; old logs will be kept here too. * @param logFile log file; old logs will be kept here too.
* @param oldLogsCount number of old logs to keep, -1 infinite, 0 none. * @param oldLogsCount number of old logs to keep, -1 infinite, 0 none.
@@ -57,7 +57,7 @@ public class Log {
/** /**
* Create a logger. If another with the name already exists, it'll be * Create a logger. If another with the name already exists, it'll be
* retrieved instead of creating a new one. * retrieved instead of creating a new one.
* *
* @param logName log name (used for filename, must be application-unique) * @param logName log name (used for filename, must be application-unique)
* @param logFile log file; old logs will be kept here too. * @param logFile log file; old logs will be kept here too.
* @return the created Log instance * @return the created Log instance
@@ -82,6 +82,12 @@ public class Log {
} }
public static LogWriter getMainLogger()
{
return main;
}
public static void addMonitor(LogMonitor mon) public static void addMonitor(LogMonitor mon)
{ {
assertInited(); assertInited();
@@ -106,7 +112,7 @@ public class Log {
/** /**
* Log a message * Log a message
* *
* @param level message level * @param level message level
* @param msg message text * @param msg message text
*/ */
@@ -124,7 +130,7 @@ public class Log {
/** /**
* Log a message * Log a message
* *
* @param level message level * @param level message level
* @param msg message text * @param msg message text
* @param t thrown exception * @param t thrown exception
@@ -143,7 +149,7 @@ public class Log {
/** /**
* Log FINE message * Log FINE message
* *
* @param msg message * @param msg message
*/ */
public static void f1(String msg) public static void f1(String msg)
@@ -154,7 +160,7 @@ public class Log {
/** /**
* Log FINER message * Log FINER message
* *
* @param msg message * @param msg message
*/ */
public static void f2(String msg) public static void f2(String msg)
@@ -165,7 +171,7 @@ public class Log {
/** /**
* Log FINEST message * Log FINEST message
* *
* @param msg message * @param msg message
*/ */
public static void f3(String msg) public static void f3(String msg)
@@ -176,7 +182,7 @@ public class Log {
/** /**
* Log INFO message * Log INFO message
* *
* @param msg message * @param msg message
*/ */
public static void i(String msg) public static void i(String msg)
@@ -187,7 +193,7 @@ public class Log {
/** /**
* Log WARNING message (less severe than ERROR) * Log WARNING message (less severe than ERROR)
* *
* @param msg message * @param msg message
*/ */
public static void w(String msg) public static void w(String msg)
@@ -198,7 +204,7 @@ public class Log {
/** /**
* Log ERROR message * Log ERROR message
* *
* @param msg message * @param msg message
*/ */
public static void e(String msg) public static void e(String msg)
@@ -209,7 +215,7 @@ public class Log {
/** /**
* Log warning message with exception * Log warning message with exception
* *
* @param msg message * @param msg message
* @param thrown thrown exception * @param thrown thrown exception
*/ */
@@ -221,7 +227,7 @@ public class Log {
/** /**
* Log exception thrown as warning * Log exception thrown as warning
* *
* @param thrown thrown exception * @param thrown thrown exception
*/ */
public static void w(Throwable thrown) public static void w(Throwable thrown)
@@ -232,7 +238,7 @@ public class Log {
/** /**
* Log error message * Log error message
* *
* @param msg message * @param msg message
* @param thrown thrown exception * @param thrown thrown exception
*/ */
@@ -244,7 +250,7 @@ public class Log {
/** /**
* Log exception thrown as error * Log exception thrown as error
* *
* @param thrown thrown exception * @param thrown thrown exception
*/ */
public static void e(Throwable thrown) public static void e(Throwable thrown)
@@ -275,7 +281,7 @@ public class Log {
/** /**
* Get stack trace from throwable * Get stack trace from throwable
* *
* @param t * @param t
* @return trace * @return trace
*/ */
@@ -309,7 +315,7 @@ public class Log {
final long time_ms = (System.currentTimeMillis() - start_ms); final long time_ms = (System.currentTimeMillis() - start_ms);
final double time_s = time_ms / 1000D; final double time_s = time_ms / 1000D;
final String time = String.format("%6.2f ", time_s); final String time = String.format("%6.2f ", time_s);
final String time_blank = StringUtil.repeat(" ", time.length()); final String time_blank = Str.repeat(" ", time.length());
String prefix = "[ ? ]"; String prefix = "[ ? ]";
@@ -9,25 +9,25 @@ import java.util.Comparator;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import mightypork.utils.files.FileUtils; import mightypork.utils.Str;
import mightypork.utils.string.StringUtil; import mightypork.utils.files.FileUtil;
/** /**
* Logger that cleans directory & archives old logs * Logger that cleans directory & archives old logs
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
* @copy (c) 2014 * @copy (c) 2014
*/ */
public class ArchivingLog extends SimpleLog { public class ArchivingLog extends SimpleLog {
/** Number of old logs to keep */ /** Number of old logs to keep */
private final int logs_to_keep; private final int logs_to_keep;
/** /**
* Log * Log
* *
* @param name log name * @param name log name
* @param file log file (in log directory) * @param file log file (in log directory)
* @param oldLogCount number of old log files to keep: -1 all, 0 none. * @param oldLogCount number of old log files to keep: -1 all, 0 none.
@@ -37,11 +37,11 @@ public class ArchivingLog extends SimpleLog {
super(name, file); super(name, file);
this.logs_to_keep = oldLogCount; this.logs_to_keep = oldLogCount;
} }
/** /**
* Log, not keeping 5 last log files (default); * Log, not keeping 5 last log files (default);
* *
* @param name log name * @param name log name
* @param file log file (in log directory) * @param file log file (in log directory)
*/ */
@@ -50,67 +50,67 @@ public class ArchivingLog extends SimpleLog {
super(name, file); super(name, file);
this.logs_to_keep = 5; this.logs_to_keep = 5;
} }
@Override @Override
public void init() public void init()
{ {
cleanLoggingDirectory(); cleanLoggingDirectory();
super.init(); super.init();
} }
private void cleanLoggingDirectory() private void cleanLoggingDirectory()
{ {
if (logs_to_keep == 0) return; // overwrite if (logs_to_keep == 0) return; // overwrite
final File log_file = getFile(); final File log_file = getFile();
final File log_dir = log_file.getParentFile(); final File log_dir = log_file.getParentFile();
final String fname = FileUtils.getBasename(log_file.toString()); final String fname = FileUtil.getBasename(log_file.toString());
// move old file // move old file
for (final File f : FileUtils.listDirectory(log_dir)) { for (final File f : FileUtil.listDirectory(log_dir)) {
if (!f.isFile()) continue; if (!f.isFile()) continue;
if (f.equals(getFile())) { if (f.equals(getFile())) {
final Date d = new Date(f.lastModified()); final Date d = new Date(f.lastModified());
final String fbase = fname + '_' + (new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss")).format(d); final String fbase = fname + '_' + (new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss")).format(d);
final String suff = "." + getSuffix(); final String suff = "." + getSuffix();
String cntStr = ""; String cntStr = "";
File f2; File f2;
for (int cnt = 0; (f2 = new File(log_dir, fbase + cntStr + suff)).exists(); cntStr = "_" + (++cnt)) {} for (int cnt = 0; (f2 = new File(log_dir, fbase + cntStr + suff)).exists(); cntStr = "_" + (++cnt)) {}
if (!f.renameTo(f2)) throw new RuntimeException("Could not move log file."); if (!f.renameTo(f2)) throw new RuntimeException("Could not move log file.");
} }
} }
if (logs_to_keep == -1) return; // keep all if (logs_to_keep == -1) return; // keep all
final List<File> oldLogs = FileUtils.listDirectory(log_dir, new FileFilter() { final List<File> oldLogs = FileUtil.listDirectory(log_dir, new FileFilter() {
@Override @Override
public boolean accept(File f) public boolean accept(File f)
{ {
if (f.isDirectory()) return false; if (f.isDirectory()) return false;
if (!f.getName().endsWith(getSuffix())) return false; if (!f.getName().endsWith(getSuffix())) return false;
if (!f.getName().startsWith(fname)) return false; if (!f.getName().startsWith(fname)) return false;
return true; return true;
} }
}); });
Collections.sort(oldLogs, new Comparator<File>() { Collections.sort(oldLogs, new Comparator<File>() {
@Override @Override
public int compare(File o1, File o2) public int compare(File o1, File o2)
{ {
return o1.getName().compareTo(o2.getName()); return o1.getName().compareTo(o2.getName());
} }
}); });
// playing with fireee // playing with fireee
for (int i = 0; i < oldLogs.size() - logs_to_keep; i++) { for (int i = 0; i < oldLogs.size() - logs_to_keep; i++) {
if (!oldLogs.get(i).delete()) { if (!oldLogs.get(i).delete()) {
@@ -118,13 +118,13 @@ public class ArchivingLog extends SimpleLog {
} }
} }
} }
/** /**
* @return log filename suffix * @return log filename suffix
*/ */
private String getSuffix() private String getSuffix()
{ {
return StringUtil.fromLastChar(getFile().toString(), '.'); return Str.fromLast(getFile().toString(), '.');
} }
} }
@@ -8,7 +8,7 @@ import mightypork.utils.logging.monitors.LogMonitor;
/** /**
* Log interface * Log interface
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public interface LogWriter { public interface LogWriter {
@@ -21,7 +21,7 @@ public interface LogWriter {
/** /**
* Add log monitor * Add log monitor
* *
* @param mon monitor * @param mon monitor
*/ */
void addMonitor(LogMonitor mon); void addMonitor(LogMonitor mon);
@@ -29,7 +29,7 @@ public interface LogWriter {
/** /**
* Remove a monitor * Remove a monitor
* *
* @param removed monitor to remove * @param removed monitor to remove
*/ */
void removeMonitor(LogMonitor removed); void removeMonitor(LogMonitor removed);
@@ -37,7 +37,7 @@ public interface LogWriter {
/** /**
* Set logging level * Set logging level
* *
* @param level * @param level
*/ */
void setLevel(Level level); void setLevel(Level level);
@@ -45,7 +45,7 @@ public interface LogWriter {
/** /**
* Enable logging. * Enable logging.
* *
* @param flag do enable logging * @param flag do enable logging
*/ */
void enable(boolean flag); void enable(boolean flag);
@@ -53,7 +53,7 @@ public interface LogWriter {
/** /**
* Log a message * Log a message
* *
* @param level message level * @param level message level
* @param msg message text * @param msg message text
*/ */
@@ -62,7 +62,7 @@ public interface LogWriter {
/** /**
* Log a message * Log a message
* *
* @param level message level * @param level message level
* @param msg message text * @param msg message text
* @param t thrown exception * @param t thrown exception
@@ -17,7 +17,7 @@ import mightypork.utils.logging.monitors.LogMonitor;
/** /**
* Basic logger * Basic logger
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class SimpleLog implements LogWriter { public class SimpleLog implements LogWriter {
@@ -86,7 +86,7 @@ public class SimpleLog implements LogWriter {
/** /**
* Add log monitor * Add log monitor
* *
* @param mon monitor * @param mon monitor
*/ */
@Override @Override
@@ -98,7 +98,7 @@ public class SimpleLog implements LogWriter {
/** /**
* Remove a monitor * Remove a monitor
* *
* @param removed monitor to remove * @param removed monitor to remove
*/ */
@Override @Override
+12
View File
@@ -0,0 +1,12 @@
package mightypork.utils.math;
/**
* Horizontal align sides
*
* @author Ondřej Hruška (MightyPork)
*/
public enum AlignX
{
LEFT, CENTER, RIGHT;
}
+12
View File
@@ -0,0 +1,12 @@
package mightypork.utils.math;
/**
* Vertical align sides
*
* @author Ondřej Hruška (MightyPork)
*/
public enum AlignY
{
TOP, CENTER, BOTTOM;
}
+17 -17
View File
@@ -13,7 +13,7 @@ import mightypork.utils.math.constraints.vect.Vect;
/** /**
* Math utils * Math utils
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public final class Calc { public final class Calc {
@@ -29,7 +29,7 @@ public final class Calc {
/** /**
* Get distance from 2D line to 2D point [X,Y] * Get distance from 2D line to 2D point [X,Y]
* *
* @param lineDirVec line directional vector * @param lineDirVec line directional vector
* @param linePoint point of line * @param linePoint point of line
* @param point point coordinate * @param point point coordinate
@@ -89,7 +89,7 @@ public final class Calc {
/** /**
* Safe equals that works with nulls * Safe equals that works with nulls
* *
* @param a * @param a
* @param b * @param b
* @return are equal * @return are equal
@@ -102,7 +102,7 @@ public final class Calc {
/** /**
* Clamp integer * Clamp integer
* *
* @param number * @param number
* @param min * @param min
* @param max * @param max
@@ -116,7 +116,7 @@ public final class Calc {
/** /**
* Clamp double * Clamp double
* *
* @param number * @param number
* @param min * @param min
* @param max * @param max
@@ -136,7 +136,7 @@ public final class Calc {
/** /**
* Get number from A to B at delta time (A -> B) * Get number from A to B at delta time (A -> B)
* *
* @param from * @param from
* @param to * @param to
* @param elapsed progress ratio 0..1 * @param elapsed progress ratio 0..1
@@ -151,7 +151,7 @@ public final class Calc {
/** /**
* Get angle [degrees] from A to B at delta time (tween A to B) * Get angle [degrees] from A to B at delta time (tween A to B)
* *
* @param from * @param from
* @param to * @param to
* @param elapsed progress ratio 0..1 * @param elapsed progress ratio 0..1
@@ -166,7 +166,7 @@ public final class Calc {
/** /**
* Get angle [radians] from A to B at delta time (tween A to B) * Get angle [radians] from A to B at delta time (tween A to B)
* *
* @param from * @param from
* @param to * @param to
* @param elapsed progress ratio 0..1 * @param elapsed progress ratio 0..1
@@ -221,7 +221,7 @@ public final class Calc {
/** /**
* Split comma separated list of integers. * Split comma separated list of integers.
* *
* @param list String containing the list. * @param list String containing the list.
* @param delimiter delimiter character * @param delimiter delimiter character
* @return array of integers or null. * @return array of integers or null.
@@ -248,7 +248,7 @@ public final class Calc {
/** /**
* Pick random element from a given list. * Pick random element from a given list.
* *
* @param list list of choices * @param list list of choices
* @return picked element * @return picked element
*/ */
@@ -260,7 +260,7 @@ public final class Calc {
/** /**
* Pick random element from a given list. * Pick random element from a given list.
* *
* @param rand RNG * @param rand RNG
* @param list list of choices * @param list list of choices
* @return picked element * @return picked element
@@ -274,7 +274,7 @@ public final class Calc {
/** /**
* Take a square * Take a square
* *
* @param a value * @param a value
* @return value squared * @return value squared
*/ */
@@ -286,7 +286,7 @@ public final class Calc {
/** /**
* Take a cube * Take a cube
* *
* @param a value * @param a value
* @return value cubed * @return value cubed
*/ */
@@ -308,7 +308,7 @@ public final class Calc {
/** /**
* Make sure value is within array length. * Make sure value is within array length.
* *
* @param index tested index * @param index tested index
* @param length array length * @param length array length
* @throws IndexOutOfBoundsException if the index is not in range. * @throws IndexOutOfBoundsException if the index is not in range.
@@ -323,7 +323,7 @@ public final class Calc {
/** /**
* Get distance of two coordinates in 2D plane * Get distance of two coordinates in 2D plane
* *
* @param x1 first coordinate X * @param x1 first coordinate X
* @param y1 first coordinate y * @param y1 first coordinate y
* @param x2 second coordinate X * @param x2 second coordinate X
@@ -351,7 +351,7 @@ public final class Calc {
/** /**
* Get ordinal version of numbers (1 = 1st, 5 = 5th etc.) * Get ordinal version of numbers (1 = 1st, 5 = 5th etc.)
* *
* @param number number * @param number number
* @return ordinal, string * @return ordinal, string
*/ */
@@ -368,7 +368,7 @@ public final class Calc {
/** /**
* Format number with thousands separated. * Format number with thousands separated.
* *
* @param number number * @param number number
* @param thousandSep * @param thousandSep
* @return string * @return string
+6 -6
View File
@@ -6,7 +6,7 @@ import mightypork.utils.math.constraints.vect.Vect;
/** /**
* Polar coordinate * Polar coordinate
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class Polar { public class Polar {
@@ -22,7 +22,7 @@ public class Polar {
/** /**
* Create a polar * Create a polar
* *
* @param angle angle in RAD * @param angle angle in RAD
* @param distance distance from origin * @param distance distance from origin
*/ */
@@ -34,7 +34,7 @@ public class Polar {
/** /**
* Create a polar * Create a polar
* *
* @param angle angle * @param angle angle
* @param deg angle is in DEG * @param deg angle is in DEG
* @param distance radius * @param distance radius
@@ -102,7 +102,7 @@ public class Polar {
/** /**
* Make polar from coord * Make polar from coord
* *
* @param coord coord * @param coord coord
* @return polar * @return polar
*/ */
@@ -115,7 +115,7 @@ public class Polar {
/** /**
* Make polar from coords * Make polar from coords
* *
* @param x x coord * @param x x coord
* @param y y coord * @param y y coord
* @return polar * @return polar
@@ -131,7 +131,7 @@ public class Polar {
/** /**
* Get coord from polar * Get coord from polar
* *
* @return coord * @return coord
*/ */
public Vect toCoord() public Vect toCoord()
+14 -14
View File
@@ -6,7 +6,7 @@ import java.util.Random;
/** /**
* Numeric range, able to generate random numbers and give min/max values. * Numeric range, able to generate random numbers and give min/max values.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class Range { public class Range {
@@ -30,7 +30,7 @@ public class Range {
/** /**
* Create new range * Create new range
* *
* @param min min number * @param min min number
* @param max max number * @param max max number
*/ */
@@ -44,7 +44,7 @@ public class Range {
/** /**
* Create new range * Create new range
* *
* @param minmax min = max number * @param minmax min = max number
*/ */
public Range(double minmax) public Range(double minmax)
@@ -116,7 +116,7 @@ public class Range {
/** /**
* Get random integer from range * Get random integer from range
* *
* @return random int * @return random int
*/ */
public int randInt() public int randInt()
@@ -127,7 +127,7 @@ public class Range {
/** /**
* Get random double from this range * Get random double from this range
* *
* @return random double * @return random double
*/ */
public double randDouble() public double randDouble()
@@ -138,7 +138,7 @@ public class Range {
/** /**
* Get random integer from range * Get random integer from range
* *
* @param rand RNG * @param rand RNG
* @return random int * @return random int
*/ */
@@ -150,7 +150,7 @@ public class Range {
/** /**
* Get random double from this range * Get random double from this range
* *
* @param rand RNG * @param rand RNG
* @return random double * @return random double
*/ */
@@ -162,7 +162,7 @@ public class Range {
/** /**
* Get min * Get min
* *
* @return min number * @return min number
*/ */
public double getMin() public double getMin()
@@ -173,7 +173,7 @@ public class Range {
/** /**
* Get max * Get max
* *
* @return max number * @return max number
*/ */
public double getMax() public double getMax()
@@ -184,7 +184,7 @@ public class Range {
/** /**
* Set min * Set min
* *
* @param min min value * @param min min value
*/ */
public void setMin(double min) public void setMin(double min)
@@ -196,7 +196,7 @@ public class Range {
/** /**
* Set max * Set max
* *
* @param max max value * @param max max value
*/ */
public void setMax(double max) public void setMax(double max)
@@ -208,7 +208,7 @@ public class Range {
/** /**
* Get identical copy * Get identical copy
* *
* @return copy * @return copy
*/ */
public Range copy() public Range copy()
@@ -219,7 +219,7 @@ public class Range {
/** /**
* Set to value of other range * Set to value of other range
* *
* @param other copied range * @param other copied range
*/ */
public void setTo(Range other) public void setTo(Range other)
@@ -233,7 +233,7 @@ public class Range {
/** /**
* Set to min-max values * Set to min-max values
* *
* @param min min value * @param min min value
* @param max max value * @param max max value
*/ */
+3 -3
View File
@@ -9,7 +9,7 @@ import mightypork.utils.math.constraints.vect.VectConst;
/** /**
* Very simple integer coordinate * Very simple integer coordinate
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class Coord { public class Coord {
@@ -68,7 +68,7 @@ public class Coord {
/** /**
* Add other coord in a copy * Add other coord in a copy
* *
* @param added * @param added
* @return changed copy * @return changed copy
*/ */
@@ -105,7 +105,7 @@ public class Coord {
/** /**
* Check if coord is in a range (inclusive) * Check if coord is in a range (inclusive)
* *
* @param x0 range min x * @param x0 range min x
* @param y0 range min y * @param y0 range min y
* @param x1 range max x * @param x1 range max x
+2 -2
View File
@@ -4,7 +4,7 @@ package mightypork.utils.math.algo;
/** /**
* Path step.<br> * Path step.<br>
* Must be binary in order to be saveable in lists. * Must be binary in order to be saveable in lists.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class Move { public class Move {
@@ -32,7 +32,7 @@ public class Move {
private final byte x; private final byte x;
private final byte y; private final byte y;
public Move(int x, int y) public Move(int x, int y)
{ {
+17 -17
View File
@@ -11,7 +11,7 @@ import mightypork.utils.math.Calc;
/** /**
* Move lists, bit masks and other utilities * Move lists, bit masks and other utilities
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class Moves { public class Moves {
@@ -42,31 +42,31 @@ public class Moves {
public static final Move SW = Move.make(-1, 1); public static final Move SW = Move.make(-1, 1);
public static final Move W = Move.make(-1, 0); public static final Move W = Move.make(-1, 0);
//@formatter:off //@formatter:off
/** All sides, in the order of bits. */ /** All sides, in the order of bits. */
public final static List<Move> ALL_SIDES = Collections.unmodifiableList(Arrays.asList( public final static List<Move> ALL_SIDES = Collections.unmodifiableList(Arrays.asList(
NW, NW,
N, N,
NE, NE,
E, E,
SE, SE,
S, S,
SW, SW,
W W
)); ));
public final static List<Move> CARDINAL_SIDES = Collections.unmodifiableList(Arrays.asList( public final static List<Move> CARDINAL_SIDES = Collections.unmodifiableList(Arrays.asList(
N, N,
E, E,
S, S,
W W
)); ));
//@formatter:on //@formatter:on
/** /**
* Get element from all sides * Get element from all sides
* *
* @param i side index * @param i side index
* @return the side coord * @return the side coord
*/ */
@@ -23,7 +23,7 @@ public abstract class FloodFill {
/** /**
* Get the max distance filled form start point. Use -1 for unlimited range. * Get the max distance filled form start point. Use -1 for unlimited range.
* *
* @return max distance * @return max distance
*/ */
public abstract double getMaxDistance(); public abstract double getMaxDistance();
@@ -37,7 +37,7 @@ public abstract class FloodFill {
/** /**
* Fill an area * Fill an area
* *
* @param start start point * @param start start point
* @param foundNodes collection to put filled coords in * @param foundNodes collection to put filled coords in
* @return true if fill was successful; false if max range was reached. * @return true if fill was successful; false if max range was reached.
@@ -8,7 +8,7 @@ public abstract class Heuristic {
/** /**
* Get tile cost (estimate of how many tiles remain to the target) * Get tile cost (estimate of how many tiles remain to the target)
* *
* @param pos current pos * @param pos current pos
* @param target target pos * @param target target pos
* @return estimated number of tiles * @return estimated number of tiles
@@ -15,7 +15,7 @@ import mightypork.utils.math.algo.pathfinding.heuristics.ManhattanHeuristic;
/** /**
* A* pathfinder * A* pathfinder
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public abstract class PathFinder { public abstract class PathFinder {
@@ -100,7 +100,6 @@ public abstract class PathFinder {
a.h_cost = (int) (heuristic.getCost(a.pos, end) * getMinCost()); a.h_cost = (int) (heuristic.getCost(a.pos, end) * getMinCost());
a.parent = current; a.parent = current;
if (!closed.contains(a)) { if (!closed.contains(a)) {
if (open.contains(a)) { if (open.contains(a)) {
@@ -235,7 +234,7 @@ public abstract class PathFinder {
/** /**
* Cost of walking onto a tile. It's useful to use ie. 10 for basic step. * Cost of walking onto a tile. It's useful to use ie. 10 for basic step.
* *
* @param from last tile * @param from last tile
* @param to current tile * @param to current tile
* @return cost * @return cost
@@ -10,7 +10,7 @@ import mightypork.utils.math.algo.Move;
/** /**
* Pathfinder proxy. Can be used to override individual methods but keep the * Pathfinder proxy. Can be used to override individual methods but keep the
* rest as is. * rest as is.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class PathFinderProxy extends PathFinder { public class PathFinderProxy extends PathFinder {
+4 -4
View File
@@ -3,14 +3,14 @@ package mightypork.utils.math.angles;
/** /**
* Common angles functionality * Common angles functionality
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
class Angles { class Angles {
/** /**
* Delta of two angles (positive or negative - positive is CCW) * Delta of two angles (positive or negative - positive is CCW)
* *
* @param alpha first angle * @param alpha first angle
* @param beta second angle * @param beta second angle
* @param fullAngle value of full angle * @param fullAngle value of full angle
@@ -29,7 +29,7 @@ class Angles {
/** /**
* Difference of two angles (same as delta, but always positive) * Difference of two angles (same as delta, but always positive)
* *
* @param alpha first angle * @param alpha first angle
* @param beta second angle * @param beta second angle
* @param fullAngle value of full angle * @param fullAngle value of full angle
@@ -43,7 +43,7 @@ class Angles {
/** /**
* Normalize angle to 0-full range * Normalize angle to 0-full range
* *
* @param angle angle * @param angle angle
* @param fullAngle full angle * @param fullAngle full angle
* @return angle normalized * @return angle normalized
+12 -12
View File
@@ -3,7 +3,7 @@ package mightypork.utils.math.angles;
/** /**
* Angle calculations for degrees. * Angle calculations for degrees.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class Deg { public class Deg {
@@ -22,7 +22,7 @@ public class Deg {
/** /**
* Subtract two angles alpha - beta * Subtract two angles alpha - beta
* *
* @param alpha first angle * @param alpha first angle
* @param beta second angle * @param beta second angle
* @return (alpha - beta) in degrees * @return (alpha - beta) in degrees
@@ -35,7 +35,7 @@ public class Deg {
/** /**
* Difference of two angles (absolute value of delta) * Difference of two angles (absolute value of delta)
* *
* @param alpha first angle * @param alpha first angle
* @param beta second angle * @param beta second angle
* @return difference in radians * @return difference in radians
@@ -48,7 +48,7 @@ public class Deg {
/** /**
* Cosinus in degrees * Cosinus in degrees
* *
* @param deg angle in degrees * @param deg angle in degrees
* @return cosinus * @return cosinus
*/ */
@@ -60,7 +60,7 @@ public class Deg {
/** /**
* Sinus in degrees * Sinus in degrees
* *
* @param deg angle in degrees * @param deg angle in degrees
* @return sinus * @return sinus
*/ */
@@ -72,7 +72,7 @@ public class Deg {
/** /**
* Tangents in degrees * Tangents in degrees
* *
* @param deg angle in degrees * @param deg angle in degrees
* @return tangents * @return tangents
*/ */
@@ -84,7 +84,7 @@ public class Deg {
/** /**
* Angle normalized to 0-360 range * Angle normalized to 0-360 range
* *
* @param angle angle to normalize * @param angle angle to normalize
* @return normalized angle * @return normalized angle
*/ */
@@ -96,7 +96,7 @@ public class Deg {
/** /**
* Convert to radians * Convert to radians
* *
* @param deg degrees * @param deg degrees
* @return radians * @return radians
*/ */
@@ -108,7 +108,7 @@ public class Deg {
/** /**
* Round angle to 0,45,90,135... * Round angle to 0,45,90,135...
* *
* @param deg angle in deg. to round * @param deg angle in deg. to round
* @param increment rounding increment (45 - round to 0,45,90...) * @param increment rounding increment (45 - round to 0,45,90...)
* @return rounded * @return rounded
@@ -127,7 +127,7 @@ public class Deg {
/** /**
* Round angle to 0,15,30,45,60,75,90... * Round angle to 0,15,30,45,60,75,90...
* *
* @param deg angle in deg to round * @param deg angle in deg to round
* @return rounded * @return rounded
*/ */
@@ -139,7 +139,7 @@ public class Deg {
/** /**
* Round angle to 0,45,90,135... * Round angle to 0,45,90,135...
* *
* @param deg angle in deg. to round * @param deg angle in deg. to round
* @return rounded * @return rounded
*/ */
@@ -151,7 +151,7 @@ public class Deg {
/** /**
* Round angle to 0,90,180,270 * Round angle to 0,90,180,270
* *
* @param deg angle in deg. to round * @param deg angle in deg. to round
* @return rounded * @return rounded
*/ */
+8 -8
View File
@@ -3,7 +3,7 @@ package mightypork.utils.math.angles;
/** /**
* Angle calculations for radians. * Angle calculations for radians.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class Rad { public class Rad {
@@ -22,7 +22,7 @@ public class Rad {
/** /**
* Subtract two angles alpha - beta * Subtract two angles alpha - beta
* *
* @param alpha first angle * @param alpha first angle
* @param beta second angle * @param beta second angle
* @return (alpha - beta) in radians * @return (alpha - beta) in radians
@@ -35,7 +35,7 @@ public class Rad {
/** /**
* Difference of two angles (absolute value of delta) * Difference of two angles (absolute value of delta)
* *
* @param alpha first angle * @param alpha first angle
* @param beta second angle * @param beta second angle
* @return difference in radians * @return difference in radians
@@ -48,7 +48,7 @@ public class Rad {
/** /**
* Cos * Cos
* *
* @param rad angle in rads * @param rad angle in rads
* @return cos * @return cos
*/ */
@@ -60,7 +60,7 @@ public class Rad {
/** /**
* Sin * Sin
* *
* @param rad angle in rads * @param rad angle in rads
* @return sin * @return sin
*/ */
@@ -72,7 +72,7 @@ public class Rad {
/** /**
* Tan * Tan
* *
* @param rad angle in rads * @param rad angle in rads
* @return tan * @return tan
*/ */
@@ -84,7 +84,7 @@ public class Rad {
/** /**
* Angle normalized to 0-2*PI range * Angle normalized to 0-2*PI range
* *
* @param angle angle to normalize * @param angle angle to normalize
* @return normalized angle * @return normalized angle
*/ */
@@ -96,7 +96,7 @@ public class Rad {
/** /**
* Convert to degrees * Convert to degrees
* *
* @param rad radians * @param rad radians
* @return degrees * @return degrees
*/ */
@@ -1,7 +1,7 @@
package mightypork.utils.math.animation; package mightypork.utils.math.animation;
import mightypork.utils.annotations.DefaultImpl; import mightypork.utils.annotations.Stub;
import mightypork.utils.interfaces.Pauseable; import mightypork.utils.interfaces.Pauseable;
import mightypork.utils.interfaces.Updateable; import mightypork.utils.interfaces.Updateable;
import mightypork.utils.math.Calc; import mightypork.utils.math.Calc;
@@ -120,7 +120,7 @@ public abstract class Animator implements NumBound, Updateable, Pauseable {
} }
@DefaultImpl @Stub
protected abstract void nextCycle(NumAnimated anim); protected abstract void nextCycle(NumAnimated anim);
@@ -3,7 +3,7 @@ package mightypork.utils.math.animation;
/** /**
* Animator that upon reaching max, animates back down and then up again * Animator that upon reaching max, animates back down and then up again
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class AnimatorBounce extends Animator { public class AnimatorBounce extends Animator {
@@ -4,7 +4,7 @@ package mightypork.utils.math.animation;
/** /**
* Animator that upon reaching top, jumps straight to zero and continues another * Animator that upon reaching top, jumps straight to zero and continues another
* cycle. * cycle.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class AnimatorRewind extends Animator { public class AnimatorRewind extends Animator {
@@ -3,14 +3,14 @@ package mightypork.utils.math.animation;
/** /**
* EasingFunction function. * EasingFunction function.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public abstract class Easing { public abstract class Easing {
/** /**
* Get value at time t. * Get value at time t.
* *
* @param t time parameter (t = 1..1) * @param t time parameter (t = 1..1)
* @return value at given t (0..1, can exceed if needed) * @return value at given t (0..1, can exceed if needed)
*/ */
@@ -19,7 +19,7 @@ public abstract class Easing {
/** /**
* Reverse an easing (factory method) * Reverse an easing (factory method)
* *
* @param original original easing * @param original original easing
* @return reversed easing * @return reversed easing
*/ */
@@ -31,7 +31,7 @@ public abstract class Easing {
/** /**
* Combine two easings (factory method) * Combine two easings (factory method)
* *
* @param in initial easing * @param in initial easing
* @param out terminal easing * @param out terminal easing
* @return product * @return product
@@ -45,7 +45,7 @@ public abstract class Easing {
/** /**
* Create "bilinear" easing - compose of straight and reverse. (factory * Create "bilinear" easing - compose of straight and reverse. (factory
* method) * method)
* *
* @param in initial easing * @param in initial easing
* @return product * @return product
*/ */
@@ -56,7 +56,7 @@ public abstract class Easing {
/** /**
* Reverse EasingFunction * Reverse EasingFunction
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
private static class Reverse extends Easing { private static class Reverse extends Easing {
@@ -82,7 +82,7 @@ public abstract class Easing {
/** /**
* Composite EasingFunction (0-0.5 EasingFunction A, 0.5-1 EasingFunction B) * Composite EasingFunction (0-0.5 EasingFunction A, 0.5-1 EasingFunction B)
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
private static class Composite extends Easing { private static class Composite extends Easing {
@@ -93,7 +93,7 @@ public abstract class Easing {
/** /**
* Create a composite EasingFunction * Create a composite EasingFunction
* *
* @param in initial EasingFunction * @param in initial EasingFunction
* @param out terminal EasingFunction * @param out terminal EasingFunction
*/ */
@@ -11,7 +11,7 @@ import mightypork.utils.math.constraints.num.var.NumMutable;
* Double which supports delta timing.<br> * Double which supports delta timing.<br>
* When both in and out easings are set differently, then they'll be used for * When both in and out easings are set differently, then they'll be used for
* fade-in and fade-out respectively. Otherwise both use the same. * fade-in and fade-out respectively. Otherwise both use the same.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class NumAnimated extends NumMutable implements Updateable, Pauseable { public class NumAnimated extends NumMutable implements Updateable, Pauseable {
@@ -42,7 +42,7 @@ public class NumAnimated extends NumMutable implements Updateable, Pauseable {
/** /**
* With linear easing * With linear easing
* *
* @param value initial value * @param value initial value
*/ */
public NumAnimated(double value) public NumAnimated(double value)
@@ -53,7 +53,7 @@ public class NumAnimated extends NumMutable implements Updateable, Pauseable {
/** /**
* Create animator with easing * Create animator with easing
* *
* @param value initial value * @param value initial value
* @param easing easing function * @param easing easing function
*/ */
@@ -66,7 +66,7 @@ public class NumAnimated extends NumMutable implements Updateable, Pauseable {
/** /**
* Create animator with easing * Create animator with easing
* *
* @param value initial value * @param value initial value
* @param easingIn easing function (fade in) * @param easingIn easing function (fade in)
* @param easingOut easing function (fade out) * @param easingOut easing function (fade out)
@@ -80,7 +80,7 @@ public class NumAnimated extends NumMutable implements Updateable, Pauseable {
/** /**
* Create animator with easing * Create animator with easing
* *
* @param value initial value * @param value initial value
* @param easing easing function * @param easing easing function
* @param defaultDuration default fade duration * @param defaultDuration default fade duration
@@ -95,7 +95,7 @@ public class NumAnimated extends NumMutable implements Updateable, Pauseable {
/** /**
* Create animator with easing * Create animator with easing
* *
* @param value initial value * @param value initial value
* @param easingIn easing function (fade in) * @param easingIn easing function (fade in)
* @param easingOut easing function (fade out) * @param easingOut easing function (fade out)
@@ -111,7 +111,7 @@ public class NumAnimated extends NumMutable implements Updateable, Pauseable {
/** /**
* Create as copy of another * Create as copy of another
* *
* @param other other animator * @param other other animator
*/ */
public NumAnimated(NumAnimated other) public NumAnimated(NumAnimated other)
@@ -143,7 +143,7 @@ public class NumAnimated extends NumMutable implements Updateable, Pauseable {
/** /**
* Get start value * Get start value
* *
* @return number * @return number
*/ */
public double getStart() public double getStart()
@@ -154,7 +154,7 @@ public class NumAnimated extends NumMutable implements Updateable, Pauseable {
/** /**
* Get end value * Get end value
* *
* @return number * @return number
*/ */
public double getEnd() public double getEnd()
@@ -201,7 +201,7 @@ public class NumAnimated extends NumMutable implements Updateable, Pauseable {
/** /**
* Get value at delta time * Get value at delta time
* *
* @return the value * @return the value
*/ */
@Override @Override
@@ -214,7 +214,7 @@ public class NumAnimated extends NumMutable implements Updateable, Pauseable {
/** /**
* Get how much of the animation is already finished * Get how much of the animation is already finished
* *
* @return completion ratio (0 to 1) * @return completion ratio (0 to 1)
*/ */
public double getProgress() public double getProgress()
@@ -240,7 +240,7 @@ public class NumAnimated extends NumMutable implements Updateable, Pauseable {
/** /**
* Get if animation is finished * Get if animation is finished
* *
* @return is finished * @return is finished
*/ */
public boolean isFinished() public boolean isFinished()
@@ -251,7 +251,7 @@ public class NumAnimated extends NumMutable implements Updateable, Pauseable {
/** /**
* Set to a value (without animation) * Set to a value (without animation)
* *
* @param value * @param value
*/ */
@Override @Override
@@ -265,7 +265,7 @@ public class NumAnimated extends NumMutable implements Updateable, Pauseable {
/** /**
* Copy other * Copy other
* *
* @param other * @param other
*/ */
public void setTo(NumAnimated other) public void setTo(NumAnimated other)
@@ -284,7 +284,7 @@ public class NumAnimated extends NumMutable implements Updateable, Pauseable {
/** /**
* Animate between two states, start from current value (if it's in between) * Animate between two states, start from current value (if it's in between)
* *
* @param from start value * @param from start value
* @param to target state * @param to target state
* @param time animation time (secs) * @param time animation time (secs)
@@ -308,7 +308,7 @@ public class NumAnimated extends NumMutable implements Updateable, Pauseable {
/** /**
* Get progress already elapsed based on current value.<br> * Get progress already elapsed based on current value.<br>
* Used to resume animation from current point in fading etc. * Used to resume animation from current point in fading etc.
* *
* @param value current value * @param value current value
* @return progress ratio 0-1 * @return progress ratio 0-1
*/ */
@@ -330,7 +330,7 @@ public class NumAnimated extends NumMutable implements Updateable, Pauseable {
/** /**
* Animate to a value from current value * Animate to a value from current value
* *
* @param to target state * @param to target state
* @param duration animation duration (speeds) * @param duration animation duration (speeds)
*/ */
@@ -345,7 +345,7 @@ public class NumAnimated extends NumMutable implements Updateable, Pauseable {
/** /**
* Animate 0 to 1 * Animate 0 to 1
* *
* @param time animation time (secs) * @param time animation time (secs)
*/ */
public void fadeIn(double time) public void fadeIn(double time)
@@ -357,7 +357,7 @@ public class NumAnimated extends NumMutable implements Updateable, Pauseable {
/** /**
* Animate 1 to 0 * Animate 1 to 0
* *
* @param time animation time (secs) * @param time animation time (secs)
*/ */
public void fadeOut(double time) public void fadeOut(double time)
@@ -389,7 +389,7 @@ public class NumAnimated extends NumMutable implements Updateable, Pauseable {
/** /**
* Make a copy * Make a copy
* *
* @return copy * @return copy
*/ */
@Override @Override
@@ -7,7 +7,7 @@ import mightypork.utils.math.angles.Deg;
/** /**
* Degree animator * Degree animator
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class NumAnimatedDeg extends NumAnimated { public class NumAnimatedDeg extends NumAnimated {
@@ -7,7 +7,7 @@ import mightypork.utils.math.angles.Rad;
/** /**
* Radians animator * Radians animator
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class NumAnimatedRad extends NumAnimated { public class NumAnimatedRad extends NumAnimated {
@@ -10,7 +10,7 @@ import mightypork.utils.math.constraints.vect.var.VectMutable;
/** /**
* 3D coordinated with support for transitions, mutable. * 3D coordinated with support for transitions, mutable.
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class VectAnimated extends VectMutable implements Pauseable, Updateable { public class VectAnimated extends VectMutable implements Pauseable, Updateable {
@@ -22,7 +22,7 @@ public class VectAnimated extends VectMutable implements Pauseable, Updateable {
/** /**
* Create an animated vector; This way different easing / settings can be * Create an animated vector; This way different easing / settings can be
* specified for each coordinate. * specified for each coordinate.
* *
* @param x x animator * @param x x animator
* @param y y animator * @param y y animator
* @param z z animator * @param z z animator
@@ -37,7 +37,7 @@ public class VectAnimated extends VectMutable implements Pauseable, Updateable {
/** /**
* Create an animated vector * Create an animated vector
* *
* @param start initial positioon * @param start initial positioon
* @param easing animation easing * @param easing animation easing
*/ */
@@ -149,7 +149,7 @@ public class VectAnimated extends VectMutable implements Pauseable, Updateable {
/** /**
* Set default animation duration (when changed without using animate()) * Set default animation duration (when changed without using animate())
* *
* @param defaultDuration default duration (seconds) * @param defaultDuration default duration (seconds)
*/ */
public void setDefaultDuration(double defaultDuration) public void setDefaultDuration(double defaultDuration)
@@ -230,7 +230,7 @@ public class VectAnimated extends VectMutable implements Pauseable, Updateable {
/** /**
* Set easing for all three coordinates * Set easing for all three coordinates
* *
* @param easing * @param easing
*/ */
public void setEasing(Easing easing) public void setEasing(Easing easing)
@@ -244,7 +244,7 @@ public class VectAnimated extends VectMutable implements Pauseable, Updateable {
/** /**
* Create an animated vector; This way different easing / settings can be * Create an animated vector; This way different easing / settings can be
* specified for each coordinate. * specified for each coordinate.
* *
* @param x x animator * @param x x animator
* @param y y animator * @param y y animator
* @param z z animator * @param z z animator
@@ -259,7 +259,7 @@ public class VectAnimated extends VectMutable implements Pauseable, Updateable {
/** /**
* Create an animated vector * Create an animated vector
* *
* @param start initial positioon * @param start initial positioon
* @param easing animation easing * @param easing animation easing
* @return animated mutable vector * @return animated mutable vector
@@ -273,7 +273,7 @@ public class VectAnimated extends VectMutable implements Pauseable, Updateable {
/** /**
* Create an animated vector, initialized at 0,0,0 * Create an animated vector, initialized at 0,0,0
* *
* @param easing animation easing * @param easing animation easing
* @return animated mutable vector * @return animated mutable vector
*/ */
+37 -4
View File
@@ -12,7 +12,7 @@ import mightypork.utils.math.constraints.num.Num;
/** /**
* Color.<br> * Color.<br>
* All values are 0-1 * All values are 0-1
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public abstract class Color { public abstract class Color {
@@ -180,7 +180,7 @@ public abstract class Color {
* multiplier value should not exceed the range 0..1, otherwise it will be * multiplier value should not exceed the range 0..1, otherwise it will be
* clamped to it. * clamped to it.
* </p> * </p>
* *
* @param alpha alpha multiplier * @param alpha alpha multiplier
*/ */
public static void pushAlpha(Num alpha) public static void pushAlpha(Num alpha)
@@ -196,7 +196,7 @@ public abstract class Color {
/** /**
* Remove a pushed alpha multiplier from the stack. If there's no remaining * Remove a pushed alpha multiplier from the stack. If there's no remaining
* multiplier on the stack, an exception is raised. * multiplier on the stack, an exception is raised.
* *
* @throws EmptyStackException if the stack is empty * @throws EmptyStackException if the stack is empty
*/ */
public static void popAlpha() public static void popAlpha()
@@ -216,7 +216,7 @@ public abstract class Color {
/** /**
* Enable alpha stack. When disabled, pushAlpha() and popAlpha() have no * Enable alpha stack. When disabled, pushAlpha() and popAlpha() have no
* effect. * effect.
* *
* @param yes * @param yes
*/ */
public static void enableAlphaStack(boolean yes) public static void enableAlphaStack(boolean yes)
@@ -244,4 +244,37 @@ public abstract class Color {
{ {
return new ColorAlphaAdjuster(this, multiplier); return new ColorAlphaAdjuster(this, multiplier);
} }
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(b());
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(g());
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(r());
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(a());
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj) return true;
if (obj == null) return false;
if (!(obj instanceof Color)) return false;
final Color other = (Color) obj;
if (Double.doubleToLongBits(b()) != Double.doubleToLongBits(other.b())) return false;
if (Double.doubleToLongBits(g()) != Double.doubleToLongBits(other.g())) return false;
if (Double.doubleToLongBits(r()) != Double.doubleToLongBits(other.r())) return false;
if (Double.doubleToLongBits(a()) != Double.doubleToLongBits(other.a())) return false;
return true;
}
} }
+29
View File
@@ -0,0 +1,29 @@
package mightypork.utils.math.color;
/**
* Linear gradient (each corner can have different color)
*
* @author MightyPork
*/
public class Grad {
public final Color leftTop, rightTop, rightBottom, leftBottom;
/**
* Create a gradient
*
* @param leftTop left top color
* @param rightTop right top color
* @param rightBottom right bottom color
* @param leftBottom left bottom color
*/
public Grad(Color leftTop, Color rightTop, Color rightBottom, Color leftBottom)
{
this.leftTop = leftTop;
this.rightTop = rightTop;
this.rightBottom = rightBottom;
this.leftBottom = leftBottom;
}
}
@@ -0,0 +1,15 @@
package mightypork.utils.math.color;
/**
* Linear horizontal gradient
*
* @author MightyPork
*/
public class GradH extends Grad {
public GradH(Color left, Color right)
{
super(left, right, right, left);
}
}
@@ -0,0 +1,15 @@
package mightypork.utils.math.color;
/**
* Linear vertical gradient
*
* @author MightyPork
*/
public class GradV extends Grad {
public GradV(Color top, Color bottom)
{
super(top, top, bottom, bottom);
}
}
+1 -1
View File
@@ -6,7 +6,7 @@ import mightypork.utils.math.color.Color;
/** /**
* CGA palette * CGA palette
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public interface CGA { public interface CGA {
@@ -6,7 +6,7 @@ import mightypork.utils.math.color.Color;
/** /**
* COMMODORE palette * COMMODORE palette
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public interface CMDR { public interface CMDR {
@@ -6,7 +6,7 @@ import mightypork.utils.math.color.Color;
/** /**
* PAL16 palette via http://androidarts.com/palette/16pal.htm * PAL16 palette via http://androidarts.com/palette/16pal.htm
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public interface PAL16 { public interface PAL16 {
+1 -2
View File
@@ -6,7 +6,7 @@ import mightypork.utils.math.color.Color;
/** /**
* Basic RGB palette * Basic RGB palette
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public class RGB { public class RGB {
@@ -21,7 +21,6 @@ public class RGB {
public static final Color BLACK_80 = Color.rgba(0, 0, 0, 0.8); public static final Color BLACK_80 = Color.rgba(0, 0, 0, 0.8);
public static final Color BLACK_90 = Color.rgba(0, 0, 0, 0.9); public static final Color BLACK_90 = Color.rgba(0, 0, 0, 0.9);
public static final Color WHITE = Color.fromHex(0xFFFFFF); public static final Color WHITE = Color.fromHex(0xFFFFFF);
public static final Color BLACK = Color.fromHex(0x000000); public static final Color BLACK = Color.fromHex(0x000000);
public static final Color GRAY_DARK = Color.fromHex(0x808080); public static final Color GRAY_DARK = Color.fromHex(0x808080);
+1 -1
View File
@@ -6,7 +6,7 @@ import mightypork.utils.math.color.Color;
/** /**
* ZX Spectrum palette * ZX Spectrum palette
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
*/ */
public interface ZX { public interface ZX {
@@ -6,7 +6,7 @@ import mightypork.utils.interfaces.Pollable;
/** /**
* Constraint that is cached * Constraint that is cached
* *
* @author Ondřej Hruška (MightyPork) * @author Ondřej Hruška (MightyPork)
* @param <C> constraint type * @param <C> constraint type
*/ */
@@ -26,7 +26,7 @@ public interface CachedConstraint<C> extends Pollable {
/** /**
* Enable caching & digest caching * Enable caching & digest caching
* *
* @param yes enable caching * @param yes enable caching
*/ */
void enableCaching(boolean yes); void enableCaching(boolean yes);

Some files were not shown because too many files have changed in this diff Show More