public class CASAUtil extends Object
Copyright: Copyright 2003-2014, Knowledge Science Group, University of Calgary. Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The Knowledge Science Group makes no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty.
Modifier and Type | Field and Description |
---|---|
(package private) static TreeMap<String,InetAddress[]> |
cachedAddresses |
private static InetAddress |
cachedLocalHost |
private static String |
ESCAPED_CHARACTERS |
private static String[] |
myAddresses
Used to cache the return value from
getMyAddresses() . |
private static String[] |
myHostNames |
private static InetAddress[] |
myInetAddresses
Used to cache the return value from
getMyInetAddresses() . |
Constructor and Description |
---|
CASAUtil() |
Modifier and Type | Method and Description |
---|---|
static String |
byteArrayAsHexString(byte[] buffer) |
static String |
bytesToString(byte[] bb,
String encoding) |
static Object |
callMethod(Class<?> cls,
String methodName,
Object target,
Class<?>[] paramTypes,
Object[] params)
Calls a method by name alone, without requiring the compiler to know about it.
|
static String |
decode(String input,
boolean decodeAmp)
Given a string with encoded "binary" data ("%hh" for ASCII codes less
than 32), returns a string with each of the encoded characters replaced
by the approriate "binary" (non-printable) character.
|
static String |
encode(String input,
boolean escapeAmp)
Given a string with "binary" data (ASCII codes less than 32), returns a string
with each of the non-printable characters (less than ASCII 32) substituted
with "%hh", where "h" is a hex digit.
|
static String |
escape(String in,
String escChars2)
Returns a new String that is in encoded with backslashes in
front of every instance of any character that occurs in escChars.
|
static Map<String,Class<?>> |
fillSubclasses(Map<String,Class<?>> map,
Class<?> superclass,
String target,
String suffix)
Search for a class named target+suffix that is a subclass of superclass.
|
static Ontology |
findOntology(TransientAgent agent,
ParamsMap params,
AgentUI ui,
Environment env) |
static List<Class<?>> |
findSubclassesOf(Class<?> superclass)
Returns a list of all the proper subclasses of the parameter class.
|
static List<Class<?>> |
findSubClassesOf(String pckgname,
Class<?> superclass)
Returns a list of all the proper subclasses of the parameter class with the parameter package.
|
static String |
formatWidth(String text,
int lineWidth,
String autoIndent) |
static String |
fromQuotedString(String s)
Returns exactly the same results as
fromQuotedString(s,0) . |
static String |
fromQuotedString(String s,
int startAt)
Given a String (as generated from
toQuotedString(String) )
returns a String without the enclosing quotes and with an escaped double-quotes
restored (unescaped). |
static AbstractProcess |
getAbstractProcessInScope()
Attempt to find an in-scope agent.
|
static AbstractProcess |
getAbstractProcessInScopeSilent()
Attempt to find an in-scope agent.
|
static String[] |
getAddressesFor(InetAddress addr) |
static String |
getDateAsString()
Returns the current time as a formated date string in the default format
|
static String |
getDateAsString(Long timeSpec)
Converts the long millisecond time to a formated date string in the default format
|
static String |
getDateAsString(Long timeSpec,
String format)
Converts the long millisecond time to a formated date string
|
static String |
getDateAsString(String format)
Returns the current time as a formated date string
|
static InetAddress[] |
getInetAddressesFor(InetAddress addr) |
private static InetAddress[] |
getInetAddressesForPrimitive(InetAddress addr) |
static InetAddress |
getLocalHost()
This method should be used by CASA in place of
InetAddress.getLocalHost() . |
static String[] |
getMyAddresses() |
static String[] |
getMyHostNames() |
static InetAddress[] |
getMyInetAddresses() |
static InetAddress |
getNetwork(InetAddress remoteAddr,
InetAddress defaultLocal)
Returns the correct outgoing IP address for network associated with remoteAddr.
|
static int |
getOpenPort(int start)
Attempts opening the requested port.
|
static String |
getPID() |
static String |
getStack(Throwable ex)
Given an Exception, return the stack trace as a String object
|
private static String |
innerSerialize(Object x) |
static Object |
interpretString(String content,
String className)
Attempt to interpret the string content as an object of type className.
|
private static boolean |
isHexDigit(char input) |
static boolean |
isMyHostName(String hostName) |
static boolean |
isMyInetAddress(InetAddress addr) |
static boolean |
isSerializable(Class<?> _class)
Determines if a class is serializable by testing to see if at least one of the following conditions holds:
it has a constructor with a single String parameter
it has a fromString(
String ) method and a constructor with no parameters
it has a fromString(TokenParser ) method and a constructor with no parameters
|
static boolean |
isSerializable(Object obj)
Determines if the object is serializable by calling
isSerializable(Class) with the class of the object. |
static String |
log(String tag,
String message,
Throwable ex,
boolean printStackTrace)
Deprecated.
Use
Trace.log(String,String,Throwable,int) instead |
static void |
main(String[] args) |
(package private) static String |
makeLogHeader(String tag)
Deprecated.
|
static String |
makeUnprintablesVisible(String s)
Utility method to display a string with all escape characters visible.
|
static Class<?>[] |
objectsToClasses(Object[] o)
Given an array of objects, return an array of Class corresponding to the
classes of the objects
|
static StringBuilder |
pad(StringBuilder buf,
int n_spaces) |
static String |
padLeftTo(String s,
char c,
int n_spaces) |
static String |
padRightTo(String s,
char c,
int n_spaces) |
static String |
printui(String s,
AgentUI ui,
ParamsMap params,
TransientAgent agent) |
static Status |
readPersistentFromProperties(String prefix,
Object obj,
CASAFilePropertiesMap properties)
Reads the persistent data from the data structures marked with the CasaPersistent annotation.
|
static void |
resetInetAddresses()
Resets the caches for
getMyAddresses() and getMyInetAddresses() . |
static int |
scanFor(String in,
int startAt,
String chars)
Scans for the first occurrence of any of the characters in chars
starting at startAt, and returns the index (from the beginning
of string, not startAt).
|
static int |
scanForWhiteSpace(String in,
int startAt)
Scans for the first occurrence of any charcter less or equal to than ascii 32 (blank)
starting at startAt, and returns the index (from the beginning
of string, not startAt).
|
static String |
serialize(Collection<?> collection)
Given a collection of Objects, returns an String of the form:
|
static String |
serialize(Map<?,?> map)
Given an
Map object, returns a String of the form: |
static String |
serialize(Object... array)
Given an array of Objects, returns an String of the form:
|
static String |
serialize(Object x)
Returns the serialized Object x in the form:
|
static boolean |
sleepIgnoringInterrupts(long time,
Runnable1<InterruptedException,Boolean> code)
Wait time milliseconds ignoring interrupts.
|
static TransientAgent |
startAnAgent(Class<?> theClass,
String agentName,
int port,
Runnable1<TransientAgent,Void> code,
String... argPairs)
Run an agent of type theClass named agentName on port port, optionally
executing code once the agent is started up.
|
void |
test() |
static LispObject |
toCons(String... strings)
Put the argument strings into a cons list.
|
static String |
toQuotedString(Object x)
Returns the result x.toString() but surrounded by double-quotes
and with any double-quotes originally in x.toString() escaped.
|
static String |
toQuotedString(String s)
Returns the s surrounded by double-quotes and with any double-quotes
originally in s escaped.
|
static String |
unescape(String in,
String escChars2)
Removes any backslash characters that had been added to in by a
previous call to
escape(String,String) with the same
escChars. |
static Object |
unserialize(String s,
int startAt,
String defaultClassName)
Attempts to construct an object from a serialized string.
|
static Object |
unserialize(String s,
String className)
Calls
unserialize(s,0) to return an
object instantiated from s. |
static Object[] |
unserializeArray(String s,
int startAt,
String className)
Returns an array of Objects instantiated from s.
|
static Object[] |
unserializeArray(String s,
String className)
Behaves exactly the same as
unserializeArray(s,0) . |
static Hashtable<Object,Object> |
unserializeHashtable(String s,
int startAt,
String className)
Returns a
HashTable object instantiated from s. |
static Hashtable<Object,Object> |
unserializeHashtable(String s,
String className)
Behaves exactly the same as
unserializeHashtable(s,0) . |
static Object |
unserializeQuotedString(String input,
int mark,
String className) |
private static void |
updateHostNames(InetAddress[] addresses) |
static Status |
writePersistentToProperties(String prefix,
Object obj,
CASAFilePropertiesMap properties)
Private recursive helper method for the public
#writePersistent() method. |
private static final String ESCAPED_CHARACTERS
private static InetAddress cachedLocalHost
static TreeMap<String,InetAddress[]> cachedAddresses
private static InetAddress[] myInetAddresses
getMyInetAddresses()
. Set to null to
get the addresses recaluclated.private static String[] myHostNames
private static String[] myAddresses
getMyAddresses()
. Set to null to
get the addresses recaluclated.public static String getStack(Throwable ex)
ex
- an Exception object; may be null, in which case the stack trace will the generated.public static String escape(String in, String escChars2)
casautil.escape("(())","()") ==> "\(\(\)\)"
escape() always escapes the backslash character, so unescape(x,"")
is exactly the same as escape(x,"\\")
.
code value of s s = "(())"; (()) s = escape(s,"()"); \(\(\)\) s = unescape(s,"()"); (()) s = escape(s,"()"); \(\(\)\) s = escape(s,"()"); \\(\\(\\)\\) s = unescape(s,"()"); \(\(\)\) s = unescape(s,"()"); (())
in
- the input String to operate onescChars2
- a String containing the characters to escape (prepend with a backslash)unescape(String, String)
,
scanFor(String, int, String)
public static String unescape(String in, String escChars2)
escape(String,String)
with the same
escChars. For example,
casautil.unescape("\(\(\)\)","()") ==> "(())"
unescape() always
unescapes the backslash character, so unescape(x,"")
is
exactly the same as unescape(x,"\\")
. code value of s s = "(())"; (()) s = escape(s,"()"); \(\(\)\) s = unescape(s,"()"); (()) s = escape(s,"()"); \(\(\)\) s = escape(s,"()"); \\(\\(\\)\\) s = unescape(s,"()"); \(\(\)\) s = unescape(s,"()"); (())
in
- the string to unescapeescChars2
- the escaped characters to recognizeescape(String,String)
,
scanFor(String,int,String)
public static int scanFor(String in, int startAt, String chars)
scanFor(String, int, String)
can be used in conjunction with {#link escape(String,String)} and unescape(String, String)
to guarantee that
an unknown string can be parsed. For example, you need to delineate an
arbitrary string for future reading, but there may be further text after
it. You can't just surround your string with {} because your string may
contain } characters. Save your string, s, as s="{"+escape(s,"{}")+"}"
you can safely use scanFor(s,1,"{}") to find the original terminating
} delimiter. The expression:
unescape(s.substring(scanFor(s,0,"{")+1,scanFor(s,scanFor(s,0,"{"),"}")),"{}")successfully retrieves the original string, no matter what was in the original string.
in
- startAt
- chars
- unescape(String, String)
,
escape(String, String)
public static int scanForWhiteSpace(String in, int startAt)
in
- startAt
- public static String toQuotedString(String s)
s
- escape(String, String)
public static String fromQuotedString(String s) throws ParseException
fromQuotedString(s,0)
.s
- the quoted string to de-quoteParseException
- if s can't be interpreted as a quoted string (eg: first non-white-space isn't '"') starting at startAtpublic static String fromQuotedString(String s, int startAt) throws ParseException
toQuotedString(String)
)
returns a String without the enclosing quotes and with an escaped double-quotes
restored (unescaped). Extra chars after the closing quote are ignored.s
- the quoted string to de-quotestartAt
- the position is s to start atParseException
- if s can't be interpreted as a quoted string (eg: first non-white-space isn't '"') starting at startAtunescape(String, String)
public static String toQuotedString(Object x)
x
- the object to turn into a quoted stringescape(String, String)
public static String serialize(Object x)
'(' class-name ')' serialized-objectwhere
serialized-object
is obtained by calling the object's
toString() method and applying toQuotedString(String)
to it. This will surround it is double-quotes and escape any quotes
that happen to be in the string.x
- the object o serializeunserialize(String, String)
public static Object unserialize(String s, String className) throws ParseException
unserialize(s,0)
to return an
object instantiated from s.s
- the string containing the serialized objectclassName
- TODOParseException
- if a new object cannot be instantiated from spublic static Object unserialize(String s, int startAt, String defaultClassName) throws ParseException
serial-obj ::= null | hashtable | array | quoted-string | integer | collection | simple-object null ::= "null" hashtable ::= "{" { serial-obj "=" serial-obj } { "," serial-obj "=" serial-obj }* "}" array ::= "[" { serial-obj } { "," serial-obj }* "]" quoted-string ::= '"' text-with-escaped-quotes '"' integer ::= {digit}+ collection ::= "(" class-name ")" array simple-object ::= "(" class-name ")" quoted-string
simple-object
s are all instantiated by trying several means in
the following order:
TokenParser
) method on the object
If all the above fails, further attempts are made:
interpretString(String, String)
is called
to interpret raw characters as per the "several means" above.
s
- the String containing the serialized object(s)startAt
- the position in the String s to start atclassName
- TODOParseException
- if an object cannot be instantiatedpublic static Object interpretString(String content, String className)
TokenParser
)
content
- The String to interpret as aboveclassName
- The name of the class the content is expected to be an object ofpublic static boolean isSerializable(Object obj)
isSerializable(Class)
with the class of the object.o
- The object to inspectisSerializable(Class)
public static boolean isSerializable(Class<?> _class)
String
) method and a constructor with no parameters
TokenParser
) method and a constructor with no parameters
_class
- The Class to inspect.public static String serialize(Map<?,?> map)
Map
object, returns a String of the form:
"{" { serial-obj "=" serial-obj } { "," serial-obj "=" serial-obj }* "}"(See
unserialize(String, int, String)
for the definition of serial-obj
.)map
- the data structure to serializepublic static String serialize(Object... array)
"[" { serial-obj } { "," serial-obj }* "]"(See
unserialize(String, int, String)
for the definition of serial-obj
.)array
- the array to serializepublic static String serialize(Collection<?> collection)
"(" class-name ")" array(See
serialize(Object[])
for the definition of array
.)collection
- the Collection to serializepublic static Hashtable<Object,Object> unserializeHashtable(String s, String className) throws ParseException
unserializeHashtable(s,0)
.s
- the String to interpret a Collection
from.className
- TODOParseException
- if an object cannot be instantiated from spublic static Hashtable<Object,Object> unserializeHashtable(String s, int startAt, String className) throws ParseException
HashTable
object instantiated from s.
s is expected to be of the form:
"(" class-name ")" arraySee
unserializeArray(String, int, String)
for the definition of
array
.
Extra characters after the end of the object are ignored.s
- the String to interpret a Collection
from.startAt
- the position in s to start parsingclassName
- TODOParseException
- if an object cannot be instantiated from spublic static Object unserializeQuotedString(String input, int mark, String className) throws ParseException
ParseException
public static Object[] unserializeArray(String s, String className) throws ParseException
unserializeArray(s,0)
.s
- the String to interpret an array of objects from.className
- TODOParseException
- if an object cannot be instantiated from spublic static Object[] unserializeArray(String s, int startAt, String className) throws ParseException
"[" { serial-obj } { "," serial-obj }* "]"See
unserialize(String, int, String)
for the definition of
serial-obj
.
Extra characters after the end of the object are ignored.s
- the String to interpret an array of Objects from.startAt
- the position in s to start parsingclassName
- TODOParseException
- if an object cannot be instantiated from spublic static void main(String[] args)
public static String encode(String input, boolean escapeAmp)
input
- the string to encodeescapeAmp
- public static StringBuilder pad(StringBuilder buf, int n_spaces)
public static String decode(String input, boolean decodeAmp)
input
- the string to encodedecodeAmp
- private static boolean isHexDigit(char input)
public static InetAddress getLocalHost()
InetAddress.getLocalHost()
. Since the firewalls etc. may
cause casa to have to use a different local host IP address, an local
host ip address may be stored in the file CASA.casa (a CASA-format file)
under the property "router". This method will look in this file (if it
exists) before using the InetAddress.getLocalHost() method to get the
local host.public static String byteArrayAsHexString(byte[] buffer)
public static Class<?>[] objectsToClasses(Object[] o)
o
- the array of Objectspublic static String getDateAsString()
public static String getDateAsString(String format)
format
- The format of the date string according to DateFormat.format(Date)
.public static String getDateAsString(Long timeSpec)
timeSpec
- the time in milliseconds to convert to a date stringpublic static String getDateAsString(Long timeSpec, String format)
timeSpec
- the time in milliseconds to convert to a date stringformat
- The format of the date string according to DateFormat.format(Date)
.public static int getOpenPort(int start)
start
- public static Status writePersistentToProperties(String prefix, Object obj, CASAFilePropertiesMap properties)
#writePersistent()
method.prefix
- A prefix to add to thisobj
- The object to write out.#writePersistent()
public static Status readPersistentFromProperties(String prefix, Object obj, CASAFilePropertiesMap properties)
prefix
- obj
- properties
- public static List<Class<?>> findSubclassesOf(Class<?> superclass)
superclass
- The class to return all the subclasses of.public static List<Class<?>> findSubClassesOf(String pckgname, Class<?> superclass)
pckgname
- The name of package to searchsuperclass
- The class to return all the subclasses of.public void test()
public static String bytesToString(byte[] bb, String encoding)
bb
- encoding
- The encoding (eg: "UTF-8").public static String makeUnprintablesVisible(String s)
s
- The string that may contain non-printable characters.public static Ontology findOntology(TransientAgent agent, ParamsMap params, AgentUI ui, Environment env)
public static String printui(String s, AgentUI ui, ParamsMap params, TransientAgent agent)
private static InetAddress[] getInetAddressesForPrimitive(InetAddress addr)
public static InetAddress[] getInetAddressesFor(InetAddress addr)
public static void resetInetAddresses()
getMyAddresses()
and getMyInetAddresses()
. Call this
method to cause the recalculation of the InetAddresses on the next call to these methods.private static void updateHostNames(InetAddress[] addresses)
public static boolean isMyHostName(String hostName)
public static String[] getMyHostNames()
public static boolean isMyInetAddress(InetAddress addr)
addr
- public static InetAddress[] getMyInetAddresses()
public static String[] getAddressesFor(InetAddress addr)
public static String[] getMyAddresses()
public static InetAddress getNetwork(InetAddress remoteAddr, InetAddress defaultLocal)
remoteAddr
- defaultLocal
- the default to return if none is found.Exception
public static Map<String,Class<?>> fillSubclasses(Map<String,Class<?>> map, Class<?> superclass, String target, String suffix)
map
- If there is already a map, this should be filled, which acts as a cache -- eliminating the search time. If this null the preferences and possibly run-time sub
classes will be searched.superclass
- The class to look for subclasses of. This may NOT be null;target
- The prefix part of the class name we are looking for, which is also used as the index to this class in the return Map. If
this is null, an extensive search will always be made for all subclasses matching the suffix part.suffix
- The suffice pat the class name (the class name we looking for is prefix+suffix). If this is null,
it will be taken as the name of the superclass.public static boolean sleepIgnoringInterrupts(long time, Runnable1<InterruptedException,Boolean> code)
time
- The time to wait.code
- If an intterrupt happens during the sleep,
Runnable1.run(Object)
on code is called. If the run() returns
true, this method aborts the sleep and returns false. This parameter may be null,
in which case, this method sleeps the entire time.public static AbstractProcess getAbstractProcessInScopeSilent()
AbstractProcess
AbstractProcess.Subthread
created with AbstractProcess.makeSubthread(Runnable)
or AbstractProcess.makeSubthread(Runnable, String)
then return the agent recorded in the SubThread.
ThreadLocal
) of type
AbstractProcess
then return this agent.
public static AbstractProcess getAbstractProcessInScope()
getAbstractProcessInScopeSilent()
@Deprecated public static String log(String tag, String message, Throwable ex, boolean printStackTrace)
Trace.log(String,String,Throwable,int)
insteadtag
- A trace tag: if an agent can't be found in scope this is ignoredmessage
- The message to logex
- If ex is not null, the stack dump is appended to the message.printStackTrace
- set to true to print a stack trace (note that if ex is not null, the trace will be printed anyway).Trace.log(String, String)
,
getAbstractProcessInScope()
@Deprecated static String makeLogHeader(String tag)
public static LispObject toCons(String... strings)
strings
- the strings that will form the atoms in the cons list.public static Object callMethod(Class<?> cls, String methodName, Object target, Class<?>[] paramTypes, Object[] params) throws NoSuchMethodException, InvocationTargetException, IllegalArgumentException, IllegalAccessException, NullPointerException, SecurityException, ExceptionInInitializerError
try { CASAUtil.callMethod(Class.forName("com.apple.mrj.MRJFileUtils"), "openURL", null, new Class[]{String.class}, new Object[]{url}); } catch(Throwable ex) {}
cls
- The class of target object. If cls is null, but target is specified, then cls is assumed to be the runtime type of target.methodName
- The name of the method to invoke.target
- The object on which to call this method. May be null if this is a methodName is the name of a static method.paramTypes
- The types of the arguments.params
- The argumentsNoSuchMethodException
InvocationTargetException
IllegalArgumentException
IllegalAccessException
NullPointerException
SecurityException
ExceptionInInitializerError
public static TransientAgent startAnAgent(Class<?> theClass, String agentName, int port, Runnable1<TransientAgent,Void> code, String... argPairs)
theClass
- The class of the agent to start.agentName
- The name of the new agent.port
- The port for the new agent.code
- The code to execute once the agent starts up -- it will be passed the actual agent.argPairs
- key/value pairs of arguments to pass in the agent's constructor (must be even).public static String getPID()