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

This commit is contained in:
ondra
2014-04-16 14:32:56 +02:00
parent e58156b7ee
commit 6843e746bc
208 changed files with 656 additions and 629 deletions
+334
View File
@@ -0,0 +1,334 @@
package mightypork.util.objects;
import mightypork.util.logging.Log;
import mightypork.util.math.Calc;
import mightypork.util.math.Range;
import mightypork.util.math.constraints.vect.Vect;
import mightypork.util.math.constraints.vect.VectConst;
/**
* Utility for converting Object to data types; Can also convert strings to data
* types.
*
* @author MightyPork
*/
public class Convert {
/**
* Get INTEGER
*
* @param o object
* @param def default value
* @return integer
*/
public static int toInteger(Object o, Integer def)
{
try {
if (o == null) return def;
if (o instanceof Number) return ((Number) o).intValue();
if (o instanceof String) return (int) Math.round(Double.parseDouble((String) o));
if (o instanceof Range) return ((Range) o).randInt();
if (o instanceof Boolean) return ((Boolean) o) ? 1 : 0;
} catch (final NumberFormatException e) {}
return def;
}
/**
* Get DOUBLE
*
* @param o object
* @param def default value
* @return double
*/
public static double toDouble(Object o, Double def)
{
try {
if (o == null) return def;
if (o instanceof Number) return ((Number) o).doubleValue();
if (o instanceof String) return Double.parseDouble((String) o);
if (o instanceof Range) return ((Range) o).randDouble();
if (o instanceof Boolean) return ((Boolean) o) ? 1 : 0;
} catch (final NumberFormatException e) {}
return def;
}
/**
* Get FLOAT
*
* @param o object
* @param def default value
* @return float
*/
public static double toFloat(Object o, Float def)
{
try {
if (o == null) return def;
if (o instanceof Number) return ((Number) o).floatValue();
} catch (final NumberFormatException e) {}
return def;
}
/**
* Get BOOLEAN
*
* @param o object
* @param def default value
* @return boolean
*/
public static boolean toBoolean(Object o, Boolean def)
{
if (o == null) return def;
if (o instanceof Boolean) return ((Boolean) o).booleanValue();
if (o instanceof Number) return ((Number) o).intValue() != 0;
if (o instanceof String) {
final String s = ((String) o).trim().toLowerCase();
if (s.equals("0")) return false;
if (s.equals("1")) return true;
try {
final double n = Double.parseDouble(s);
return n != 0;
} catch (final NumberFormatException e) {}
if (s.equals("true")) return true;
if (s.equals("yes")) return true;
if (s.equals("y")) return true;
if (s.equals("a")) return true;
if (s.equals("enabled")) return true;
if (s.equals("false")) return false;
if (s.equals("no")) return false;
if (s.equals("n")) return false;
if (s.equals("disabled")) return true;
}
return def;
}
/**
* Get STRING
*
* @param o object
* @param def default value
* @return String
*/
public static String toString(Object o, String def)
{
if (o == null) return def;
if (o instanceof String) return ((String) o);
if (o instanceof Float) return Calc.toString((float) o);
if (o instanceof Double) return Calc.toString((double) o);
if (o instanceof Vect) {
final Vect c = (Vect) o;
return String.format("(%f|%f|%f)", c.x(), c.y(), c.z());
}
if (o instanceof Range) {
final Range c = (Range) o;
return String.format("{%f|%f}", c.getMin(), c.getMax());
}
if (o instanceof Class<?>) {
return Log.str(o);
}
return o.toString();
}
/**
* Get a vector
*
* @param o object
* @param def default value
* @return vector
*/
public static VectConst toVect(Object o, Vect def)
{
try {
if (o == null) return def.freeze();
if (o instanceof Vect) return ((Vect) o).freeze();
if (o instanceof String) {
String s = ((String) o).trim();
// drop whitespace
s = s.replaceAll("\\s", "");
// drop brackets
s = s.replaceAll("[\\(\\[\\{\\)\\]\\}]", "");
// norm separators
s = s.replaceAll("[:;]", "|");
// norm floating point
s = s.replaceAll("[,]", ".");
final String[] parts = s.split("[|]");
if (parts.length >= 2) {
final double x = Double.parseDouble(parts[0].trim());
final double y = Double.parseDouble(parts[1].trim());
if (parts.length == 2) {
return Vect.make(x, y);
}
final double z = Double.parseDouble(parts[2].trim());
return Vect.make(x, y, z);
}
}
} catch (final NumberFormatException | ArrayIndexOutOfBoundsException e) {
// ignore
}
return def.freeze();
}
/**
* Get RANGE
*
* @param o object
* @param def default value
* @return AiCoord
*/
public static Range toRange(Object o, Range def)
{
try {
if (o == null) return def;
if (o instanceof Range) return (Range) o;
if (o instanceof Number) return new Range(((Number) o).doubleValue(), ((Number) o).doubleValue());
if (o instanceof String) {
String s = ((String) o).trim();
// drop whitespace
s = s.replaceAll("\\s", "");
// drop brackets
s = s.replaceAll("[\\(\\[\\{\\)\\]\\}]", "");
// norm separators
s = s.replaceAll("[:;]", "|").replace("..", "|");
// norm floating point
s = s.replaceAll("[,]", ".");
// dash to pipe, if not a minus sign
s = s.replaceAll("([0-9])\\s?[\\-]", "$1|");
final String[] parts = s.split("[|]");
if (parts.length >= 1) {
final double low = Double.parseDouble(parts[0].trim());
if (parts.length == 2) {
final double high = Double.parseDouble(parts[1].trim());
return Range.make(low, high);
}
return Range.make(low, low);
}
}
} catch (final NumberFormatException e) {
// ignore
}
return def;
}
/**
* Get INTEGER
*
* @param o object
* @return integer
*/
public static int toInteger(Object o)
{
return toInteger(o, 0);
}
/**
* Get DOUBLE
*
* @param o object
* @return double
*/
public static double toDouble(Object o)
{
return toDouble(o, 0d);
}
/**
* Get FLOAT
*
* @param o object
* @return float
*/
public static double toFloat(Object o)
{
return toFloat(o, 0f);
}
/**
* Get BOOLEAN
*
* @param o object
* @return boolean
*/
public static boolean toBoolean(Object o)
{
return toBoolean(o, false);
}
/**
* Get STRING
*
* @param o object
* @return String
*/
public static String toString(Object o)
{
return toString(o, "");
}
/**
* Get a vector of two or three coordinates
*
* @param o object
* @return Coord
*/
public static VectConst toVect(Object o)
{
return toVect(o, Vect.ZERO);
}
/**
* Get RANGE
*
* @param o object
* @return AiCoord
*/
public static Range toRange(Object o)
{
return toRange(o, new Range());
}
}
+76
View File
@@ -0,0 +1,76 @@
package mightypork.util.objects;
import java.util.*;
import java.util.Map.Entry;
/**
* Map sorting utils
*
* @author MightyPork
*/
public class MapSort {
/**
* Sort a map by keys, maintaining key-value pairs.
*
* @param map map to be sorted
* @param comparator a comparator, or null for natural ordering
* @return linked hash map with sorted entries
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <K extends Comparable, V extends Comparable> Map<K, V> sortByKeys(Map<K, V> map, final Comparator<K> comparator)
{
final List<K> keys = new LinkedList<>(map.keySet());
if (comparator == null) {
Collections.sort(keys);
} else {
Collections.sort(keys, comparator);
}
// LinkedHashMap will keep the keys in the order they are inserted
// which is currently sorted on natural ordering
final Map<K, V> sortedMap = new LinkedHashMap<>();
for (final K key : keys) {
sortedMap.put(key, map.get(key));
}
return sortedMap;
}
/**
* Sort a map by values, maintaining key-value pairs.
*
* @param map map to be sorted
* @param comparator a comparator, or null for natural ordering
* @return linked hash map with sorted entries
*/
@SuppressWarnings("rawtypes")
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());
Collections.sort(entries, new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(Entry<K, V> o1, Entry<K, V> o2)
{
if (comparator == null) return o1.getValue().compareTo(o2.getValue());
return comparator.compare(o1.getValue(), o2.getValue());
}
});
// LinkedHashMap will keep the keys in the order they are inserted
// which is currently sorted on natural ordering
final Map<K, V> sortedMap = new LinkedHashMap<>();
for (final Map.Entry<K, V> entry : entries) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
}
+78
View File
@@ -0,0 +1,78 @@
package mightypork.util.objects;
/**
* Mutable object
*
* @author MightyPork
* @param <T> type
*/
public class Mutable<T> {
/** The wrapped value */
private T o = null;
/**
* New mutable object
*
* @param o value
*/
public Mutable(T o) {
this.o = o;
}
/**
* Get the wrapped value
*
* @return value
*/
public T get()
{
return o;
}
/**
* Set value
*
* @param o new value to set
*/
public void set(T o)
{
this.o = o;
}
@Override
public String toString()
{
if (o == null) return "<null>";
return o.toString();
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((o == null) ? 0 : o.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj) return true;
if (obj == null) return false;
if (!(obj instanceof Mutable)) return false;
final Mutable<?> other = (Mutable<?>) obj;
if (o == null) {
if (other.o != null) return false;
} else if (!o.equals(other.o)) return false;
return true;
}
}
@@ -0,0 +1,48 @@
package mightypork.util.objects;
import java.util.ArrayList;
import java.util.List;
/**
* Object utils class
*
* @author MightyPork
*/
public class ObjectUtils {
public static Object fallback(Object... options)
{
for (final Object o : options) {
if (o != null) return o;
}
return null; // error
}
public static String arrayToString(Object[] arr)
{
final StringBuilder sb = new StringBuilder();
sb.append('[');
final boolean first = true;
for (final Object o : arr) {
if (!first) sb.append(',');
sb.append(o.toString());
}
sb.append(']');
return sb.toString();
}
public static <T extends Object> List<T> arrayToList(T[] objs)
{
final ArrayList<T> list = new ArrayList<>();
for (final T o : objs) {
list.add(o);
}
return list;
}
}
+92
View File
@@ -0,0 +1,92 @@
package mightypork.util.objects;
import mightypork.util.math.Calc;
/**
* Structure of 2 objects.
*
* @author MightyPork
* @copy (c) 2012
* @param <T1> 1st object class
* @param <T2> 2nd object class
*/
public class Pair<T1, T2> {
/**
* 1st object
*/
public T1 first;
/**
* 2nd object
*/
public T2 second;
/**
* Make structure of 2 objects
*
* @param first 1st object
* @param second 2nd object
*/
public Pair(T1 first, T2 second) {
this.first = first;
this.second = second;
}
/**
* @return 1st object
*/
public T1 getFirst()
{
return first;
}
/**
* @return 2nd object
*/
public T2 getSecond()
{
return second;
}
@Override
public boolean equals(Object obj)
{
if (obj == null) {
return false;
}
if (!this.getClass().equals(obj.getClass())) {
return false;
}
final Pair<?, ?> t = (Pair<?, ?>) obj;
return Calc.areObjectsEqual(first, t.first) && Calc.areObjectsEqual(second, t.second);
}
@Override
public int hashCode()
{
int hash = 13;
hash += (first == null ? 0 : first.hashCode());
hash += (second == null ? 0 : second.hashCode());
return hash;
}
@Override
public String toString()
{
return "PAIR{" + first + "," + second + "}";
}
}
+80
View File
@@ -0,0 +1,80 @@
package mightypork.util.objects;
import mightypork.util.math.Calc;
/**
* Structure of 3 objects.
*
* @author MightyPork
* @copy (c) 2012
* @param <T1> 1st object class
* @param <T2> 2nd object class
* @param <T3> 3rd object class
*/
public class Triad<T1, T2, T3> extends Pair<T1, T2> {
/**
* 3rd object
*/
public T3 third;
/**
* Make structure of 3 objects
*
* @param objA 1st object
* @param objB 2nd object
* @param objC 3rd object
*/
public Triad(T1 objA, T2 objB, T3 objC) {
super(objA, objB);
third = objC;
}
/**
* @return 3rd object
*/
public T3 getThird()
{
return third;
}
/**
* Set 1st object
*
* @param obj 1st object
*/
public void setThird(T3 obj)
{
third = obj;
}
@Override
public boolean equals(Object obj)
{
if (!super.equals(obj)) return false;
return Calc.areObjectsEqual(third, ((Triad<?, ?, ?>) obj).third);
}
@Override
public int hashCode()
{
return super.hashCode() + (third == null ? 0 : third.hashCode());
}
@Override
public String toString()
{
return "TRIAD{" + first + "," + second + "," + third + "}";
}
}
@@ -0,0 +1,54 @@
package mightypork.util.objects;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Varargs parser<br>
* Converts an array of repeated "key, value" pairs to a LinkedHashMap.<br>
* example:
*
* <pre>
* Object[] array = { &quot;one&quot;, 1, &quot;two&quot;, 4, &quot;three&quot;, 9, &quot;four&quot;, 16 };
* Map&lt;String, Integer&gt; args = new VarargsParser&lt;String, Integer&gt;().parse(array);
* </pre>
*
* @author MightyPork
* @param <K> Type for Map keys
* @param <V> Type for Map values
*/
public class VarargsParser<K, V> {
/**
* Parse array of vararg key, value pairs to a LinkedHashMap.
*
* @param args varargs
* @return LinkedHashMap
* @throws ClassCastException in case of incompatible type in the array
* @throws IllegalArgumentException in case of invalid array length (odd)
*/
@SuppressWarnings("unchecked")
public Map<K, V> parse(Object... args) throws ClassCastException, IllegalArgumentException
{
final LinkedHashMap<K, V> attrs = new LinkedHashMap<>();
if (args.length % 2 != 0) {
throw new IllegalArgumentException("Odd number of elements in varargs map!");
}
K key = null;
for (final Object o : args) {
if (key == null) {
if (o == null) throw new RuntimeException("Key cannot be NULL in varargs map.");
key = (K) o;
} else {
attrs.put(key, (V) o);
key = null;
}
}
return attrs;
}
}