com.cloudtran.util
Class Utils

java.lang.Object
  extended by com.cloudtran.util.Utils

public class Utils
extends Object

Utils static block must not call Trace.log or any trace functions


Nested Class Summary
static class Utils.Pair
          Tuples
static class Utils.Triple
           
 
Field Summary
static char ADDSTART
           
static String ADDSTARTSTRING
           
static String CONFIG_PROPS_NAME
           
static IConfigPropertiesReader configReader
           
static char CR
           
static String defaultCharsetName
           
static char DOUBLENULLLINEDELETER
           
static String DOUBLENULLLINEDELETERSTRING
           
static char ENDSTART
           
static String ENDSTARTSTRING
           
static String fileSep
           
static char fileSepChar
           
static boolean isDOS
           
static boolean isUNIX
           
static int KEEPCOMPILERHAPPY_INT
           
static String lineSep
           
static char lineSepChar0
           
static String manySpaces
           
static int manySpacesLen
           
static String N_STARS
           
static String N_STARS_N
           
static char NL
           
static String NN_STARS
           
static String NN_STARS_N
           
static int NULL_INT
           
static long NULL_LONG
           
static short NULL_SHORT
           
static char NULLLINEDELETER
           
static String NULLLINEDELETERSTRING
           
static String pathSep
          From jeewiz /
static char pathSepChar
           
static String STARS
           
static String STARS_N
           
static Properties systemProperties
           
static char theOtherWorldsFileSepChar
           
static char UNINDENT
           
static String UNINDENTSTRING
           
 
Constructor Summary
Utils()
           
 
Method Summary
static void acquireSemaphore(Semaphore semaphore)
          acquires a semaphore, throwing CTInterruptedException (unchecked) when interrupted.
static void acquireSemaphore(Semaphore semaphore, int permits)
           
static List addLists(List a, List b)
           
static String addUniqueCSStrings(String string1, String string2)
          Add two unique comma-separated strings, and ensures that the result has unique entries - i.e.
static String appendToUniqueCSString(List uniqueList, String extraCSItems)
          Append a comma-separated string to a List of Unique strings, and ensures that the result has unique entries - i.e.
static boolean areBinaryFilesEqual(File f1, File f2)
          areBinaryFilesEqual was written as areFilesEqual by Soren Bak.
static String arrayListToCsv(ArrayList<String> alIn)
           
static String arrayListToCsv(ArrayList<String> alIn, String separator, String delimiter)
          arrayListToCsv produces a single string in CSV format from some fields, represented as an ArrayList of Strings.
