org.starhope.util
Class LibMisc

java.lang.Object
  extended by org.starhope.util.LibMisc

public class LibMisc
extends Object

Miscellaneous utility methods that might be useful elsewhere

Author:
brpocock@star-hope.org

Field Summary
private static String[] cardinalNumberWords_English
          Word-forms of English cardinal numbers
private static HashMap<Class<?>,Class<?>> extensionClasses
          An extension class can be registered to supplement or replace methods in the basic built-in command interpreters.
(package private) static int MAX_SHUTDOWN_TRIES
          Maximum number of times to clear the socket input buffer.
private static Map<String,Properties> messages
          The currently-loaded message catalogs
 
Constructor Summary
LibMisc()
           
 
Method Summary
static boolean areWeThereYet(AbstractUser thing, long when)
          WRITEME: document this method (brpocock@star-hope.org, Nov 24, 2009)
private static String cardinalNumber_English(int number)
          Get the English string form of a cardinal number
static void closeAll(Object... things)
          Close a bunch of things carefully, ignoring exceptions.
static void commandJSON(String cmd, org.json.JSONObject jso, CanProcessCommands commandThread, AbstractUser user, Class<?> klass)
           Execute a command with a certain method signature from klass, passing it the JSON parameters as well as the environment (thread, zone, and user) to run with.
static
<T> Collection<T>
condense(Collection<Collection<T>> sets)
          Condense a collection of collections down to just a collection.
static double distance(AbstractUser from, AbstractUser to, long when)
          WRITEME: document this method (brpocock@star-hope.org, Nov 24, 2009)
static double distance(double x1, double y1, double x2, double y2)
          WRITEME: document this method (brpocock@star-hope.org, Nov 24, 2009)
static void executeCommand(String cmd, org.json.JSONObject jso, CanProcessCommands commandThread, AbstractUser user, Method commandProcessor)
          WRITEME: Document this method brpocock@star-hope.org
private static String formatFutureDate_English(Date targetDate)
           
static String formatFutureDate(Date targetDate)
          WRITEME: document this method (brpocock@star-hope.org, Jan 18, 2010)
static String formatFutureDate(Date targetDate, String language_dialect)
          WRITEME brpocock@star-hope.org Jul 21, 2010
static String formatFutureDate(Date targetDate, String language, String dialect)
          WRITEME: document this method (brpocock@star-hope.org, Jan 18, 2010)
static String formatMemory(long numBytes)
          Create an user-visible string using metric figures accurate to 1 decimal place, expressing an amount of memory in KiB, MiB, &c.
private static String formatPastDate_English(Date targetDate)
           
static String formatPastDate(Date pastDate)
          See formatFutureDate(Date, String, String); applies the currently-selected default language of the thread context
static String formatPastDate(Date targetDate, String language, String dialect)
          WRITEME: document this method (brpocock@star-hope.org, Jan 18, 2010)
static String genFakeIP(Object o)
          Generate something that resembles an IP address, but is clearly not a valid host address.
static String getText(String string)
           
static String getText(String string, String language_dialect)
          WRITEME brpocock@star-hope.org Jul 21, 2010
static String getText(String string, String language, String dialect)
           
static String getTextOrDefault(String key, String fallback)
          Look for a string key in the message catalogue.
static String getTextOrDefault(String key, String language, String dialect, String fallback)
          WRITEME: Document this method brpocock@star-hope.org
static boolean hasText(String string)
          WRITEME: document this method (brpocock@star-hope.org, Jan 5, 2010)
static boolean hasText(String string, String language, String dialect)
          WRITEME: document this method (brpocock@star-hope.org, Jan 5, 2010)
static String hexify(byte[] input)
          Convert an array of bytes into a string of ASCII hexadecimal nybbles.
private static void initMessages()
           Initialise the configured message catalogues.
static double limit(double value, double min, double max)
          Limit a value to being between the minimum and maximum allowed
private static String listToDisplay_English(List<String> words)
          Internal helper method for listToDisplay(List, String, String) for English.
private static String listToDisplay_Español(List<String> words)
          Internal helper method for listToDisplay(List, String, String) for Spanish.
private static String listToDisplay_فرسئ(List<String> words)
          Internal helper method for listToDisplay(List, String, String) for Persian.
static String listToDisplay(Collection<? extends Object> words, String language, String dialect)
          WRITEME: document this method (brpocock@star-hope.org, Jan 12, 2010)
static String listToDisplay(List<String> words, String language, String dialect)
           Given a list of strings, combine then into a string for display purposes.
