Some refactoring and cleaning, string utils.

master
Ondřej Hruška 11 years ago
parent 272fb63168
commit 33696050d4
  1. 6
      src/mightypork/utils/Convert.java
  2. 4
      src/mightypork/utils/Reflect.java
  3. 231
      src/mightypork/utils/Str.java
  4. 95
      src/mightypork/utils/Support.java
  5. 5
      src/mightypork/utils/eventbus/BusEvent.java
  6. 22
      src/mightypork/utils/eventbus/EventBus.java
  7. 6
      src/mightypork/utils/eventbus/EventChannel.java
  8. 2
      src/mightypork/utils/eventbus/events/DestroyEvent.java
  9. 12
      src/mightypork/utils/files/FileUtil.java
  10. 14
      src/mightypork/utils/ion/Ion.java
  11. 4
      src/mightypork/utils/logging/Log.java
  12. 4
      src/mightypork/utils/logging/writers/ArchivingLog.java
  13. 4
      src/mightypork/utils/math/timing/Profiler.java
  14. 82
      src/mightypork/utils/string/StringUtil.java

@ -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();

@ -65,7 +65,7 @@ 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.");
} }
@ -86,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 ReflectiveOperationException("The " + fieldName + " field of " + Support.str(objClass) + " must be static and final!"); throw new ReflectiveOperationException("The " + fieldName + " field of " + Str.val(objClass) + " must be static and final!");
} }
fld.setAccessible(true); fld.setAccessible(true);

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

@ -9,8 +9,6 @@ import java.util.Iterator;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import mightypork.utils.annotations.Alias;
/** /**
* Miscelanous utilities * Miscelanous utilities
@ -201,97 +199,4 @@ public final class Support {
} }
} }
/**
* Convert a class to string, preserving name and outer class, but excluding
* path.
*
* @param cls the class
* @return class name
*/
public static String str(Class<?> cls)
{
final Alias ln = cls.getAnnotation(Alias.class);
if (ln != null) {
return ln.name();
}
String name = cls.getName();
String sep = "";
if (name.contains("$")) {
name = name.substring(name.lastIndexOf("$") + 1);
sep = "$";
} else {
name = name.substring(name.lastIndexOf(".") + 1);
sep = ".";
}
final Class<?> enclosing = cls.getEnclosingClass();
return (enclosing == null ? "" : Support.str(enclosing) + sep) + name;
}
/**
* Convert double to string, remove the mess at the end.
*
* @param d double
* @return string
*/
public static String str(Double d)
{
String s = d.toString();
s = s.replace(',', '.');
s = s.replaceAll("([0-9]+\\.[0-9]+)00+[0-9]+", "$1");
s = s.replaceAll("0+$", "");
s = s.replaceAll("\\.$", "");
return s;
}
/**
* Convert float to string, remove the mess at the end.
*
* @param f float
* @return string
*/
public static String str(Float f)
{
String s = f.toString();
s = s.replaceAll("([0-9]+\\.[0-9]+)00+[0-9]+", "$1");
s = s.replaceAll("0+$", "");
s = s.replaceAll("\\.$", "");
return s;
}
/**
* Convert object to string. If the object overrides toString(), it is
* caled. Otherwise it's class name is converted to string.
*
* @param o object
* @return string representation
*/
public static String str(Object o)
{
if (o == null) return "<null>";
boolean hasToString = false;
try {
hasToString = (o.getClass().getMethod("toString").getDeclaringClass() != Object.class);
} catch (final Throwable t) {
// oh well..
}
if (hasToString) {
return o.toString();
} else {
return str(o.getClass());
}
}
} }