static String buildCSString(List stringList)
          Builds a comma separated string from a List containing either Strings or CDataAttribute objects (one CDataAttribute object is created by JeeWiz to read each <description> element.
static String capitalise(String inputString)
          Returns the input string as is, except that if the first letter is lower-case, it is converted to upper case.
static String capitalize(String inputString)
          Synonym for capitalise.
static String changeString(String inputString, String separators, String toThis)
          Internal - Don't use - doesn't do what it says on the tin - only works on single-character items.
static String checkXsdDate(String s)
          Checks that a string, supposedly a valid XML Date, can be converted into a Calendar object.
static String checkXsdDateTime(String s)
          Checks that a string, supposedly a valid XML DateTime, can be converted into a Calendar object.
static String checkXsdTime(String s)
          Checks that a string, supposedly a valid XML Time, can be converted into a Calendar object.
static int compareStringNumbers(String s1, String s2)
          Calls BigInteger.compareTo for BigIntegers constructed from s1 and s2
static
<T> T[]
concatArray(T[] firstArray, T[] secondArray)
          Concatenates two arrays, either of which may be null or empty.
static ArrayList convertStringToLines(String input)
          Converts the input string to an ArrayList of lines.
static ArrayList<String> csvToArrayList(String csv)
          Takes a CSV string, with ',' as the separator and " as the string delimiter and converts it into an ArrayList
static ArrayList<String> csvToArrayList(String csv, String separator, String delimiter)
          This takes as input a string in CSV (Comma-Separated Value) format and turns it an ArrayList of the Strings it contains.
static String decapitalize(String inputString)
          This method implements the JavaBeans 'decapitalize' method, which is - if the first two letters of a variable name are upper case, leave them unchanged (e.g.
static String dumpObject(Object objectToDump)
          This is a variant of the 'dumpObject' method, which has no initial indentation and three spaces for each nested level of objects.
static String dumpObject(Object objectToDump, int maxInList)
          This is a variant of the 'dumpObject' method, which has no initial indentation and three spaces for each nested level of objects.
static String dumpObject(Object objectToDump, String initialIndent, String indentIncrement)
          This method dumps the object in a "nice format" - that takes account of the Java Collections Framework, particularly objects that implement Map and List - adding newLines and key/value separation, to aid readability.
static String dumpObject(Object objectToDump, String initialIndent, String indentIncrement, int maxInList)
           
static String dumpStringWithControlChars(String s)
          Dumps a string with JeeWiz-specific control character names.
static String dumpStringWithCRLF(String s)
           
static void dumpStringWithHighlightedControlChars(String s)
           
static void dumptTxIFPAndStorer(TransactionInfoForPersistor txIFP, ICloudTranStorer storer, String message)
           
static void dumpTxIFP(TransactionInfoForPersistor txIFP, String message)
           
static void error(String msg)
          Traces an error message and then throws a RuntimeException with message = the input message
static void error(String msg, Exception e)
          Traces an error message and the input exception, and then throws a RuntimeException with message = the input message and a nested exception.
static void exit()
          exit() calls System.exit() with a 0 exitStatus parameter - which indicates successful execution.
static void exit(int exitStatus)
          exit( int ) calls System.exit() with the exitStatus parameter
static void exit(long exitStatus)
          exit( long ) calls System.exit() with the exitStatus parameter, throwing away any high-order bits
static void exit(String errorMessage)
          exit( String errorMessage ) writes the errorMessage to the error log and then exits (i.e.
static void exit1()
           
static void exitOrContinue()
          This exits in non-production mode, and continues in production
static void exitOrContinue(String message)
          This exits in non-production mode, and continues in production
static void exitOrContinue(String message, Exception e)
           
static void fatalConfigError(String errmsg)
           
static void fatalConfigError(String errmsg, Exception e)
           
static void fatalError(String errmsg, Exception e)
           
static void fatalInternalError(Exception e)
           
static void fatalInternalError(String errmsg)
           
static void fatalInternalError(String errmsg, Exception e)
           
static boolean fileIsAbsolute(String path)
          Returns true if the input path represents an absolute.file.
static int firstIndexOf(String source, String findChars)
          Search for the first occurrence of one of the characters in findChars in source string.
static String firstLetterCaps(String inputString)
          Synonym for capitalise.
static String firstValue(String s1, String s2)
          Returns the first 'real value' of the two inputs.
static String firstValue(String s1, String s2, String s3)
          Returns the first 'real value' of the three inputs.
static String formatNumericString(String str)
          formatNumericString formats a string, presumed to be integral and a valid Long number, using the current locale's standards, and in groups.
static String formatNumericString(String str, Locale locale)
          formatNumericString formats a string, presumed to be integral and a valid Long number, using the locale parameter's standards, and in groups.
static String generateIncrementalNumberString(String start, String end, String interval, String separator)
           
static String getAbsolutePath(File f)
          Returns Java's File.getAbsolutePath() value for the input file.
static String getAbsolutePath(String s)
          Uses the input file name as a constructor for a file and then calls Java's File.getAbsolutePath().
static int getAndSetConfigPropertyD(String propertyName, String defaultValue)
          Get a configProperty using Utils.getConfigPropertyD and then set that value back into the property.
static String getBasename(String path)
          Get the filename part - after the last '/' or '\' - from a path string.
static Boolean getBooleanFalse()
          returns a Boolean false value, which is the same as "false" in Velocity.
static Boolean getBooleanTrue()
          returns a Boolean true value, which is the same as "true" in Velocity.
static String getCallersStackTrace()
          If methodA() calls methodB() which calls getCallersStackTrace(), this method will report the stack trace at methodA().
static String getCanonicalPath(File f)
          Returns Java's File.getCanonicalPath.
static String getCanonicalPath(String fileName)
          Returns the Java File canonical path (i.e.
static String getCapsAndSeparatorName(String externalName, char separator)
          internal
static String getCapsAndSeparatorName(String externalName, String separator)
          getCapsAndSeparatorName converts 'externalName' to Java Class format, then adds 'separator' before each capital letter in the external name if - it is preceded by a lower-case or numeric letter, or - it is the last in the sequence of capital letters and followed by a lower-case letter.
static String getCapsAndSpacesName(String externalName)
          getCapsAndSpacesName is a wrapper for getCapsAndSeparatorName, using space as the separator.
static String getCapsAndUnderscoreName(String externalName)
          getCapsAndUnderscoreName is a wrapper for getCapsAndSeparatorName, using underscore as the separator.
static int getCharacterCount(String s, char c)
          internal Gets the number of occurrences of the character 'c' in the string 's'.
static int getCharacterCount(String s, String c)
          Gets the number of occurrences of the first character of 'c' in the string 's'.
static String getClassSafe(Object object)
           
static Class getConfigClass(String propertyName)
          This helper method tries to get a class by using the value of the property and then doing a Class.forName() on thevalue.
static Class getConfigClass(String propertyName, String defaultClassName)
          This helper method tries to get a class by using the value of the property and then doing a Class.forName() on thevalue.
static Object getConfigClassInstance(String propertyName)
          This helper method tries to get a class instance object by using the value of the property and then doing a Class.forName() on the class.
static Object getConfigClassInstance(String propertyName, String defaultClassName)
          This helper method tries to get a class instance object by using the value of the property and then doing a Class.forName() on thevalue.
static Object getConfigClassInstance(String propertyName, String defaultClassName, Class[] constructorSignature, Object[] arguments)
          This helper method tries to get a class instance object by using the value of the property and then looks up the constructor based on the value.
static Object getConfigClassInstance(String propertyName, String defaultClassName, Class implementedInterface, boolean required)
          This helper method is like the 2-parameter version of getConfigClassInstance, but additionally adds - an optional default for the property (can be null) - an optional interface class the class instance implements (can be null) - whether a value is required or not.
static Properties getConfigPropertiesMatched(String regExp)
          Get a list of config properties, subsetted from getConfigProperties(), whose property names match the regular expression input.
static Properties getConfigPropertiesStartingWith(String prefix)
          Get a list of config properties, subsetted from getConfigProperties(), whose property names begin with the input string.
static String getConfigProperty(String propertyName)
          This method is almost obsolete - because config properties are now available via System.getProperty.
static boolean getConfigProperty(String propertyName, boolean defaultValue)
          This helper method gets a Boolean config property, returning a Boolean default value if the config value is not specified.
static int getConfigProperty(String propertyName, int defaultValue)
          This helper method gets an int config property, returning the int default value if the config value is not specified or is empty.
static int getConfigProperty(String propertyName, int defaultValue, int minValue, int maxValue)
          This helper method gets an int config property, returning the int default value if the config value is not specified or is empty.
static String getConfigProperty(String propertyName, String defaultValue)
          This helper method gets a config property, returning a default value if the config value is not specified.
static String[] getConfigPropertyArray(String propertyName, String defaultValue)
          Get an array of Strings, based on a String property holding a comma-separated list.
static int getConfigPropertyD(String propertyName, String defaultValue)
          "int getConfigPropertyD()" is like getConfigProperty() - gets an int config property.
static int getConfigPropertyD(String propertyName, String defaultValue, int minValue, int maxValue)
          Get a configProperty using Utils.getConfigPropertyD and then do min/max checks.
static int[] getConfigPropertyIntArray(String propertyName, String defaultValue)
          Get an array of int's, based on a String property holding a comma-separated list.
static String getDirname(String path)
          Get the directory part - up to but not including the last '/' or '\' - from a path string.
static String getEOLString(String inputString)
          getEOLString gets the first EOL (end of line) string in the input string.
static String getExceptionAsString(Exception e)
           
static File getFile(File dir, String fileName)
          Returns a Java File from the fileName, i.e.
static File getFile(String path)
          Returns a Java File from the path, i.e.
static File getFile(String dirPath, String fileName)
          Returns a Java File from the fileName, i.e.
static String getFileSeparator()
          Returns the file separator, either '/' for UNIX or '\' for Windows.
static String getFirstPieceOf(String inputString, char separator)
          internal getFirstPieceOf gets the first piece of the inputString
static String getFirstPieceOf(String inputString, String separator)
          getFirstPieceOf gets the first piece of the inputString - this variant takes a string to delimit the pieces rather than a character.
static String getIndentStartBody()
           
static String getIndentStartHeader()
           
static boolean getIsDOS()
          Returns true if on DOS (Windows)
static boolean getIsUNIX()
          Returns true if on UNIX or Linux.
static boolean getIsWindows()
          Returns true if on Windows
static String getJavaClassName(String inputName)
          Converts from an XML name to a Java class-style name.
static String getJavaName(String inputName, boolean capitaliseFirstCharacter)
          Converts from an XML name to a Java class or variable name, depending on the setting of capitaliseFirstCharacter.
static String getJavaVarName(String inputName)
          Converts from an XML name to a Java variable-style name.
 String getJaxbAttributeName(String xmlName)
          get the Jaxb attribute name in Java from the xml name.
static String getLastPieceOf(String inputString, char separator)
          internal getLastPieceOf gets the last piece of the inputString
static String getLastPieceOf(String inputString, String separator)
          getLastPieceOf gets the last piece of the inputString
static String getLF()
           
static String getLineSeparator()
          Returns the appropriate line separator for UNIX (\n) or Windows (\r\n).
static String getLocalName(String qName)
          Returns the local-part name from an XML Qname.
static Matcher getMatcher(String regex, String text)
          Utility method to get a matcher based on regex - a regular expression string - match against the input text parameter.
static String getMyPid()
           
static ArrayList getNewArrayList(int n)
          Returns a new ArrayList with an initial capacity of n.
static Utils.Pair getNewPair()
           
static Utils.Pair getNewPair(Object v1, Object v2)
           
static Utils.Triple getNewTriple()
           
static Utils.Triple getNewTriple(Object v1, Object v2, Object v3)
           
static String getNull()
          This returns a null, as an easy way to get a null value in Velocity - use $null.
static String getPathSeparator()
          Returns the path separator, either ':' for UNIX or ';' for Windows.
static Pattern getPattern(String regex)
          call the regex Pattern compile() method to get a pattern object.
static String getPieceOf(String inputString, char separator, int pieceNumber)
          internal getPiece of gets a numbered piece of a string - see the other version for documentation
static String getPieceOf(String inputString, String separator, int pieceNumber)
          getPieceOf in this form gets a numbered piece of a string.
static String getPieceOf(String inputString, String leftSeparator, String rightSeparator)
          getPieceOf gets a piece of the inputString, separated by delimiters.
static ArrayList getPieces(String inputString, String separator)
          getPieces gets the pieces of the inputString before the last.
static ArrayList getPieces(String inputString, String separator, boolean removeEmptyPieces)
          getPieces gets the pieces of the inputString before the last.
static String getPlatformPath(File f)
          Returns the input file as a path in a standard, absolute format for the input file, suitable for error messages and for specifying to other tools on this platform.
static String getPlatformPath(String fileName)
          Returns the input file name as a path in a standard, absolute format for the indicated file, suitable for error messages and for specifying to other tools on this platform.
static String getPrefix(String qName)
          Return the prefix from an XML QName.
static String getPreLastPieceOf(String inputString, String separator)
          getPreLastPieceOf gets the pieces of the inputString before the last.
static String getRelativePath(String path, String baseDirectory)
          getRelativePath returns a path, relative to a base directory, if possible.
static String getRelativePath(String path, String baseDirectory, int nLevels)
          getRelativePath returns a path, relative to a base directory, if possible.
static String getRelativePathBS(String path, String baseDirectory)
          Returns the same as getRelativePath, but with any '/' changed to '\' (for Windows).
static String getRelativePathBS(String path, String baseDirectory, int nLevels)
          Returns the same as getRelativePath, but with any '/' changed to '\' (for Windows).
static String getResolvedPathFrom(String path, String baseDir)
          The input path is one or more path elements separated by the platform path separator (';' or ':') or ",".
static String getSingleLineText(String description)
          This method converts from an internal String value (e.g.
static String getStackTraceAsString(StackTraceElement[] stackTrace)
           
static Properties getSystemProperties()
          returns the system properties, i.e.
static Properties getSystemPropertiesClone()
           
static String getUnindent()
           
static String getUniqueKey(String baseKey, Map map)
          getUniqueKey with two parameters is a variant of the three-parameter method.
static String getUniqueKey(String baseKey, Map map, Object entryValue)
          getUniqueKey gets a unique key for a map, starting with the baseKey string.
static String getUnixPath(File f)
          Returns Java's File.getCanonicalPath for the input file, but using '/' as the path separator.
static String getUnixPath(String fileName)
          Creates a File using the input file name in the constructor, then returns Java's File.getCanonicalPath for the file, but using '/' as the path separator.
static String getUUID()
          Get a random UUID.
static String getUUID(String hostName)
          This is present for backward compatibility.
static String getValueForTracing(Object rv)
           
static String getWindowsPath(File f)
          Returns Java's File.getCanonicalPath for the input file, but using '\' as the path separator.
static String getWindowsPath(String fileName)
          Creates a File using the input file name in the constructor, then returns Java's File.getCanonicalPath for the file, but using '\' as the path separator.
 String getXmlLocalPart(String s)
          getXmlLocalPart gets the xml local part from the input string.
static String getXmlName(String inputName)
          Converts the input name into 'standard XML' format.
static String getXMLName(String inputName)
          Synonym for 'getXmlName'
 String getXmlPrefix(String s)
          getXmlPrefix gets the xml prefix from the input string.
static Calendar getXsdDateAsCalendar(String s)
          Gets an XML Schema date string into a calendar object.
static String getXsdDateFromCalendarAsString(Calendar calendar)
           
static Calendar getXsdDateTimeAsCalendar(String s)
          Gets an XML Schema dateTime string into a calendar object.
static String getXsdDateTimeFromCalendarAsString(Calendar calendar)
           
static Calendar getXsdTimeAsCalendar(String sIn)
          Gets an XML Schema time string into a calendar object.
static String getXsdTimeFromCalendarAsString(Calendar calendar)
           
static String indent(String multiline, String indent)
           
static boolean isAfter(long t1, long t2)
           
static boolean isBefore(long t1, long t2)
          This compares two times t1 and t2 and deduces whether t1 is 'before' t2 (in the 'happensBefore' Java concurrent sense of the term).
static boolean isDirectory(String fileName)
          Returns true if the fileName represents a directory.
static boolean isFile(String fileName)
          Returns true if the fileName represents a normal file.
static boolean isLessThanUnsigned(long n1, long n2)
          Implements an unsigned comparison in Java.
static int javaFindCommentEnd(String text, int fromIndex)
          Find the index of the end of a quote.
static int javaFindEndSeparator(String text)
          Find the matching separator of paired Java separators.
static int javaFindEndSeparator(String text, int fromIndex)
          Find the matching separator of paired Java separators.
static int javaFindMatchingQuote(String text, int fromIndex)
          Find the matching quote character, single-quote or double-quote to end a Java String literal.
static int javaFindText(String textToSearch, int fromIndex, String textToFind)
          finds the specified 'textToFind' string in the 'textToSearch', starting from 'fromIndex'.
static long leadCharCount(String inputString, String firstChar)
          This takes a one-character string If the firstChar parameter string is not a string of length 1 then the method returns 0.
static String leftJustify(String s, int n)
          Returns a string 'n' spaces long, up to a maximum of 600 or so.
static String list(String list, String sep, List listOfStrings)
           
static String list(String input, String separator, String addon)
          Returns a concatenated list.
static String list(String list, String sep, String addon, String addon2)
           
static String list(String list, String sep, String addon, String addon2, String addon3)
           
static String list(String list, String sep, String addon, String addon2, String addon3, String addon4)
           
static String list(String list, String sep, String addon, String addon2, String addon3, String addon4, String addon5)
           
static String list2String(List listOfStrings, String sep)
           
static String lowerCaseOnSecond(String inputString)
          Returns the input string as is, except that if the *second* letter is upper-case, ALL characters are converted to lower case.
static String mapChar(char c)
           
static String multiplyString(String value, int multiplier)
          returns the value string, multiplied by 'multiplier'.
static String nullableIntToString(Integer n)
           
static String nullableIntToString(Short n)
           
static String nullableLongToString(Long n)
           
 String parseFormat(String format, String fControl, String fTerm)
          parseFormat - Similar to parseFormat in the uiBase jwControl, this is to make the same functionality available for .vms
static
<E> E
pollLinkedBlockingQueue(LinkedBlockingQueue<E> queue, long timeout, TimeUnit unit)
           
static String processSpecialCharacters(String resultString)
          Processes the JeeWiz special characters INDENTSTART etc.
static Map projectMap(Map mapFrom, Object objectToMap)
           
static Map projectMap(Map mapFrom, Object objectToMap, Map targetMap)
          Internal When we are picking up a lot values from files, it is useful to know the source So this routine projects an object (e.g.
static
<E> void
putOnLinkedBlockingQueue(LinkedBlockingQueue<E> queue, E entry)
           
static ArrayList readFileAsLines(File file)
          Reads 'file' as an ArrayList of lines.
static ArrayList readFileAsLines(String fileName)
          readFileAsLines returns the contents of a file as a String.
static String readFileAsString(File file)
          Reads 'file' as a String.
static String readFileAsString(String fileName)
          readFileAsString returns the contents of a file as a String.
static Properties readPropertiesFile(File file)
          readPropertiesFile returns the contents of a file as a java.util.Properties.
static Properties readPropertiesFile(String fileName)
          readPropertiesFile returns the contents of a file as a java.util.Properties.
static Properties readPropertiesResources(String resourceName)
          readPropertiesResource returns the contents of the named resource as a java.util.Properties.
static String readUrlAsString(String resourceAbsolutePath)
          Looks up 'resourceAbsolutePath' as a URL resource in the class path and reads it as a string.
static void releaseSemaphore(Semaphore semaphore)
           
static String removeChars(String data, String unwantedChars)
          Remove unwanted characters from a data string.
static void removeCSListDuplicates(List list)
          Removes any duplicate or null strings from 'list' - an ArrayList containing strings or CDataAttribute objects
static String removeDash(String data)
          Internal Remove dashes from a string but leave the capitalization of the other letters unchanged.
static String removeFirstPieceOf(String inputString, String separator)
          removeFirstPieceOf removes the first piece of the input string, based on the given separator.
static String removePunctuationAndCapitalise(String inputString)
          removePunctuationAndCapitalise takes away the punctuation from a string and capitalises the character after one or more separators.
static String removeSpaces(String s)
          Converts a string with spaces to one without.
static String removeSpacesCapitalise(String s)
          Converts a string to a string in the Java variable name style, i.e.
static String removeSpacesProperCase(String s)
          Converts a string to a string in the Java variable name style, i.e.
static String removeString(String inputString, String separators)
          removeString takes away the separators from a string and capitalises the character after a separator.
static String removeStringNoCapital(String inputString, String separators)
          Takes away the separators from a string.
static String removeTrailingWhitespace(String inputString)
           
static String removeUnwantedChars(String data)
          Internal Remove unwanted characters '$', '.' and '!' from the input data - AND REPLACE WITH '_'.
static Properties resetConfigProperties()
          Reset the config properties to the initial (start of day) state.
static String rightJustify(String s, int n)
          Returns a string 's' in a field of 'n' characters wide.
static String separateByCapitals(String inputString)
          This takes an input string and splits it before a capital, by inserting a space.
static void setConfigProperty(String key, String value)
          This method is documented - but just delegates to System.setProperty.
static void sleepNoException(long millis)
          Sleep for the target milliseconds.
static void sleepNoExceptionMicros(int micros)
          Sleep for the target milliseconds.
static String spaces(int n)
          Returns a string 'n' spaces long, up to a maximum of 600 or so.
static String spaces(String s)
          Returns a string as long as the input string, up to a maximum of 600 characters or so, but filled with spaces.
static String spaces1(int n)
          Returns a string 'n' spaces long, up to a maximum of 600 or so.
static ArrayList<String> splitCSString(String csString)
          Splits up a comma separated string, returning the resulting tokens (substrings) between the comma's in a List.
static ArrayList splitCSStringWithoutDuplicates(String csString)
          Like 'splitCSString' but with any duplicates removed If the input string 'csString' is null or zero-length, a List with no items is returned.
static ArrayList splitSeparatorString(String stringToSplit, String delimiters)
          Splits up the string 'stringToSplit' into tokens based on the provided delimiters, with the resulting tokens trimmed (as in 'String.trim()').
static ArrayList splitSeparatorString(String stringToSplit, String delimiters, boolean returnDelims)
          Splits up the string 'stringToSplit' into tokens based on the provided delimiters with the resulting tokens trimmed (as in 'String.trim()').
static ArrayList splitStringIntoTwo(String stringToSplit, String separatorString)
          splitStringIntoTwo() splits a string based on a separator string.
static String stackTraceToString()
          returns the callers stackTrace (in Throwable stack trace format - with " at " prefix).
static String stackTraceToString(int stackIndex)
          returns the callers stackTrace (in Throwable stack trace format - with " at " prefix).
static String stackTraceToString(Throwable e)
          returns the callers stackTrace (in Throwable stack trace format - with " at " prefix).
static boolean stringNumberEqual(String s1, String s2)
          Arbitrary precision number comparison.
static boolean stringNumberGreater(String s1, String s2)
          Arbitrary precision number comparison.
static boolean stringNumberGreaterOrEqual(String s1, String s2)
          Arbitrary precision number comparison.
static boolean stringNumberLess(String s1, String s2)
          Arbitrary precision number comparison.
static boolean stringNumberLessOrEqual(String s1, String s2)
          Arbitrary precision number comparison.
static String stringReplace(String inputString, String from, String to)
          stringReplace - exists because String.replace uses characters and Velocity doesn't support characters.
static String stringToCDATAsection(String s)
          generates a CDATA section holding the trimmed input 's', as long as s is not null or empty or whitespace only.
static String stringToXMLAttr(String s)
          stringToXMLAttr(s) converts the input string 's' from an string value into an XML attribute, including the appropriate quotes ('' or "") and &'s etc converted to '&' etc.
static String stringToXMLAttrWithoutQuotes(String s)
          Returned value is same as stringToXMLAttr, but without the enclosing quotes.
static String stringToXMLCharacterData(String s)
          generate XML character data.
static String stringWithinCData(String s)
          generate characters within a CData section.
static List subtractList(List biggerList, List subtractedList)
           
static
<E extends Delayed>
E
takeFromDelayQueue(DelayQueue<E> dq)
           
static
<E> E
takeFromLinkedBlockingQueue(LinkedBlockingQueue<E> queue)
           
static String toHTML(String inputLine)
          'toHTML' is used to create HTML documentation from a simple layout.
static String uncapitalise(String inputString)
          Returns the input string as is, except that if the first letter is upper-case, it is converted to lower case.
static String uncapitaliseInitialGroup(String inputString)
          Returns the input string uncapitalising all but the last of a leading group of capital letters.
static String uncapitaliseSecond(String inputString)
          Returns the input string as is, except that if the *second* letter is upper-case, it is converted to lower case.
static String uncapitalize(String inputString)
          Synonym for uncapitalise
static void writeStringToFile(File file, String stringToWrite)
          writeStringToFile writes the contents of a String to a file using the default character encoding.
static void writeStringToFile(File file, String stringToWrite, String encoding)
          writeStringToFile writes the contents of a String to a file the specified character encoding.
static void writeStringToFile(String fileName, String stringToWrite)
          writeStringToFile writes the contents of the stringToWrite parameter to a file using the default character encoding.
static void writeStringToFile(String fileName, String stringToWrite, String encoding)
          writeStringToFile writes the contents of a String to a file using the specified character encoding.
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

NULL_LONG

public static final long NULL_LONG
See Also:
Constant Field Values

NULL_INT

public static final int NULL_INT
See Also:
Constant Field Values

NULL_SHORT

public static final short NULL_SHORT
See Also:
Constant Field Values

KEEPCOMPILERHAPPY_INT

public static final int KEEPCOMPILERHAPPY_INT
See Also:
Constant Field Values

STARS

public static final String STARS
See Also:
Constant Field Values

N_STARS

public static final String N_STARS
See Also:
Constant Field Values

NN_STARS

public static final String NN_STARS
See Also:
Constant Field Values

NN_STARS_N

public static final String NN_STARS_N
See Also:
Constant Field Values

STARS_N

public static final String STARS_N
See Also:
Constant Field Values

N_STARS_N

public static final String N_STARS_N
See Also:
Constant Field Values

CONFIG_PROPS_NAME

public static final String CONFIG_PROPS_NAME
See Also:
Constant Field Values

configReader

public static IConfigPropertiesReader configReader

systemProperties

public static final Properties systemProperties

pathSep

public static final String pathSep
From jeewiz /


pathSepChar

public static final char pathSepChar

isUNIX

public static final boolean isUNIX

isDOS

public static final boolean isDOS

fileSep

public static final String fileSep

fileSepChar

public static final char fileSepChar

theOtherWorldsFileSepChar

public static final char theOtherWorldsFileSepChar

lineSep

public static final String lineSep

lineSepChar0

public static final char lineSepChar0

ADDSTART

public static final char ADDSTART
See Also:
Constant Field Values

ADDSTARTSTRING

public static final String ADDSTARTSTRING
See Also:
Constant Field Values

ENDSTART

public static final char ENDSTART
See Also:
Constant Field Values

ENDSTARTSTRING

public static final String ENDSTARTSTRING
See Also:
Constant Field Values

UNINDENT

public static final char UNINDENT
See Also:
Constant Field Values

UNINDENTSTRING

public static final String UNINDENTSTRING
See Also:
Constant Field Values

NULLLINEDELETER

public static final char NULLLINEDELETER
See Also:
Constant Field Values

NULLLINEDELETERSTRING

public static final String NULLLINEDELETERSTRING
See Also:
Constant Field Values

DOUBLENULLLINEDELETER

public static final char DOUBLENULLLINEDELETER
See Also:
Constant Field Values

DOUBLENULLLINEDELETERSTRING

public static final String DOUBLENULLLINEDELETERSTRING
See Also:
Constant Field Values

NL

public static final char NL
See Also:
Constant Field Values

CR

public static final char CR
See Also:
Constant Field Values

defaultCharsetName

public static final String defaultCharsetName

manySpaces

public static final String manySpaces
See Also:
Constant Field Values

manySpacesLen

public static final int manySpacesLen
Constructor Detail

Utils

public Utils()
Method Detail

nullableLongToString

public static String nullableLongToString(Long n)

nullableIntToString

public static String nullableIntToString(Integer n)

nullableIntToString

public static String nullableIntToString(Short n)

getSystemPropertiesClone

public static Properties getSystemPropertiesClone()

resetConfigProperties

public static Properties resetConfigProperties()
Reset the config properties to the initial (start of day) state. This allows config property settings to be tested in test frameworks like JUnit.

This method discards all the properties set after start of day, or after a previous resetConfigProperties(). All system properties, such as those set by '-D' command-line options, are retained.

Custom config properties set via the config properties are also reloaded, by calling the {link ConfigPropertiesReader.

Returns:
the customized start-of-day properties, which is also the System.getProperties() object.

setConfigProperty

public static void setConfigProperty(String key,
                                     String value)
This method is documented - but just delegates to System.setProperty. In other words, properties added by this method go straight into System.properties.

Properties set in System.properties after CloudTran has initialized (and custom properties read) can be reinitialized by calling resetConfigProperties();


getConfigProperty

public static String getConfigProperty(String propertyName)
This method is almost obsolete - because config properties are now available via System.getProperty. Any custom properties (e.g. set via the config.properties mechanism) are added to the system properties. However, this method trims whitespace (i.e. String.trim()) from the returned value; in some JVMs, this doesn't happen ... and whitespace should be irrelevant in properties.


getConfigProperty

public static String getConfigProperty(String propertyName,
                                       String defaultValue)
This helper method gets a config property, returning a default value if the config value is not specified. If there is no config.properties file or the property is not present, this returns defaultValue.


getConfigProperty

public static int getConfigProperty(String propertyName,
                                    int defaultValue)
This helper method gets an int config property, returning the int default value if the config value is not specified or is empty. If there is no config.properties file or the property is not present, this returns defaultValue.


getConfigPropertyD

public static int getConfigPropertyD(String propertyName,
                                     String defaultValue)
"int getConfigPropertyD()" is like getConfigProperty() - gets an int config property. It differs in that the value in the file and the default value specified here can be of the format "n/m", where n and m are integers. If Trace.DEBUG is *not* set, then the first number - 'n' - is used. In DEBUG runs, 'm' is used. returning the int default value if the config value is not specified or is empty. If there is no config.properties file or the property is not present, this returns defaultValue.


getAndSetConfigPropertyD

public static int getAndSetConfigPropertyD(String propertyName,
                                           String defaultValue)
Get a configProperty using Utils.getConfigPropertyD and then set that value back into the property.


getConfigProperty

public static int getConfigProperty(String propertyName,
                                    int defaultValue,
                                    int minValue,
                                    int maxValue)
This helper method gets an int config property, returning the int default value if the config value is not specified or is empty. If there is no config.properties file or the property is not present, this returns defaultValue. The result value must be >= minValue and <= maxValue. The default, min and max values are independent of the DEBUG state in the code; in .


getConfigPropertyD

public static int getConfigPropertyD(String propertyName,
                                     String defaultValue,
                                     int minValue,
                                     int maxValue)
Get a configProperty using Utils.getConfigPropertyD and then do min/max checks.

Throws:
RuntimeException - if the default value is incorrectly specified or if the return value is out of bounds.

getConfigPropertyArray

public static String[] getConfigPropertyArray(String propertyName,
                                              String defaultValue)
Get an array of Strings, based on a String property holding a comma-separated list.


getConfigPropertyIntArray

public static int[] getConfigPropertyIntArray(String propertyName,
                                              String defaultValue)
Get an array of int's, based on a String property holding a comma-separated list. Throws a runtime exception if the strings are not numbers. If there's no default and no value is specified in config properties, then a 0-length array is returned It is possible for this to return a 0-length array.


getConfigProperty

public static boolean getConfigProperty(String propertyName,
                                        boolean defaultValue)
This helper method gets a Boolean config property, returning a Boolean default value if the config value is not specified. If there is no config.properties file or the property is not present, this returns defaultValue. The only true string for Boolean is "true", case-sensitive, i.e. this will return true myProperty=true but this will return false myProperty=True


getConfigPropertiesMatched

public static Properties getConfigPropertiesMatched(String regExp)
Get a list of config properties, subsetted from getConfigProperties(), whose property names match the regular expression input. For example, if regExp == "datasource[.][^.]+[.]url" this will pull out all datasource url properties - e.g. those with names like "datasource.ds1.url". For non-pathological cases (i.e. where getConfigProperties() blows up), a different, non-null Properties object is returned for each call.


getConfigPropertiesStartingWith

public static Properties getConfigPropertiesStartingWith(String prefix)
Get a list of config properties, subsetted from getConfigProperties(), whose property names begin with the input string. For example, if input == "ct.coherence.mvcc." this will return all properties - like "ct.coherence.mvcc.test=true" - where the property name begins with (or is) "ct.coherence.mvcc".


getConfigClass

public static Class getConfigClass(String propertyName)
This helper method tries to get a class by using the value of the property and then doing a Class.forName() on thevalue. If there is no config.properties file or the property is not present, this returns null. If there is a property value but there is a problem loading the class, this will throw the RuntimeException - which typically need not be caught.


getConfigClass

public static Class getConfigClass(String propertyName,
                                   String defaultClassName)
This helper method tries to get a class by using the value of the property and then doing a Class.forName() on thevalue. If there is no config.properties file, then the provided default class name is used. If both are null, null is returned. If there is a problem loading the class, this will throw the RuntimeException - which typically need not be caught.


getConfigClassInstance

public static Object getConfigClassInstance(String propertyName)
This helper method tries to get a class instance object by using the value of the property and then doing a Class.forName() on the class. If there is no config.properties file or the property is not present, this returns null. If there is a property value but there is a problem loading the class, this will throw the RuntimeException - which typically need not be caught.


getConfigClassInstance

public static Object getConfigClassInstance(String propertyName,
                                            String defaultClassName)
This helper method tries to get a class instance object by using the value of the property and then doing a Class.forName() on thevalue. If there is no config.properties file, then the provided default class name is used. If there is a problem loading the class, this will throw the RuntimeException - which typically need not be caught.


getConfigClassInstance

public static Object getConfigClassInstance(String propertyName,
                                            String defaultClassName,
                                            Class[] constructorSignature,
                                            Object[] arguments)
This helper method tries to get a class instance object by using the value of the property and then looks up the constructor based on the value. If there is no config.properties file, then the provided default class name is used. If there is a problem loading the class, this will throw the RuntimeException - which typically need not be caught.


getConfigClassInstance

public static Object getConfigClassInstance(String propertyName,
                                            String defaultClassName,
                                            Class implementedInterface,
                                            boolean required)
This helper method is like the 2-parameter version of getConfigClassInstance, but additionally adds - an optional default for the property (can be null) - an optional interface class the class instance implements (can be null) - whether a value is required or not. The property name itself cannot be null.


acquireSemaphore

public static void acquireSemaphore(Semaphore semaphore)
acquires a semaphore, throwing CTInterruptedException (unchecked) when interrupted.


acquireSemaphore

public static void acquireSemaphore(Semaphore semaphore,
                                    int permits)

releaseSemaphore

public static void releaseSemaphore(Semaphore semaphore)

takeFromDelayQueue

public static <E extends Delayed> E takeFromDelayQueue(DelayQueue<E> dq)

takeFromLinkedBlockingQueue

public static <E> E takeFromLinkedBlockingQueue(LinkedBlockingQueue<E> queue)

putOnLinkedBlockingQueue

public static <E> void putOnLinkedBlockingQueue(LinkedBlockingQueue<E> queue,
                                                E entry)

pollLinkedBlockingQueue

public static <E> E pollLinkedBlockingQueue(LinkedBlockingQueue<E> queue,
                                            long timeout,
                                            TimeUnit unit)

sleepNoException

public static void sleepNoException(long millis)
Sleep for the target milliseconds. If interrupted, rethrow the exception as a RuntimeException.


sleepNoExceptionMicros

public static void sleepNoExceptionMicros(int micros)
Sleep for the target milliseconds. If interrupted, rethrow the exception as a RuntimeException.


getPathSeparator

public static String getPathSeparator()
Returns the path separator, either ':' for UNIX or ';' for Windows.


getIsUNIX

public static boolean getIsUNIX()
Returns true if on UNIX or Linux.


getIsDOS

public static boolean getIsDOS()
Returns true if on DOS (Windows)


getIsWindows

public static boolean getIsWindows()
Returns true if on Windows


getFileSeparator

public static String getFileSeparator()
Returns the file separator, either '/' for UNIX or '\' for Windows.


getLineSeparator

public static String getLineSeparator()
Returns the appropriate line separator for UNIX (\n) or Windows (\r\n).


getLF

public static String getLF()

getAbsolutePath

public static String getAbsolutePath(String s)
Uses the input file name as a constructor for a file and then calls Java's File.getAbsolutePath(). If the input file name is null, this returns null.


getAbsolutePath

public static String getAbsolutePath(File f)
Returns Java's File.getAbsolutePath() value for the input file. If the input file is null, this returns null.


getCanonicalPath

public static String getCanonicalPath(String fileName)
Returns the Java File canonical path (i.e. the absolute location of the file using the OS's file separator - '/' or '\'). If the input file name is null or getCanonicalPath throws an exception, this returns null.


getCanonicalPath

public static String getCanonicalPath(File f)
Returns Java's File.getCanonicalPath. If the input file is null or getCanonicalPath throws an exception, this returns null.


getResolvedPathFrom

public static String getResolvedPathFrom(String path,
                                         String baseDir)
The input path is one or more path elements separated by the platform path separator (';' or ':') or ",". The path elements can optionally have leading or trainling whitespace (e.g. newlines), which will be trimmed before use The baseDir is the base to resolve from. The returned value is the input string, but where a path element is relative, it is resolved into an absolute path. Empty path elements (i.e. a zero-length string) are discarded in this process. For example, on Windows getResolvedPathFrom( "C:\jw\myproject;../subdir", "C:\jw\top" ) = "C:\jw\myproject;C:\jw\subdir"


getPlatformPath

public static String getPlatformPath(String fileName)
Returns the input file name as a path in a standard, absolute format for the indicated file, suitable for error messages and for specifying to other tools on this platform. This is a synonym for getCanonicalPath. Use getUnixPath for ant scripts. On Windows, this uses '\' path separators; on UNIX, it uses '/'. If the input file name is null, this returns null.


getPlatformPath

public static String getPlatformPath(File f)
Returns the input file as a path in a standard, absolute format for the input file, suitable for error messages and for specifying to other tools on this platform. On Windows, this uses '\' path separators; on UNIX, it uses '/'. This is a synonym for getCanonicalPath. Use getUnixPath for ant scripts. If the input file name is null, this returns null.


getUnixPath

public static String getUnixPath(String fileName)
Creates a File using the input file name in the constructor, then returns Java's File.getCanonicalPath for the file, but using '/' as the path separator. [ We use the 'Unix' in the name to reflect the '/' separator, but on Windows this will have the 'drive:' at the start so it is not strictly a Unix path.] If the input file name is null or File.getCanonicalPath throws an exception, getUnixPath() returns null. Use this method to write file paths into Ant scripts and into properties files (in properties files, the '\' character of a Windows path will be interpreted as an escape character). Use getPlatformPath() for creating files for input to local-platform tools.


getUnixPath

public static String getUnixPath(File f)
Returns Java's File.getCanonicalPath for the input file, but using '/' as the path separator. [ We use the 'Unix' in the name to reflect the '/' separator, but on Windows this will have the 'drive:' at the start so it is not strictly a Unix path.] If the input file is null or File.getCanonicalPath throws an exception, getUnixPath() returns null. Use this method to write file paths into Ant scripts and into properties files (in properties files, the '\' character of a Windows path will be interpreted as an escape character). Use getPlatformPath() for creating files for input to local-platform tools.


getWindowsPath

public static String getWindowsPath(String fileName)
Creates a File using the input file name in the constructor, then returns Java's File.getCanonicalPath for the file, but using '\' as the path separator. If the input file name is null or File.getCanonicalPath throws an exception, getWindowsPath() returns null. Use this method for creating files for input to Windows commands.


getWindowsPath

public static String getWindowsPath(File f)
Returns Java's File.getCanonicalPath for the input file, but using '\' as the path separator. If the input file is null or File.getCanonicalPath throws an exception, getWindowsPath() returns null. Use this method for creating files for input to Windows commands.


getRelativePath

public static String getRelativePath(String path,
                                     String baseDirectory)
getRelativePath returns a path, relative to a base directory, if possible. The input 'path' can be either a single path, or multiple paths separated by the current platform's path separator (';' or ':'). Each individual path is resolved to a directory relative to the current one, by moving up the parents to find a common directory with the baseDirectory. If a common directory is found, the path relative via that directory is returned, with forward '/' for the file separator. However this process stops when four levels have been examined unsuccessfully; at this point, the original path in Unix format is returned.


getRelativePath

public static String getRelativePath(String path,
                                     String baseDirectory,
                                     int nLevels)
getRelativePath returns a path, relative to a base directory, if possible. The input 'path' can be either a single path, or multiple paths separated by the current platform's path separator (';' or ':'). Each individual path is resolved to a directory relative to the current one, by moving up the parents to find a common directory with the baseDirectory. If a common directory is found, the path relative via that directory is returned, with forward '/' for the file separator. In this variant of getRelativePath, the number of levels examined for a common directory is specified by 'nLevels'; at this point, the original path in Unix format is returned.


getRelativePathBS

public static String getRelativePathBS(String path,
                                       String baseDirectory)
Returns the same as getRelativePath, but with any '/' changed to '\' (for Windows). The number of parent directory levels searched for a common directory is 4 in this version.


getRelativePathBS

public static String getRelativePathBS(String path,
                                       String baseDirectory,
                                       int nLevels)
Returns the same as getRelativePath, but with any '/' changed to '\' (for Windows). The number of parent directory levels searched for a common directory is specified by 'nLevels' in this version.


getFile

public static File getFile(String path)
Returns a Java File from the path, i.e. 'new File( path )'.


getFile

public static File getFile(File dir,
                           String fileName)
Returns a Java File from the fileName, i.e. 'new File( dir, fileName )'.


getFile

public static File getFile(String dirPath,
                           String fileName)
Returns a Java File from the fileName, i.e. 'new File( dirPath, fileName )'.


fileIsAbsolute

public static boolean fileIsAbsolute(String path)
Returns true if the input path represents an absolute.file. This also


getBasename

public static String getBasename(String path)
Get the filename part - after the last '/' or '\' - from a path string. If the path is null or doesn't contain '/' or '\', then the path is returned


getDirname

public static String getDirname(String path)
Get the directory part - up to but not including the last '/' or '\' - from a path string. If the path is null or empty, the path value is returned. If the path doesn't contain '/' or '\', then ".." is returned (on the assumption that name is a relative reference to the current directory and so the desired directory is the parent of the current directory).


getEOLString

public static String getEOLString(String inputString)
getEOLString gets the first EOL (end of line) string in the input string. An end-of-line string is one of the following: CR-LF CR LF If there is no end-of-line sequence, then null is returned


getPieceOf

public static String getPieceOf(String inputString,
                                String separator,
                                int pieceNumber)
getPieceOf in this form gets a numbered piece of a string. For example getPieceOf( "a,b,c", ",", 2 ) returns "b".

Parameters:
inputString - the string to be broken apart
separator - the separator character that defines the pieces. In the method where separator is a character, this can be any character - it doesn't have to be punctuation In the method where separator is a string.
pieceNumber - the piece number: if pieceNumber is 0, the inputString is returned. If there is no such piece - i.e. the number is out of range, then the empty string "" is returned. For pieceNumbers greater than 0, the 'first' piece runs from the start of the string to the character before the first separator or the end of the string, so getFirstPieceOf( x, "," ) == getPieceOf( x, "," 1 ) The second piece runs from after the first separator to just before the second separator or the end of the string; and so on. If pieceNumber is less than 0, then -1 is the "last" occurrence, -2 is the second last occurrence, and so on.
Returns:
the substring of inputString before the pieceNumber'th occurrence of the separator, but after the previous occurrence. So getPieceOf( "a,b,c", ",", 1 ) returns "a", i.e. the same as getFirstPieceOf( "a,b,c", "," ) getPieceOf( "a,b,c", ",", 2 ) returns "b" getPieceOf( "a,b,c", ",", 3 ) returns "c" - there are two occurrences of the separator, so the third piece is the remainder of the string getPieceOf( "a,b,c", ",", 4 ) returns "" - there aren't enough separator characters This method returns "" in all degenerate cases, i.e. where - the input string is null or the empty string - the piece number is less than 1 - the separator string is null or the empty string - there are not enough separator strings (i.e. there are less than 'pieceNumber-1' occurrences of the separator string.

getPieceOf

public static String getPieceOf(String inputString,
                                char separator,
                                int pieceNumber)
internal getPiece of gets a numbered piece of a string - see the other version for documentation


getFirstPieceOf

public static String getFirstPieceOf(String inputString,
                                     char separator)
internal getFirstPieceOf gets the first piece of the inputString

Parameters:
inputString - the string to be broken apart
separator - the separator character that defines the pieces. This can be any character.
Returns:
the substring of inputString before the first occurrence of separator, or, if there is none, the input string

getFirstPieceOf

public static String getFirstPieceOf(String inputString,
                                     String separator)
getFirstPieceOf gets the first piece of the inputString - this variant takes a string to delimit the pieces rather than a character.

Parameters:
inputString - the string to be broken apart
separator - the separator that defines the pieces. The separator can be any non-empty string, although normally it is a single character of punctuation.
Returns:
the substring of inputString before the first occurrence of a single-character separator, or, if there is none, the input string

removeFirstPieceOf

public static String removeFirstPieceOf(String inputString,
                                        String separator)
removeFirstPieceOf removes the first piece of the input string, based on the given separator. For example, removeFirstPieceOf( "first//remainder", "//" ) returns remainder. If the separator is missing from the string, null is returned.

Parameters:
inputString - the string to be broken apart
separator - the separator that defines the pieces. The separator can be any non-empty string, although normally it is a single character of punctuation.
Returns:
the substring of inputString after the first occurrence of a separator, or, if there is none, null

getPieceOf

public static String getPieceOf(String inputString,
                                String leftSeparator,
                                String rightSeparator)
getPieceOf gets a piece of the inputString, separated by delimiters. This variant takes a left separator, to mark the LHS of the result, and a right separator, to mark the end of the result.

Parameters:
inputString - the string to be broken apart
leftSeparator - the separator character that defines the pieces. In fact, this can be any non-empty string, although normally it is a single-character punctuation.
Returns:
the substring of inputString after the leftSeparator and before the rightSeparator. The empty string "" is returned in the 'degenerate' cases, i.e. if any of the input parameters are null or empty. Null is returned if - there is no occurence of the leftSeparator in the inputString - there is no occurence of the rightSeparator after the leftSeparator.

getLastPieceOf

public static String getLastPieceOf(String inputString,
                                    char separator)
internal getLastPieceOf gets the last piece of the inputString

Parameters:
inputString - the string to be broken apart
separator - the separator character that defines the pieces. This can be any character.
Returns:
the substring of inputString after the last occurrence of separator, of, if there is none, the input string

getLastPieceOf

public static String getLastPieceOf(String inputString,
                                    String separator)
getLastPieceOf gets the last piece of the inputString

Parameters:
inputString - the string to be broken apart
separator - the separator character that defines the pieces. The separator can be any non-empty string, although normally it is a single character of punctuation.
Returns:
the substring of inputString after the last occurrence of separator, of, if there is none, the input string

getPreLastPieceOf

public static String getPreLastPieceOf(String inputString,
                                       String separator)
getPreLastPieceOf gets the pieces of the inputString before the last.

Parameters:
inputString - the string to be broken apart
separator - the separator character that defines the pieces. The separator can be any non-empty string, although normally it is a single character of punctuation.
Returns:
null if the inputString or separator are null, otherwise the substring of inputString preceding the last occurrence of separator, of, if there is none, "". e.g. getLastPieceOf( "x.y", "." ) = "x"

getPieces

public static ArrayList getPieces(String inputString,
                                  String separator)
getPieces gets the pieces of the inputString before the last. The separator is the string that separates the pieces. The separator can be any non-empty string: in particular, it can be more than a single character in length.

Returns:
null if the inputString or separator are null, or if the separator is empty, otherwise an ArrayList whose elements are the pieces of the input string separated by the separator string. Note that empty strings are removed from the result list if they are encountered. e.g. getPieces( "x - y - z - ", " - " ) = { "x", "y", "z", "" } getPieces( "", " - " ) = { "" } getPieces( "", "" ) = null getPieces( "a b", " " ) = { "a", "", "", "b" }

getPieces

public static ArrayList getPieces(String inputString,
                                  String separator,
                                  boolean removeEmptyPieces)
getPieces gets the pieces of the inputString before the last. The separator is the string that separates the pieces. The separator can be any non-empty string: in particular, it can be more than a single character in length. The 'removeEmptyPieces' flag tells whether empty strings should be removed from the output list.

Returns:
null if the inputString or separator are null, or if the separator is empty, otherwise an ArrayList whose elements are the pieces of the input string separated by the separator string. Note that empty strings are possible as elements of the returned ArrayList if 'removeEmptyPieces' is false. e.g. getPieces( "a b", " ", true ) = { "a", "b" } getPieces( "a b", " ", false ) = { "a", "", "", "b" }

getXmlPrefix

public String getXmlPrefix(String s)
getXmlPrefix gets the xml prefix from the input string. For example, if the input string is "prefix:localpart", the return value is "prefix". If there is no prefix, the return value is "". If the input string is null, the return value is null.


getXmlLocalPart

public String getXmlLocalPart(String s)
getXmlLocalPart gets the xml local part from the input string. For example, if the input string is "prefix:localpart", the return value is "localpart". If there is no prefix, the return value is the input string. If the input string is null, the return value is null.


getJavaName

public static String getJavaName(String inputName,
                                 boolean capitaliseFirstCharacter)
Converts from an XML name to a Java class or variable name, depending on the setting of capitaliseFirstCharacter. If capitaliseFirstCharacter is set, this is equivalent to getJavaClassName. If capitaliseFirstCharacter is not set, this is equivalent to getJavaVarName. The '.', '-' and ':' are allowed name characters in XML but not in Java. (Although ':' is used in the XML prefix syntax, you can run JeeWiz with 'processPrefixes=false', and the ':' character is processed by this algorithm.) There characters are used as 'capitalization' triggers - the next character if any is capitalized - and the character itself is discarded.


getJavaClassName

public static String getJavaClassName(String inputName)
Converts from an XML name to a Java class-style name. The Java class-style name is as you would expect: a leading uppercase letter, followed by alphanumerics with capitals signalling the start of new logical 'words'. The details of the steps involved are:
  1. capitalise the first character of the name
  2. find disallowed characters - XML characters that are not allowed in Java ('.', ':' and '-')
  3. remove these characters and capitalise the next character, if any
  4. leave the case of characters within the body of the name that do not follow a separator unchanged
The '_' character, which is allowed in XML and in Java, is passed through and the case of the following letter is unchanged.


getXMLName

public static String getXMLName(String inputName)
Synonym for 'getXmlName'


getXmlName

public static String getXmlName(String inputName)
Converts the input name into 'standard XML' format. This means:
  1. initial capital letters are made lower cases
  2. capital letters in the remainder of the input name are also made lower case, but a '-' is inserted before them ... unless there is already a '-' there, in which case this is omitted - to avoid synthetic double '-'s.
For example
      getXmlName( "EjbJar" ) = "ejb-jar"
      getXmlName( "Ejb-Jar" ) = "ejb-jar"
 
Note that the double-'-' rule means that the Xml and JavaVar names are not associative. This is because
      getXmlName( getJavaVarName( x ) ) == x
 
is not true when there is a '-' before an upper case.


getJavaVarName

public static String getJavaVarName(String inputName)
Converts from an XML name to a Java variable-style name. In other words, this is the same as getJavaClassName, except the first character will be lower-case.


getNull

public static String getNull()
This returns a null, as an easy way to get a null value in Velocity - use $null.


removeSpaces

public static String removeSpaces(String s)
Converts a string with spaces to one without. E.g. 'My old String' becomes MyoldString'


removeSpacesProperCase

public static String removeSpacesProperCase(String s)
Converts a string to a string in the Java variable name style, i.e. spaces are removed characters that followed a removed space are upper-cased the first character is lower-cased. For example, 'My old String' becomes 'myOldString'.


removeSpacesCapitalise

public static String removeSpacesCapitalise(String s)
Converts a string to a string in the Java variable name style, i.e. spaces are removed characters that followed a removed space are upper-cased the first character is upper-cased. For example, 'My old String' becomes 'MyOldString'.


removeChars

public static String removeChars(String data,
                                 String unwantedChars)
Remove unwanted characters from a data string. The result is the data string less the unwanted characters. In other words, the return value is constructed by removing all occurrences (in the data string) of each chracter in the unwantedChars string. If either the data or the unwanted characters are null or empty, then 'data' is returned.


removeUnwantedChars

public static String removeUnwantedChars(String data)
Internal Remove unwanted characters '$', '.' and '!' from the input data - AND REPLACE WITH '_'. The result is the input less those three characters.


removeDash

public static String removeDash(String data)
Internal Remove dashes from a string but leave the capitalization of the other letters unchanged. For example foo-barBar becomes FooBarBar.

Parameters:
data - string to process
Returns:
String

getLocalName

public static String getLocalName(String qName)
Returns the local-part name from an XML Qname. The syntax for an XML Qname is:     QName ::= (Prefix ':')? LocalPart In other words, the prefix is optional and separated from the local part of the name by ':'. So getLocalName returns the qName as input, less the prefix and ':', if present.


getPrefix

public static String getPrefix(String qName)
Return the prefix from an XML QName. For example, if qName="pfx:elt", then this method returns "pfx". If there is no prefix on the QName, this method returns "".


getCapsAndSpacesName

public static String getCapsAndSpacesName(String externalName)
getCapsAndSpacesName is a wrapper for getCapsAndSeparatorName, using space as the separator. This is used to construct user-visible labels, e.g. labels on screen controls.


getCapsAndUnderscoreName

public static String getCapsAndUnderscoreName(String externalName)
getCapsAndUnderscoreName is a wrapper for getCapsAndSeparatorName, using underscore as the separator. This is used, for example, to construct database table names from the entity java-style name.


getCapsAndSeparatorName

public static String getCapsAndSeparatorName(String externalName,
                                             char separator)
internal


getCapsAndSeparatorName

public static String getCapsAndSeparatorName(String externalName,
                                             String separator)
getCapsAndSeparatorName converts 'externalName' to Java Class format, then adds 'separator' before each capital letter in the external name if - it is preceded by a lower-case or numeric letter, or - it is the last in the sequence of capital letters and followed by a lower-case letter. For example, - getCapsAndSeparatorName( "boy-band", "_" )="Boy_Band" // JavaClass form="BoyBand" - getCapsAndSeparatorName( "XYZCorp", " " )="XYZ Corp" // "C" is last in sequence of capital letters - getCapsAndSeparatorName( "XYZ.Corp", "/" )="XYZ.Corp" // no change - last in sequence not followed by letter Normally 'separator' is a single-character string, but it does not need to be


removePunctuationAndCapitalise

public static String removePunctuationAndCapitalise(String inputString)
removePunctuationAndCapitalise takes away the punctuation from a string and capitalises the character after one or more separators. For example, foo_-bar&too becomes FooBarToo. More exactly, any characters that are not letters or digits are removed. Note this means that legal Java characters - '_' and '$' - are also removed. This then yields a conventional Java class name. This method is used to support Jaxb name conversion. If the input string is null, null is returned.


removeString

public static String removeString(String inputString,
                                  String separators)
removeString takes away the separators from a string and capitalises the character after a separator. For example, removing "_" from foo_bar becomes fooBar. If the input string is null, null is returned.


removeStringNoCapital

public static String removeStringNoCapital(String inputString,
                                           String separators)
Takes away the separators from a string. This version does *not* capitalise the character after a separator. For example, removing "_" from foo_bar becomes foobar.


separateByCapitals

public static String separateByCapitals(String inputString)
This takes an input string and splits it before a capital, by inserting a space. If there is a sequence of capitals a space is only inserted before the last one. A space is never inserted before the first character or the last. eg. "ZIPCode" becomes "ZIP Code", and "ISBN" stays "ISBN".


parseFormat

public String parseFormat(String format,
                          String fControl,
                          String fTerm)
parseFormat - Similar to parseFormat in the uiBase jwControl, this is to make the same functionality available for .vms

Parameters:
format - the raw format String, containing 0 to many format terms.
fControl - the characters starting the format, usually @ followed by the type, eg @w or @i.
fTerm - the terminating character, usually @
Returns:
String returns the value of the relevant format term.

changeString

public static String changeString(String inputString,
                                  String separators,
                                  String toThis)
Internal - Don't use - doesn't do what it says on the tin - only works on single-character items.

change one string to another string

Parameters:
inputString - string to hump
separators - string to be replaced
toThis - string
Returns:
String

stringReplace

public static String stringReplace(String inputString,
                                   String from,
                                   String to)
stringReplace - exists because String.replace uses characters and Velocity doesn't support characters.

Parameters:
inputString - the string to do the replacing on
from - the character(s) to replace. Multiple characters are allowed.
to - the character(s) to replace it with (matching characters in 'to' with characters in 'from' by position
Returns:
String returns the inputString.replace( from, to ), with occurrences of from.charAt(i) replaced with to.charAt(i), where i goes from 0 to the minimum length of 'from' and 'to' minus 1.

firstValue

public static String firstValue(String s1,
                                String s2)
Returns the first 'real value' of the two inputs. In detail this means, the returned value is s1 if that is a non-empty string (i.e. length>0); otherwise it is s2. This can be used to construct a default.


firstValue

public static String firstValue(String s1,
                                String s2,
                                String s3)
Returns the first 'real value' of the three inputs. In detail this means, the returned value is - s1 if that is a non-empty string (i.e. length>0); - otherwise it is s2 if that is a non-empty string . - otherwise it is s3. This can be used to construct a default.


firstLetterCaps

public static String firstLetterCaps(String inputString)
Synonym for capitalise.


capitalise

public static String capitalise(String inputString)
Returns the input string as is, except that if the first letter is lower-case, it is converted to upper case.


capitalize

public static String capitalize(String inputString)
Synonym for capitalise.


uncapitalise

public static String uncapitalise(String inputString)
Returns the input string as is, except that if the first letter is upper-case, it is converted to lower case.


uncapitalize

public static String uncapitalize(String inputString)
Synonym for uncapitalise


uncapitaliseSecond

public static String uncapitaliseSecond(String inputString)
Returns the input string as is, except that if the *second* letter is upper-case, it is converted to lower case.


lowerCaseOnSecond

public static String lowerCaseOnSecond(String inputString)
Returns the input string as is, except that if the *second* letter is upper-case, ALL characters are converted to lower case.


uncapitaliseInitialGroup

public static String uncapitaliseInitialGroup(String inputString)
Returns the input string uncapitalising all but the last of a leading group of capital letters. The first two characters are always decapitalised


decapitalize

public static String decapitalize(String inputString)
This method implements the JavaBeans 'decapitalize' method, which is - if the first two letters of a variable name are upper case, leave them unchanged (e.g. URL remains as URL) - otherwise ensure the first character becomes lower-case.


getCharacterCount

public static int getCharacterCount(String s,
                                    String c)
Gets the number of occurrences of the first character of 'c' in the string 's'. This allows 'c' to be a string; only the first charater is used. If c or s is null, the returned value is 0.


getCharacterCount

public static int getCharacterCount(String s,
                                    char c)
internal Gets the number of occurrences of the character 'c' in the string 's'. If s is null, the returned value is 0.


spaces

public static String spaces(String s)
Returns a string as long as the input string, up to a maximum of 600 characters or so, but filled with spaces. If 's' is null or 0-length, "" is returned


spaces

public static String spaces(int n)
Returns a string 'n' spaces long, up to a maximum of 600 or so. If n is less than or equal to 0, the empty string is returned.


spaces1

public static String spaces1(int n)
Returns a string 'n' spaces long, up to a maximum of 600 or so. If n is less than or equal to 1, one space is returned.


leftJustify

public static String leftJustify(String s,
                                 int n)
Returns a string 'n' spaces long, up to a maximum of 600 or so.


rightJustify

public static String rightJustify(String s,
                                  int n)
Returns a string 's' in a field of 'n' characters wide. If s.length() < n, the returned value is the required number of spaces followed by 's'; otherwise, 's' is returned.


leadCharCount

public static long leadCharCount(String inputString,
                                 String firstChar)
This takes a one-character string If the firstChar parameter string is not a string of length 1 then the method returns 0. Otherwise it returns the length of the continuous string of the 'firstChar' characters.


removeTrailingWhitespace

public static String removeTrailingWhitespace(String inputString)

splitCSString

public static ArrayList<String> splitCSString(String csString)
Splits up a comma separated string, returning the resulting tokens (substrings) between the comma's in a List. The substrings are trimmed, i.e. leading and trailing whitespace is removed. If the input string 'csString' is null or zero-length, a List with no items is returned.


splitCSStringWithoutDuplicates

public static ArrayList splitCSStringWithoutDuplicates(String csString)
Like 'splitCSString' but with any duplicates removed If the input string 'csString' is null or zero-length, a List with no items is returned.


splitSeparatorString

public static ArrayList splitSeparatorString(String stringToSplit,
                                             String delimiters)
Splits up the string 'stringToSplit' into tokens based on the provided delimiters, with the resulting tokens trimmed (as in 'String.trim()'). Only non-empty tokens are returned; 0-length strings are discarded. The returned ArrayList contains Strings, one for each token. For example, splitSeparatorString( "abc.dot=equ", ".=" ) = List{ "abc", "dot", "equ" }


splitSeparatorString

public static ArrayList splitSeparatorString(String stringToSplit,
                                             String delimiters,
                                             boolean returnDelims)
Splits up the string 'stringToSplit' into tokens based on the provided delimiters with the resulting tokens trimmed (as in 'String.trim()'). Only non-empty tokens are returned; 0-length strings are discarded.. The returned ArrayList contains one token for each non-empty non-delimiter string and, if returnDelims is true, for every delimiter . If returnDelims is false, this operates in the same way as the two-parameter splitSeparatorString() method. For example, splitSeparatorString( "abc.dot=equ", ".=", true ) = List{ "abc", ".", "dot", "=", "equ" }


splitStringIntoTwo

public static ArrayList splitStringIntoTwo(String stringToSplit,
                                           String separatorString)
splitStringIntoTwo() splits a string based on a separator string. For example, splitStringIntoTwo( "GiveMeCookies", "Me" ) = { "Give", "Cookies" } The method returns an ArrayList of precisely two Strings. The first item in the returned ArrayList is equal to getFirstPieceOf( stringToSplit, separatorString ). The second item is the remainder after the separatorString if it is present in the stringToSplit, otherwise the empty string - "". If the stringToSplit or the separatorString are null or empty, a list of two empty strings {"", ""} is returned.


buildCSString

public static String buildCSString(List stringList)
Builds a comma separated string from a List containing either Strings or CDataAttribute objects (one CDataAttribute object is created by JeeWiz to read each <description> element. The comma-separated list does not have unique entries (i.e. duplicates are not removed). Leading and trailing spaces are significant in the items in 'stringList'; they are not trimmed.


removeCSListDuplicates

public static void removeCSListDuplicates(List list)
Removes any duplicate or null strings from 'list' - an ArrayList containing strings or CDataAttribute objects


appendToUniqueCSString

public static String appendToUniqueCSString(List uniqueList,
                                            String extraCSItems)
Append a comma-separated string to a List of Unique strings, and ensures that the result has unique entries - i.e. has no duplicate values. This method assumes that the uniqueList is already unique, but the extraCSItems may duplicate values either within itself or with the entries in uniqueList In other words, if one or the other has no value, the other string is returned.


addUniqueCSStrings

public static String addUniqueCSStrings(String string1,
                                        String string2)
Add two unique comma-separated strings, and ensures that the result has unique entries - i.e. has no duplicate values. This method is optimised assuming that the two input strings are already unique. In other words, if one or the other has no value, the other string is returned.


list

public static String list(String input,
                          String separator,
                          String addon)
Returns a concatenated list.  The returned value is - 'addon' if 'inputCSList' is empty (i.e. null or "") - 'inputCSList' if 'addon' is empty - otherwise, the concatenation of 'inputCSList', 'separator' and 'addon'. This is useful for building lists in Velocity. The following will create a list, with the properties separated by ', '.
     #set( $result = "" )
     #foreach( $whatever )
         #set( $result = $this.list( $result, ", ", $whatever.property ) )
     #end


list

public static String list(String list,
                          String sep,
                          String addon,
                          String addon2)

list

public static String list(String list,
                          String sep,
                          String addon,
                          String addon2,
                          String addon3)

list

public static String list(String list,
                          String sep,
                          String addon,
                          String addon2,
                          String addon3,
                          String addon4)

list

public static String list(String list,
                          String sep,
                          String addon,
                          String addon2,
                          String addon3,
                          String addon4,
                          String addon5)

list2String

public static String list2String(List listOfStrings,
                                 String sep)

list

public static String list(String list,
                          String sep,
                          List listOfStrings)

toHTML

public static String toHTML(String inputLine)
'toHTML' is used to create HTML documentation from a simple layout. This is used in documenting the standard meta-models. The conversions that are applied are: - adjacent non-empty lines are joined into paragraphs - blank lines create paragraph boundaries - left-justified '-' followed by whitespace creates an unnumbered list item, the start and end of the list is detected automatically - whitespace then '-' then whitespace creates a second-level unnumbered list item. This is a convenience so that the descriptions can be read in the raw file or in an HTML document. See the JeeWiz metaModel, specifications directory (jeewiz/resources/JeeWiz/specification) and the JeeWiz Meta-MetaModel chapter for examples.


javaFindEndSeparator

public static int javaFindEndSeparator(String text)
Find the matching separator of paired Java separators. This calls the other instance of javaFindEndSeparator with fromIndex==0.


javaFindEndSeparator

public static int javaFindEndSeparator(String text,
                                       int fromIndex)
Find the matching separator of paired Java separators. The Java paired separators are '{...}', '(...)' and '[...]'; the RHS that can be looked for is '}', ']' or ')'. This method observes the syntax of Java, which means the search ignores comments (// or /star ) and String or character literals ( "..." or '...'). The text parameter is the piece of Java to search for the separator. It must not be null or empty; it must begin with the left separator of the pair - in other words, it must begin with '{', '(' or '[' The text parameter should start outside of comments or quotes. The fromIndex parameter denotes the index of the character within the 'text' parameter to start from. fromIndex==0 indicates to start from the beginning of the string. The return value, if successful, is the index in 'text' string of the matching RHS separator. If unsuccessful, the return value is less than 0 and equals the negative of the index of the character which could not be satisfied before the end of the text string. For example, if the input text is '{...(', the return value will be -4. The number in the return value is relative to the start of the text string, not to the substring starting at 'fromIndex'. If the contract of this method are violated, an IllegalArgumentException is thrown. Without having tested it, this method has a fighting chance of working for C, C++ and C#.


javaFindMatchingQuote

public static int javaFindMatchingQuote(String text,
                                        int fromIndex)
Find the matching quote character, single-quote or double-quote to end a Java String literal. The text parameter is the piece of Java to search for the separator. It must not be null or empty; it must begin with the single- or double-quote character that starts the literal. The fromIndex parameter denotes the index of the character within the 'text' parameter to start from. fromIndex==0 indicates to start from the beginning of the string. The return value, if successful, is the index in 'text' string of the matching quote. If unsuccessful, the return value is 0 or less; in this case, the negative of the return value is the index of the character which could not be satisfied before the end of the text string. The number in the return value is relative to the start of the text string, not to the substring starting at 'fromIndex'. If the contract of this method are violated, an IllegalArgumentException is thrown. Without having tested it, this method has a fighting chance of working for C, C++ and C#.


javaFindCommentEnd

public static int javaFindCommentEnd(String text,
                                     int fromIndex)
Find the index of the end of a quote. The first character of the text substring starting at fromIndex must be '/' If the next character is '*', a /star star/ comment is swallowed and the return value is the index of the terminating /. If the next character is '/', the rest of the line is swallowed and the return value is the terminator of the end of the line - CR, LF, or CR-LF. If the end of a Java comment cannot be found, -fromIndex is returned


javaFindText

public static int javaFindText(String textToSearch,
                               int fromIndex,
                               String textToFind)
finds the specified 'textToFind' string in the 'textToSearch', starting from 'fromIndex'. The trick is that this finds the text at the same Java syntactic level as the search. All Java quotes and comments are ignored. If an unmatched '}', ']' or ')' character is found outside quotes, this is considered to end this level and the text is not found. The textToSearch strings can be null or empty, in which case -1 (not found) is returned. The textToFind fstring cannot be null or empty. The returned value if successful is the index of the textToFind within the fromIndex substring of textToSearch. This may be in the range 0 to the length of textToSearch-1. A return value less than 0 indicates failure - there was an unmatched character (quote, comment or paired separator []{}() ). To retrieve the index of the unmatched character, take the negative of the value and subtract 1 from it. For example, if the 0'th character is unmatched, then -1 is returned; the negative of this is 1, and subtracting 1 gives 0.


firstIndexOf

public static int firstIndexOf(String source,
                               String findChars)
Search for the first occurrence of one of the characters in findChars in source string. If found, return the index of the earliest character. Otherwise, return -1. For example, firstIndexOf( "The quick, brown fox", "qk" ) = 4


getSingleLineText

public static String getSingleLineText(String description)
This method converts from an internal String value (e.g. read in from XML character data) into a string suitable for creating a single-line String constant in a Java program.


stringToXMLAttrWithoutQuotes

public static String stringToXMLAttrWithoutQuotes(String s)
Returned value is same as stringToXMLAttr, but without the enclosing quotes.


stringToXMLAttr

public static String stringToXMLAttr(String s)
stringToXMLAttr(s) converts the input string 's' from an string value into an XML attribute, including the appropriate quotes ('' or "") and &'s etc converted to '&' etc. This - chooses the correct quote type - replaces <& by the correct XML values For example - the returned value is showed below *not* in Java String format, because it is easier to see without that - stringToXMLAttr( null ) = [ empty string ] - stringToXMLAttr( "" ) = [ empty string ] - stringToXMLAttr( "\"" ) = '"' - stringToXMLAttr( "'" ) = "'" - stringToXMLAttr( "&<\">" ) = "&amp;&lt;&quot;>"


stringToXMLCharacterData

public static String stringToXMLCharacterData(String s)
generate XML character data. If there are sensitive characters, then this adds a CDATA and then converts ]]> to a <[CDATA[...]]> sequence. If there are no sensitive characters, the input string is returned as is.


stringWithinCData

public static String stringWithinCData(String s)
generate characters within a CData section. If there are ]]> sequences, they are converted to a "]]>" + "]]&gt;" + "<

stringToCDATAsection

public static String stringToCDATAsection(String s)
generates a CDATA section holding the trimmed input 's', as long as s is not null or empty or whitespace only. In other words, the return value will be "<![CDATA[" + s.trim() + " ]]>". If s is null or empty or whitespace only, then the empty string is returned.


multiplyString

public static String multiplyString(String value,
                                    int multiplier)
returns the value string, multiplied by 'multiplier'. For example, multiplyString( "123", 3 ) == "123123123" If value is null, or multiplier is <= 0, then "" is returned.


indent

public static String indent(String multiline,
                            String indent)

addLists

public static List addLists(List a,
                            List b)

subtractList

public static List subtractList(List biggerList,
                                List subtractedList)

isFile

public static boolean isFile(String fileName)
Returns true if the fileName represents a normal file. This uses Java's 'File.isFile()' method, but catches any thrown exception (i.e. the SecurityException in Java 1.4) and returns false. In other words, a true result means that the file exists and is readable. If fileName is a relative file, it will be interpreted in Velocity as relative to the build.xml file calling Velocity. As this can change with different renderings, it is best to only use absolute fileName's from Velocity.


isDirectory

public static boolean isDirectory(String fileName)
Returns true if the fileName represents a directory. This uses Java's 'File.isDirectory()' method, but catches any thrown exception (i.e. the SecurityException in Java 1.4) and returns false. In other words, a true result means that fileName is a directory and is accessible. If fileName is a relative file, it will be interpreted in Velocity as relative to the build.xml file calling Velocity. As this can change with different renderings, it is best to only use absolute fileName's from Velocity.


projectMap

public static Map projectMap(Map mapFrom,
                             Object objectToMap,
                             Map targetMap)
Internal When we are picking up a lot values from files, it is useful to know the source So this routine projects an object (e.g. the file) using the keys from a source map onto a target map. So all the entries in the source map will be created in the target Map, with a value of the given object. After doing this a few times, e.g. you can tell where the source object came from: source: targetMap and entry in mapFrom the object to put in the Map - typically a string or a source file. targetMap( "specDir" ) = File("dotNet/alias.properties" )


projectMap

public static Map projectMap(Map mapFrom,
                             Object objectToMap)

getUUID

public static String getUUID()
Get a random UUID. This is necessary because it is difficult or impossible to construct the UUID object in J5.


getUUID

public static String getUUID(String hostName)
This is present for backward compatibility. It returns the same as getUUID().


getUniqueKey

public static String getUniqueKey(String baseKey,
                                  Map map,
                                  Object entryValue)
getUniqueKey gets a unique key for a map, starting with the baseKey string. If the baseKey already has an entry in the map, '1', '2', '3' and so on are suffixed onto baseKey until a unique key is produced. An entry is created in the map, using the returned value as the key and entryValue as the value. If baseKey is null, "" is used. map may not be null. entryValue may be null, and will result in a null value being put into the map. The returned value is the unique key


getUniqueKey

public static String getUniqueKey(String baseKey,
                                  Map map)
getUniqueKey with two parameters is a variant of the three-parameter method. It puts a zero-length string "" as the entry in the HashMap.


getIndentStartHeader

public static String getIndentStartHeader()

getIndentStartBody

public static String getIndentStartBody()

getUnindent

public static String getUnindent()

writeStringToFile

public static void writeStringToFile(String fileName,
                                     String stringToWrite)
writeStringToFile writes the contents of the stringToWrite parameter to a file using the default character encoding. 'fileName' is interpreted as a file name. The output encoding is the JeeWiz output encoding - either the outputEncoding property specified at start of day or the system default if not. If the file is not successfully written, this method issues a InternalException (stopping the build). If the parent directory for the indicated file does not exist, this method mkdir's it.


writeStringToFile

public static void writeStringToFile(String fileName,
                                     String stringToWrite,
                                     String encoding)
writeStringToFile writes the contents of a String to a file using the specified character encoding. 'fileName' is interpreted as a file name, and used to call writeStringToFile(file). 'encoding' must be the name of a valid encoding (e.g. 'windows-1252'). If the file is not successfully written, this method issues a InternalException (stopping the build). If the parent directory for the indicated file does not exist, this method mkdir's it.


writeStringToFile

public static void writeStringToFile(File file,
                                     String stringToWrite)
writeStringToFile writes the contents of a String to a file using the default character encoding. If the file is not successfully written, this method issues a InternalException (stopping the build). If the parent directory for the indicated file does not exist, this method mkdir's it.


writeStringToFile

public static void writeStringToFile(File file,
                                     String stringToWrite,
                                     String encoding)
writeStringToFile writes the contents of a String to a file the specified character encoding. 'encoding' must be the name of a valid encoding (e.g. 'windows-1252'). If the file is not successfully written, this method issues a InternalException (stopping the build). If the parent directory for the indicated file does not exist, this method mkdir's it.


convertStringToLines

public static ArrayList convertStringToLines(String input)
Converts the input string to an ArrayList of lines. This uses the Java default BufferedReader's interpretation of lines.


areBinaryFilesEqual

public static boolean areBinaryFilesEqual(File f1,
                                          File f2)
                                   throws IOException
areBinaryFilesEqual was written as areFilesEqual by Soren Bak. It compares two binary files given the two File objects. It returns true if the two files are exactly the same byte sequence.

Throws:
IOException

readFileAsString

public static String readFileAsString(String fileName)
readFileAsString returns the contents of a file as a String. 'fileName' is interpreted as a file name, and used to call readFileAsString(file). This method uses the default input encoding to read the string, as defined by the 'inputEncoding' "Engine Configuration Value" - see the Architect Guide chapter on "Running And Configuring JeeWiz".


readFileAsString

public static String readFileAsString(File file)
Reads 'file' as a String. If the file does not exist, is not a file or cannot be read due to an IO error, logs an error and return null. Otherwise, returns the contents of the file as a single string. This method uses the default input encoding to read the string, as defined by the 'inputEncoding' "Engine Configuration Value" - see the Architect Guide chapter on "Running And Configuring JeeWiz".


readFileAsLines

public static ArrayList readFileAsLines(String fileName)
readFileAsLines returns the contents of a file as a String. 'fileName' is interpreted as a file name, and used to call readFileAsLines(file). This method uses the default input encoding to read the string, as defined by the 'inputEncoding' "Engine Configuration Value" - see the Architect Guide chapter on "Running And Configuring JeeWiz".


readFileAsLines

public static ArrayList readFileAsLines(File file)
Reads 'file' as an ArrayList of lines. If the file does not exist, is not a file or cannot be read due to an IO error, logs an error and return null. Otherwise, returns the contents of the file as a single string. This method uses the default input encoding to read the string, as defined by the 'inputEncoding' "Engine Configuration Value" - see the Architect Guide chapter on "Running And Configuring JeeWiz".


readUrlAsString

public static String readUrlAsString(String resourceAbsolutePath)
Looks up 'resourceAbsolutePath' as a URL resource in the class path and reads it as a string. The URL is absolute, so start it with a '/' - e.g. '/META-INF/persistence.xml'. If the resource does not exist or cannot be read as a stream due to an IO error, readUrlAsString logs an error and returns null. Otherwise, this method returns the contents of the file as a single string. This method uses the default input encoding to read the string.


readPropertiesFile

public static Properties readPropertiesFile(String fileName)
readPropertiesFile returns the contents of a file as a java.util.Properties. This is an adapater to the Properties.load( InputStream ) method. If the file does not exist, null is returned.


readPropertiesFile

public static Properties readPropertiesFile(File file)
readPropertiesFile returns the contents of a file as a java.util.Properties. This is an adapater to the Properties.load( InputStream ) method. If the file does not exist, null is returned.


readPropertiesResources

public static Properties readPropertiesResources(String resourceName)
readPropertiesResource returns the contents of the named resource as a java.util.Properties. This is an adapater to the Properties.load( InputStream ) method. If the resource does not exist, null is returned.


formatNumericString

public static String formatNumericString(String str)
formatNumericString formats a string, presumed to be integral and a valid Long number, using the current locale's standards, and in groups. For example, in the US, formatNumericString("1234") == "1,234". In a German system, "1.234" will be returned. If the input string cannot be converted to a long, this method throws a NumberFormatException. (If there is any valid possibility that the input string is not a number, the method should be called inside a #try() block.)


formatNumericString

public static String formatNumericString(String str,
                                         Locale locale)
formatNumericString formats a string, presumed to be integral and a valid Long number, using the locale parameter's standards, and in groups. If the input string cannot be converted to a long, this method throws a NumberFormatException. (If there is any valid possibility that the input string is not a number, the method should be called inside a #try() block.) The locale can be created via getClassInstance, e.g. #set( $locale = $this.getClassInstance( "java.util.Locale", "de" ) ) #set( $y = $this.formatNumericString( "1234", $locale ) ) The 1-, 2- and 3-parameter constructor for Locale can be used in getClassInstance.


compareStringNumbers

public static int compareStringNumbers(String s1,
                                       String s2)
Calls BigInteger.compareTo for BigIntegers constructed from s1 and s2


stringNumberLess

public static boolean stringNumberLess(String s1,
                                       String s2)
Arbitrary precision number comparison. Returns true if s1 is less than s2


stringNumberLessOrEqual

public static boolean stringNumberLessOrEqual(String s1,
                                              String s2)
Arbitrary precision number comparison. Returns true if s1 is <= than s2


stringNumberEqual

public static boolean stringNumberEqual(String s1,
                                        String s2)
Arbitrary precision number comparison. Returns true if s1 is numerically equal to s2


stringNumberGreater

public static boolean stringNumberGreater(String s1,
                                          String s2)
Arbitrary precision number comparison. Returns true if s1 is greater than s2


stringNumberGreaterOrEqual

public static boolean stringNumberGreaterOrEqual(String s1,
                                                 String s2)
Arbitrary precision number comparison. Returns true if s1 is >= s2


generateIncrementalNumberString

public static String generateIncrementalNumberString(String start,
                                                     String end,
                                                     String interval,
                                                     String separator)

getXsdDateAsCalendar

public static Calendar getXsdDateAsCalendar(String s)
Gets an XML Schema date string into a calendar object.

Parameters:
s - The date, in YYYY-MM-DD format, optionally followed by a timezone specification.
Returns:
The Calendar object with the Year/Month/Day fields set. The timezone will be set to the input timezone if one is present, otherwise to the current default timezone.
Throws:
IllegalArgumentException - if the input string is not a timezone format, or empty

getXsdTimeAsCalendar

public static Calendar getXsdTimeAsCalendar(String sIn)
Gets an XML Schema time string into a calendar object.

Parameters:
sIn - The total 'time' (without the date part) in HH:MM:SS[.sss]format, optionally followed by a timezone specification. There can be a timezone specification on the end of the string - but only 'Z' is allowed. Any number of 'sub-seconds' (after the '.') can be specified as per the spec, but only 3 are used.
Returns:
The Calendar object with the Year/Month/Day fields set. The timezone will be set to the input timezone if one is present, otherwise to the current default timezone.
Throws:
IllegalArgumentException - if the input string is not a timezone format, or empty

getXsdDateTimeAsCalendar

public static Calendar getXsdDateTimeAsCalendar(String s)
Gets an XML Schema dateTime string into a calendar object.

Parameters:
s - The dateTime, in YYYY-MM-DDTHH:MM:SS[.sss] format, optionally followed by a timezone specification.
Returns:
The Calendar object with all fields set.
Throws:
IllegalArgumentException - if the input string is not a valid dateTime.

getXsdDateFromCalendarAsString

public static String getXsdDateFromCalendarAsString(Calendar calendar)

getXsdTimeFromCalendarAsString

public static String getXsdTimeFromCalendarAsString(Calendar calendar)

getXsdDateTimeFromCalendarAsString

public static String getXsdDateTimeFromCalendarAsString(Calendar calendar)

checkXsdDateTime

public static String checkXsdDateTime(String s)
Checks that a string, supposedly a valid XML DateTime, can be converted into a Calendar object.

Parameters:
s - The dateTime string to be validated.
Returns:
The exception's error message on failure, otherwise null

checkXsdDate

public static String checkXsdDate(String s)
Checks that a string, supposedly a valid XML Date, can be converted into a Calendar object.

Parameters:
s - The date string to be validated.
Returns:
The exception's error message on failure, otherwise null

checkXsdTime

public static String checkXsdTime(String s)
Checks that a string, supposedly a valid XML Time, can be converted into a Calendar object.

Parameters:
s - The time string to be validated.
Returns:
The exception's error message on failure, otherwise null

getValueForTracing

public static String getValueForTracing(Object rv)

dumpObject

public static String dumpObject(Object objectToDump,
                                String initialIndent,
                                String indentIncrement)
This method dumps the object in a "nice format" - that takes account of the Java Collections Framework, particularly objects that implement Map and List - adding newLines and key/value separation, to aid readability. The initialIndent parameter should be the number of spaces to indent the first list of sub-objects. The indentIncrement parameter should be the number of spaces to additionaly indent further lists of sub-objects. (Note that the very first line is not indented at all). There is an anti-recursion stopper at a depth of 20 nested objects.


dumpObject

public static String dumpObject(Object objectToDump,
                                String initialIndent,
                                String indentIncrement,
                                int maxInList)

dumpObject

public static String dumpObject(Object objectToDump)
This is a variant of the 'dumpObject' method, which has no initial indentation and three spaces for each nested level of objects.


dumpObject

public static String dumpObject(Object objectToDump,
                                int maxInList)
This is a variant of the 'dumpObject' method, which has no initial indentation and three spaces for each nested level of objects.


dumpStringWithControlChars

public static String dumpStringWithControlChars(String s)
Dumps a string with JeeWiz-specific control character names. The special characters are: CR - carriage return LF - line feed TAB - tab ADS - JeeWiz start of additional indent text ( == [0001] ) END - JeeWiz end of additional indent text, and start of text to be indented by that amount ( == [0002] ) UNI - JeeWiz end of additional indent sequence ( == [0003] ) NLD - Null line deleter ( == [0004] ) NL2 - Delete two null lines ( == [0005] ) [nnnn] - Other ISO control characters. Any other characters are printed out as themselves


dumpStringWithHighlightedControlChars

public static void dumpStringWithHighlightedControlChars(String s)

getSystemProperties

public static Properties getSystemProperties()
returns the system properties, i.e. System.getProperties() from the java.lang.System class. Note that because the property names have '.' in them, you cannot say e.g. $systemProperties.user.name to get the user name. Instead, you should use the Properties class's 'get' method: $systemProperties.get( "user.name" ) Note that this method has nothing to do with the JeeWiz "System Properties" concept.


getJaxbAttributeName

public String getJaxbAttributeName(String xmlName)
get the Jaxb attribute name in Java from the xml name. This - removes punctuation characters - capitalises the letter following a word break (which is either punctuation or numerics) For example, "n.A-s_t2y" becomes "nAST2Y"


getBooleanTrue

public static Boolean getBooleanTrue()
returns a Boolean true value, which is the same as "true" in Velocity. This can be used to initialise variales in system.properties and component.properties with "booleanTrue".


getBooleanFalse

public static Boolean getBooleanFalse()
returns a Boolean false value, which is the same as "false" in Velocity. This can be used to initialise variales in system.properties and component.properties with "booleanFalse".


processSpecialCharacters

public static String processSpecialCharacters(String resultString)
Processes the JeeWiz special characters INDENTSTART etc. See jeewiz\resources\base\control\system.properties for symbolic names - $indentStartHeader etc. See also following short-hand names $i, $u, $b, $e.


mapChar

public static String mapChar(char c)

dumpStringWithCRLF

public static String dumpStringWithCRLF(String s)

dumpTxIFP

public static void dumpTxIFP(TransactionInfoForPersistor txIFP,
                             String message)

dumptTxIFPAndStorer

public static void dumptTxIFPAndStorer(TransactionInfoForPersistor txIFP,
                                       ICloudTranStorer storer,
                                       String message)

getExceptionAsString

public static String getExceptionAsString(Exception e)

getStackTraceAsString

public static String getStackTraceAsString(StackTraceElement[] stackTrace)

getCallersStackTrace

public static String getCallersStackTrace()
If methodA() calls methodB() which calls getCallersStackTrace(), this method will report the stack trace at methodA().


getMyPid

public static String getMyPid()
Returns:
the process id of this process or null if cannot be determined

exit

public static void exit()
exit() calls System.exit() with a 0 exitStatus parameter - which indicates successful execution.


exit

public static void exit(int exitStatus)
exit( int ) calls System.exit() with the exitStatus parameter


exit

public static void exit(long exitStatus)
exit( long ) calls System.exit() with the exitStatus parameter, throwing away any high-order bits


exit

public static void exit(String errorMessage)
exit( String errorMessage ) writes the errorMessage to the error log and then exits (i.e. System.exit) with a return status of 1, indicating failure.


getNewPair

public static Utils.Pair getNewPair()

getNewPair

public static Utils.Pair getNewPair(Object v1,
                                    Object v2)

getNewTriple

public static Utils.Triple getNewTriple()

getNewTriple

public static Utils.Triple getNewTriple(Object v1,
                                        Object v2,
                                        Object v3)

getNewArrayList

public static ArrayList getNewArrayList(int n)
Returns a new ArrayList with an initial capacity of n. Note that you must use the full name 'getNewArrayList(...)' to call this method (unlike the 0-parameter version, which can be referenced without the 'get' - e.g. '$this.newArrayList').


csvToArrayList

public static ArrayList<String> csvToArrayList(String csv)
Takes a CSV string, with ',' as the separator and " as the string delimiter and converts it into an ArrayList


csvToArrayList

public static ArrayList<String> csvToArrayList(String csv,
                                               String separator,
                                               String delimiter)
This takes as input a string in CSV (Comma-Separated Value) format and turns it an ArrayList of the Strings it contains. The format of the CSV string must be individual strings separated by a separator and optionally delimited by a delimiter. In this form of the method, the separator and delimiter are explicitly specified. The separator separates the values, and is usually ",". The delimiter delimits valid values (i.e. so they can contain the separator), and is usually the " character. If a field contains a separator or leading/trailing blank spaces, it will must be delimited. If a delimited field contains the delimiter as part of the data, it must be represented by two adjacent delimiters. Any field whose first non-blank character is a delimiter is deemed to be delimited (so two adjacent delimiters as the first non-blank characters are treated as an empty string, not as a string containing a single delimiter).


arrayListToCsv

public static String arrayListToCsv(ArrayList<String> alIn)

arrayListToCsv

public static String arrayListToCsv(ArrayList<String> alIn,
                                    String separator,
                                    String delimiter)
arrayListToCsv produces a single string in CSV format from some fields, represented as an ArrayList of Strings. The format of the CSV string will be individual strings, separated by a separator and optionally delimited. If a field contains a separator or leading/trailing blank spaces, or if it starts with a delimiter, it will be delimited in the output string. If a delimited field contains the delimiter as part of the data, that delimiter will be represented by two adjacent delimiters. A null entry in the ArrayList is converted into an empty value; it is therefore equivalent to "".


getPattern

public static Pattern getPattern(String regex)
call the regex Pattern compile() method to get a pattern object.


getMatcher

public static Matcher getMatcher(String regex,
                                 String text)
Utility method to get a matcher based on regex - a regular expression string - match against the input text parameter.


concatArray

public static <T> T[] concatArray(T[] firstArray,
                                  T[] secondArray)
Concatenates two arrays, either of which may be null or empty. If both are null, null is returned. Otherwise, the result is an array with whatever objects were in 'firstArray' followed by whatever objects were in 'secondArray'.


error

public static void error(String msg)
Traces an error message and then throws a RuntimeException with message = the input message


error

public static void error(String msg,
                         Exception e)
Traces an error message and the input exception, and then throws a RuntimeException with message = the input message and a nested exception.


stackTraceToString

public static String stackTraceToString()
returns the callers stackTrace (in Throwable stack trace format - with " at " prefix).


stackTraceToString

public static String stackTraceToString(int stackIndex)
returns the callers stackTrace (in Throwable stack trace format - with " at " prefix).

Parameters:
stackIndex - the index in the stack to start from. '0' here is equivalent the no-parameter version of stackTraceToString. To reference your caller, use "stackTraceToString( 1 )" If stackIndex exceeds the bounds of the stack, the empty string is returned.

stackTraceToString

public static String stackTraceToString(Throwable e)
returns the callers stackTrace (in Throwable stack trace format - with " at " prefix).

Parameters:
stackIndex - the index in the stack to start from. '0' here is equivalent the no-parameter version of stackTraceToString. To reference your caller, use "stackTraceToString( 1 )" If stackIndex exceeds the bounds of the stack, the empty string is returned.

getClassSafe

public static String getClassSafe(Object object)

exitOrContinue

public static void exitOrContinue()
This exits in non-production mode, and continues in production


exitOrContinue

public static void exitOrContinue(String message)
This exits in non-production mode, and continues in production


exitOrContinue

public static void exitOrContinue(String message,
                                  Exception e)

fatalConfigError

public static void fatalConfigError(String errmsg)

fatalConfigError

public static void fatalConfigError(String errmsg,
                                    Exception e)

fatalInternalError

public static void fatalInternalError(String errmsg)
                               throws RuntimeException
Throws:
RuntimeException

fatalInternalError

public static void fatalInternalError(String errmsg,
                                      Exception e)

fatalInternalError

public static void fatalInternalError(Exception e)

fatalError

public static void fatalError(String errmsg,
                              Exception e)

exit1

public static void exit1()

isLessThanUnsigned

public static boolean isLessThanUnsigned(long n1,
                                         long n2)
Implements an unsigned comparison in Java.

This is different from a 'happensBefore' check that must handle wraparound.


isBefore

public static boolean isBefore(long t1,
                               long t2)
This compares two times t1 and t2 and deduces whether t1 is 'before' t2 (in the 'happensBefore' Java concurrent sense of the term).

The assumptions here are that

Throws:
IllegalArgumentException - if the two parameters are too far part (> 2**62).

isAfter

public static boolean isAfter(long t1,
                              long t2)
Throws:
IllegalArgumentException - if the two parameters are too far part (> 2**62).