static String listToDisplay(Object[] set, String language, String dialect)
           
static Class<?> loadExtension(Class<?> klass)
          Find a substitute class for a command interpreter class with local extensions.
static int makeHashCode(String string)
          WRITEME: document this method (brpocock@star-hope.org, Dec 1, 2009)
static Map<Integer,String> randomize(Map<Integer,String> map)
           twheys@gmail.com Feb 5, 2010
static String rot13(String msg)
          Perform rot-13 on basic alphabetic characters in the font
(package private) static void sendJSONCommandBugReport(String cmd, org.json.JSONObject jso, CanProcessCommands commandThread, AbstractUser user, InvocationTargetException e)
          Send a bug report on something that occurred while attempting to process a JSON-based command
static void setMaxShutdownTries(int mst)
          Set the maximum number of times to clear the socket input buffer.
static void shutdownInput(Socket socket)
           This method taken from Apache Tomcat:
static LinkedHashMap<Integer,Integer> sortHashMapByValues(Map<Integer,Integer> stuffToSort)
          Sort the contents of a hash map based upon comparing the values of its keys.
private static void stringify_column(ResultSet rs, StringBuilder s, ResultSetMetaData meta, int i)
          WRITEME: Document this method brpocock@star-hope.org
private static void stringify_form(ResultSet rs, StringBuilder s, ResultSetMetaData meta, int numCols)
          WRITEME: Document this method brpocock@star-hope.org
private static void stringify_tabular(ResultSet rs, StringBuilder s, ResultSetMetaData meta, int numCols)
          WRITEME: Document this method brpocock@star-hope.org
static String stringify(Map<? extends Object,? extends Object> map)
          Convert a map into a string, mostly for debugging purposes.
static String stringify(Object... crap)
           
static String stringify(ResultSet rs)
          Dump an SQL ResultSet as a string table
static String stringify(StackTraceElement[] stackTrace)
          Create a pure string version of a stack backtrace
static String stringify(Throwable e)
           
static String stringJoin(String[] array, String delimiter)
          Joins an array of strings together using the given delimiter
static long timeToTarget(AbstractUser thing, long when)
          Deprecated. use Geometry.updateUserPositioning(AbstractUser, long, boolean)
static String toJavaCase(String source)
          convert a user-visible string into a javaCased moniker
static String trimWhiteSpace(String string)
           twheys@gmail.com Feb 17, 2010
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

cardinalNumberWords_English

private static final String[] cardinalNumberWords_English
Word-forms of English cardinal numbers


extensionClasses

private static final HashMap<Class<?>,Class<?>> extensionClasses
An extension class can be registered to supplement or replace methods in the basic built-in command interpreters. This is where they're stored.


MAX_SHUTDOWN_TRIES

static int MAX_SHUTDOWN_TRIES
Maximum number of times to clear the socket input buffer.


messages

private static Map<String,Properties> messages
The currently-loaded message catalogs

Constructor Detail

LibMisc

public LibMisc()
Method Detail

areWeThereYet

public static boolean areWeThereYet(AbstractUser thing,
                                    long when)
WRITEME: document this method (brpocock@star-hope.org, Nov 24, 2009)

Parameters:
thing - Who are we?
when - When are we?
Returns:
true if we've arrived on station

cardinalNumber_English

private static String cardinalNumber_English(int number)
Get the English string form of a cardinal number

Parameters:
number - a number
Returns:
a string

closeAll

public static void closeAll(Object... things)
Close a bunch of things carefully, ignoring exceptions. The “things” supported, thus far, are:

This is mostly meant for “finally” clauses.

Parameters:
things - A set of SQL statements, result sets, and database connections

commandJSON

public static void commandJSON(String cmd,
                               org.json.JSONObject jso,
                               CanProcessCommands commandThread,
                               AbstractUser user,
                               Class<?> klass)

Execute a command with a certain method signature from klass, passing it the JSON parameters as well as the environment (thread, zone, and user) to run with.

The class klass is searched for a method with the name "do_COMMAND", which must take a Zone, JSONObject, User, and Integer (as a room number in which the user is standing) as input parameters. If no such method is found, the extension class (if any) defined for klass using loadExtension(Class) will also be searched, before reporting an error back to the command thread.

Parameters:
cmd - The command's string name
jso - JSON parameters to that command
commandThread - The command processor thread
user - The user initiating the command
klass - The command-processor class in which to search for the command

condense

public static <T> Collection<T> condense(Collection<Collection<T>> sets)
Condense a collection of collections down to just a collection.