@ -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;
@ -58,8 +59,6 @@ public abstract class BusEvent<HANDLER> {
throw new UnsupportedOperationException("Not consumable."); throw new UnsupportedOperationException("Not consumable.");
} }
(new Throwable()).printStackTrace();
consumed = true; consumed = true;
} }
@ -119,7 +118,9 @@ public abstract class BusEvent<HANDLER> {
* *
* @param bus event bus instance * @param bus event bus instance
*/ */
@Stub
public void onDispatchComplete(EventBus bus) public void onDispatchComplete(EventBus bus)
{ {
//
} }
} }

@ -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;
@ -206,7 +206,7 @@ final public class EventBus implements Destroyable {
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);
@ -224,7 +224,7 @@ final public class EventBus implements Destroyable {
{ {
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 {
{ {
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);
} }
@ -254,7 +254,7 @@ final public class EventBus implements Destroyable {
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));
} }
@ -269,7 +269,7 @@ final public class EventBus implements Destroyable {
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 {
{ {
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 {
//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) {
@ -362,8 +362,8 @@ final public class EventBus implements Destroyable {
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));
} }

@ -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;
@ -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);
@ -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) + " }";
} }
} }

@ -4,6 +4,7 @@ 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;
@ -14,6 +15,7 @@ import mightypork.utils.interfaces.Destroyable;
*/ */
@DirectEvent @DirectEvent
@NonConsumableEvent @NonConsumableEvent
@NonRejectableEvent
public class DestroyEvent extends BusEvent<Destroyable> { public class DestroyEvent extends BusEvent<Destroyable> {
@Override @Override

@ -17,8 +17,8 @@ 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;
@ -234,7 +234,7 @@ public class FileUtil {
public static String getExtension(String file) public static String getExtension(String file)
{ {
return StringUtil.fromLastChar(file, '.'); return Str.fromLast(file, '.');
} }
@ -249,13 +249,13 @@ public class FileUtil {
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);
@ -402,13 +402,13 @@ public class FileUtil {
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, '/');
} }

@ -13,7 +13,7 @@ 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;
/** /**
@ -116,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));
} }
} }
@ -135,7 +135,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));
} }
} }
@ -161,7 +161,7 @@ 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);
} }
} }
@ -223,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.");
} }
} }
@ -376,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) + ".");
} }
} }
@ -482,7 +482,7 @@ public class Ion {
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()));
} }
} }

@ -7,13 +7,13 @@ 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;
/** /**
@ -315,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,8 +9,8 @@ import java.util.Comparator;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import mightypork.utils.Str;
import mightypork.utils.files.FileUtil; import mightypork.utils.files.FileUtil;
import mightypork.utils.string.StringUtil;
/** /**
@ -125,6 +125,6 @@ public class ArchivingLog extends SimpleLog {
*/ */
private String getSuffix() private String getSuffix()
{ {
return StringUtil.fromLastChar(getFile().toString(), '.'); return Str.fromLast(getFile().toString(), '.');
} }
} }

@ -1,7 +1,7 @@
package mightypork.utils.math.timing; package mightypork.utils.math.timing;
import mightypork.utils.Support; import mightypork.utils.Str;
/** /**
@ -57,7 +57,7 @@ public class Profiler {
*/ */
public static String endStr(long begun) public static String endStr(long begun)
{ {
return Support.str(end(begun)) + " s"; return Str.val(end(begun)) + " s";
} }
} }

@ -1,82 +0,0 @@
package mightypork.utils.string;
/**
* General purpose string utilities
*
* @author Ondřej Hruška (MightyPork)
*/
public class StringUtil {
public static String fromLastDot(String s)
{
return fromLastChar(s, '.');
}
public static String toLastDot(String s)
{
return toLastChar(s, '.');
}
public static String fromLastChar(String s, char c)
{
if (s == null) return null;
return s.substring(s.lastIndexOf(c) + 1, s.length());
}
public static String toLastChar(String s, char c)
{
if (s == null) return null;
if (s.lastIndexOf(c) == -1) return s;
return s.substring(0, s.lastIndexOf(c));
}
/**
* 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;
}
}
Loading…
Cancel
Save