Type Parameters:
T - whatever type of stuff you want to put into it
Parameters:
sets - a collection of collections
Returns:
just a collection

distance

public static double distance(AbstractUser from,
                              AbstractUser to,
                              long when)
WRITEME: document this method (brpocock@star-hope.org, Nov 24, 2009)

Parameters:
from - one thing
to - another thing
when - when is it
Returns:
the distance between the two objects

distance

public static double distance(double x1,
                              double y1,
                              double x2,
                              double y2)
WRITEME: document this method (brpocock@star-hope.org, Nov 24, 2009)

Parameters:
x1 - start x abcessa
y1 - start y ordinate
x2 - end x abcessa
y2 - end y ordinate
Returns:
distance

executeCommand

public static void executeCommand(String cmd,
                                  org.json.JSONObject jso,
                                  CanProcessCommands commandThread,
                                  AbstractUser user,
                                  Method commandProcessor)
WRITEME: Document this method brpocock@star-hope.org

Parameters:
cmd - WRITEME
jso - WRITEME
commandThread - WRITEME
user - WRITEME
commandProcessor - WRITEME

formatFutureDate

public static String formatFutureDate(Date targetDate)
WRITEME: document this method (brpocock@star-hope.org, Jan 18, 2010)

Parameters:
targetDate - a date in the future
Returns:
a human-legible expression describing the time in the future

formatFutureDate

public static String formatFutureDate(Date targetDate,
                                      String language_dialect)
WRITEME brpocock@star-hope.org Jul 21, 2010

Parameters:
targetDate - WRITEME
language_dialect - WRITEME
Returns:
WRITEME

formatFutureDate

public static String formatFutureDate(Date targetDate,
                                      String language,
                                      String dialect)
WRITEME: document this method (brpocock@star-hope.org, Jan 18, 2010)

Parameters:
targetDate - a date in the future
language - the user's language
dialect - the user's dialect
Returns:
a human-legible expression describing the time in the future

formatFutureDate_English

private static String formatFutureDate_English(Date targetDate)
Parameters:
targetDate - a date in the future
Returns:
a human-legible expression describing the time in the future

formatMemory

public static String formatMemory(long numBytes)
Create an user-visible string using metric figures accurate to 1 decimal place, expressing an amount of memory in KiB, MiB, &c. to one decimal place. For example, “12.1 KiB” or “4.2 GiB”.

Parameters:
numBytes - a number of bytes (size_t)
Returns:
a human-legible string

formatPastDate

public static String formatPastDate(Date pastDate)
See formatFutureDate(Date, String, String); applies the currently-selected default language of the thread context

Parameters:
pastDate - the date to be thus described
Returns:
a string describing the past date in general terms

formatPastDate

public static String formatPastDate(Date targetDate,
                                    String language,
                                    String dialect)
WRITEME: document this method (brpocock@star-hope.org, Jan 18, 2010)

Parameters:
targetDate - a date in the future
language - the user's language
dialect - the user's dialect
Returns:
a human-legible expression describing the time in the future

formatPastDate_English

private static String formatPastDate_English(Date targetDate)
Parameters:
targetDate - a date in the future
Returns:
a human-legible expression describing the time in the future

genFakeIP

public static String genFakeIP(Object o)
Generate something that resembles an IP address, but is clearly not a valid host address. Nonetheless, this address will contain valid byte values. Some byte in the address will be a 255 or the address will begin or end with a zero byte. Since this method uses the object's hash code, it will be consistent for an object.

Parameters:
o - The object for which to generate a fake IP address
Returns:
a string in dotted-quad form

getText

public static String getText(String string)
Parameters:
string - WRITEME
Returns:
WRITEME

getText

public static String getText(String string,
                             String language_dialect)
WRITEME brpocock@star-hope.org Jul 21, 2010

Parameters:
string - WRITEME
language_dialect - WRITEME
Returns:
WRITEME

getText

public static String getText(String string,
                             String language,
                             String dialect)
Parameters:
string - WRITEME
language - WRITEME
dialect - WRITEME
Returns:
WRITEME

getTextOrDefault

public static String getTextOrDefault(String key,
                                      String fallback)
Look for a string key in the message catalogue. If a given key does exist, return that message. If not, fall back to the provided default text.

Parameters:
key - The key name which should exist in the message catalogue.
fallback - The fallback text to be used if that message does not exist.
Returns:
Either the message from the catalogue, or the fallback message if one is unavailable.

getTextOrDefault

public static String getTextOrDefault(String key,
                                      String language,
                                      String dialect,
                                      String fallback)
WRITEME: Document this method brpocock@star-hope.org

Parameters:
key -
language -
dialect -
fallback -
Returns:

hasText

public static boolean hasText(String string)
WRITEME: document this method (brpocock@star-hope.org, Jan 5, 2010)

Parameters:
string - WRITEME
Returns:
WRITEME

hasText

public static boolean hasText(String string,
                              String language,
                              String dialect)
WRITEME: document this method (brpocock@star-hope.org, Jan 5, 2010)

Parameters:
string - WRITEME
language - WRITEME
dialect - WRITEME
Returns:
WRITEME

hexify

public static String hexify(byte[] input)
Convert an array of bytes into a string of ASCII hexadecimal nybbles.

Parameters:
input - The bytes to be converted to hex
Returns:
the hex equivalent

initMessages

private static void initMessages()

Initialise the configured message catalogues.

Each message catalogue is loaded based upon the key named org.starhope.messages.LANG_DIALECT, and must be enumerated in the “master” list of org.starhope.messages.

In the absence of either key, the default message language set is simply en_US (US English), and the default message catalogues are /etc/appius/messages/$LANG_DIALECT.properties, e.g. /etc/appius/messages/en_US.properties


limit

public static double limit(double value,
                           double min,
                           double max)
Limit a value to being between the minimum and maximum allowed

Parameters:
value - the value
min - the least permitted value
max - the max permitted value
Returns:
the value, clipped to the range

listToDisplay

public static String listToDisplay(Collection<? extends Object> words,
                                   String language,
                                   String dialect)
WRITEME: document this method (brpocock@star-hope.org, Jan 12, 2010)

Parameters:
words - WRITEME
language - WRITEME
dialect - WRITEME
Returns:
WRITEME

listToDisplay

public static String listToDisplay(List<String> words,
                                   String language,
                                   String dialect)

Given a list of strings, combine then into a string for display purposes.

For English, the list will obey the traditional grammatical usage of commas: List elements are joined with commas, except that the conjunction (in our case, always “and”) occurs penultimate, and two or three element lists do not use commas.

For Spanish, works essentially the same way.

For other languages, we just join the words with commas and omit the conjunction

Parameters:
words - A list of words.
language - The user's display language
dialect - The user's sublanguage dialect
Returns:
The list formatted into a string.

listToDisplay

public static String listToDisplay(Object[] set,
                                   String language,
                                   String dialect)
Parameters:
set - WRITEME
language - WRITEME
dialect - WRITEME
Returns:
WRITEME

listToDisplay_English

private static String listToDisplay_English(List<String> words)
Internal helper method for listToDisplay(List, String, String) for English.

Parameters:
words - word list
Returns:
list formatted for display in English

listToDisplay_Español

private static String listToDisplay_Español(List<String> words)
Internal helper method for listToDisplay(List, String, String) for Spanish.

Parameters:
words - word list
Returns:
list formatted for display in Spanish

listToDisplay_فرسئ

private static String listToDisplay_فرسئ(List<String> words)
Internal helper method for listToDisplay(List, String, String) for Persian.

Parameters:
words - word list
Returns:
list formatted for display in Persian

loadExtension

public static Class<?> loadExtension(Class<?> klass)
Find a substitute class for a command interpreter class with local extensions. These are defined by specifying the canonical class name in the configuration as a parameter to a key of the form "xtn." plus the canonical class name of the main class to which the extension applies.

Parameters:
klass - The class for which an extension might exist
Returns:
An extension class, if one exists; else, the same class as passed-in

makeHashCode

public static int makeHashCode(String string)
WRITEME: document this method (brpocock@star-hope.org, Dec 1, 2009)

Parameters:
string - WRITEME
Returns:
WRITEME

randomize

public static Map<Integer,String> randomize(Map<Integer,String> map)
 twheys@gmail.com Feb 5, 2010
 
TO randomize return a shuffled map.

Parameters:
map - the hashmap to shuffle
Returns:
Map with values shuffled

rot13

public static String rot13(String msg)
Perform rot-13 on basic alphabetic characters in the font

Parameters:
msg - The string to be rot-13:ed
Returns:
The string after rot-13

sendJSONCommandBugReport

static void sendJSONCommandBugReport(String cmd,
                                     org.json.JSONObject jso,
                                     CanProcessCommands commandThread,
                                     AbstractUser user,
                                     InvocationTargetException e)
Send a bug report on something that occurred while attempting to process a JSON-based command

Parameters:
cmd - WRITEME
jso - WRITEME
commandThread - WRITEME
user - WRITEME
e - WRITEME

setMaxShutdownTries

public static void setMaxShutdownTries(int mst)
Set the maximum number of times to clear the socket input buffer.

Parameters:
mst - maximum number of tries to shut down a socket input buffer

shutdownInput

public static void shutdownInput(Socket socket)
                          throws IOException

This method taken from Apache Tomcat:

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Shut down the input stream of a connection

Parameters:
socket - The socket whose input stream is to be shut down
Throws:
IOException - If the input stream cannot be shut down despite best efforts

sortHashMapByValues

public static LinkedHashMap<Integer,Integer> sortHashMapByValues(Map<Integer,Integer> stuffToSort)
Sort the contents of a hash map based upon comparing the values of its keys. This implementation takes a hash map tying integers to integers, and is used for e.g. sorting high scores by players

Parameters:
stuffToSort - The hash table to be sorted
Returns:
the stuff all sorted

stringify

public static String stringify(Map<? extends Object,? extends Object> map)
Convert a map into a string, mostly for debugging purposes.

Parameters:
map - a map object to be stringified
Returns:
a string containing all keys and values in the map

stringify

public static String stringify(Object... crap)
Parameters:
crap - arbitrary stuff to stringify
Returns:
a somewhat legible stringification of the set

stringify

public static String stringify(ResultSet rs)
Dump an SQL ResultSet as a string table

Parameters:
rs - result set to dump
Returns:
tabular form

stringify

public static String stringify(StackTraceElement[] stackTrace)
Create a pure string version of a stack backtrace

Parameters:
stackTrace - An array of StackTraceElements:s
Returns:
A string version of the entire stack backtrace

stringify

public static String stringify(Throwable e)
Parameters:
e - A Throwable to be stringified into a backtrace
Returns:
The string form

stringify_column

private static void stringify_column(ResultSet rs,
                                     StringBuilder s,
                                     ResultSetMetaData meta,
                                     int i)
                              throws SQLException
WRITEME: Document this method brpocock@star-hope.org

Parameters:
rs - WRITEME
s - WRITEME
meta - WRITEME
i - WRITEME
Throws:
SQLException - WRITEME

stringify_form

private static void stringify_form(ResultSet rs,
                                   StringBuilder s,
                                   ResultSetMetaData meta,
                                   int numCols)
                            throws SQLException
WRITEME: Document this method brpocock@star-hope.org

Parameters:
rs - WRITEME
s - WRITEME
meta - WRITEME
numCols - WRITEME
Throws:
SQLException - WRITEME

stringify_tabular

private static void stringify_tabular(ResultSet rs,
                                      StringBuilder s,
                                      ResultSetMetaData meta,
                                      int numCols)
                               throws SQLException
WRITEME: Document this method brpocock@star-hope.org

Parameters:
rs - WRITEME
s - WRITEME
meta - WRITEME
numCols - WRITEME
Throws:
SQLException - WRITEME

stringJoin

public static String stringJoin(String[] array,
                                String delimiter)
Joins an array of strings together using the given delimiter

Parameters:
array - The array of strings
delimiter - The string to append between the other strings
Returns:
A new string with the strings all appended together

timeToTarget

@Deprecated
public static long timeToTarget(AbstractUser thing,
                                           long when)
Deprecated. use Geometry.updateUserPositioning(AbstractUser, long, boolean)

Determine the object's current position, and the time until it reaches its target (from now). Note that this was the preferred routine to be used to update the position of an object. Now, use #updateUserPositioning(AbstractUser,long)

When called through this interface, always executes side-effects

Identical to Geometry.updateUserPositioning(AbstractUser, long, boolean) with the last parameter as “true.”

Parameters:
thing - what is moving
when - what time is it now
Returns:
how long until it gets there
See Also:
Geometry.getTimeToTarget(AbstractUser, long), Geometry.updateUserPositioning(AbstractUser), Geometry.updateUserPositioning(AbstractUser, long), Geometry.updateUserPositioning(AbstractUser, long, boolean)

toJavaCase

public static String toJavaCase(String source)
convert a user-visible string into a javaCased moniker

Parameters:
source - the string provided
Returns:
the string converted into javaCased (CamelCase with initial miniscule letter)

trimWhiteSpace

public static String trimWhiteSpace(String string)
 twheys@gmail.com Feb 17, 2010
 
Replace all groups of whitespace including return lines and tabs with a single space and trims the leading and trailing whitespace.

Parameters:
string - A string to be trimmed.
Returns:
the trimmed string