Package net.sf.okapi.common
Class Util
- java.lang.Object
-
- net.sf.okapi.common.Util
-
public final class Util extends Object
Collection of various all-purpose helper functions.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classUtil.SUPPORTED_OSEnumeration of supported OSes
-
Field Summary
Fields Modifier and Type Field Description static StringINPUT_ROOT_DIRECTORY_VARName of the input root directory variable.static StringLINEBREAK_DOSLine-break string for DOS/Windows.static StringLINEBREAK_MACLine-break string for Macintoshstatic StringLINEBREAK_UNIXLine-break string for Unix/Linuxstatic StringMTFLAGShared flag indicating a translation that was generated using machine translation.static StringROOT_DIRECTORY_VARName of the root directory variable.static StringRTF_ENDCODEDefault RTF style for ending an external code.static StringRTF_ENDINLINEDefault RTF style for ending an internal code.static StringRTF_ENDMARKERDefault RTF style for ending an in-between source/target marker.static StringRTF_MIDMARKER1Default RTF style for the first half of a middle part of an in-between source/target marker.static StringRTF_MIDMARKER2Default RTF style for the second half of a middle part of an in-between source/target marker.static StringRTF_STARTCODEDefault RTF style for starting an external code.static StringRTF_STARTINLINEDefault RTF style for starting an internal code.static StringRTF_STARTMARKERDefault RTF style for starting an in-between source/target marker.
-
Constructor Summary
Constructors Constructor Description Util()
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static StringbuildPath(String... parts)Builds a path from given parts.static PrintWritercharsetPrintWriter(String filePath, Charset charset)Create a newPrintWriter, without automatic line flushing, writing to the specified file path and using the specified Charset.static booleancheckFlag(int value, int flag)Indicates whether a byte-flag is set or not in a given value.static <E> booleancheckIndex(int index, List<E> list)Indicates if a given index is within the list bounds.static <T> booleancheckIndex(int index, T[] array)Returns true if a given index is within the array bounds.static <T extends Comparable<T>>
Comparator<T>createComparatorHandlingNullKeys(Class<T> clazz)static booleancreateDirectories(String path)Creates the directory tree for the give full path (dir+filename)static XPathFactorycreateXPathFactory()creates an XPathFactory and tries to handle issues with saxon.static booleandeleteDirectory(File directory)Recursive function to delete the content of a given directory (including all its sub-directories.static voiddeleteDirectory(String directory, boolean contentOnly)Deletes the content of a given directory, and if requested, the directory itself.static StringdeleteLastChar(String string)Deletes the last character of a given string.static voiddeleteLastChar(StringBuilder sb)Deletes the last character of a given StringBuilder object.static StringensureLeadingSeparator(String path, boolean forceForwardSlash)Determines if a given path starts with a file name separator for the current platform.static StringensureSeparator(String path, boolean forceForwardSlash)Determines if a given path ends with a file name separator for the current platform.static StringescapeToRTF(String text, boolean convertLineBreaks, int lineBreakStyle, CharsetEncoder encoder)Escapes a given string into RTF format.static StringescapeToXML(String text, int quoteMode, boolean escapeGT, CharsetEncoder encoder)Escapes a string for XML.static StringescapeWhitespaceForXML(String text)Escape newlines and whitespace so they survive roundtrip as an xml attribute \n= \r= =static StringexpandPath(String path, String rootDir, String inputRootDir)Expand all supported variables and canonicalize (resolve ".." and ".") a path.static intfastParseInt(String s)Convert String to int .static StringfillInputRootDirectoryVariable(String original, String inputRootDir)Replaces in a given original string, a potential variable INPUT_ROOT_DIRECTORY_VAR by a given root directory.static StringfillRootDirectoryVariable(String original, String rootDir)Replaces in a given original string, a potential variable ROOT_DIRECTORY_VAR by a given root directory.static StringfillSystemEnvars(String original)Expands environment variables by replacing strings of the type ${varname} with their values as reported by the system.static <T> TfindMatch(T orig, List<T> things, boolean[] matches, Comparator<T>... cmps)Find a match in things based on the list ofComparatorstatic StringfixFilename(String fileName)Replaces unsupported characters in a given short file name (no directory path) with underscore.static StringfixFilename(String fileName, String replacer)Replaces unsupported characters in a given short file name (no directory path) with a given replacer.static StringfixPath(String path)Removes exceeding separators in a given path.static StringfixPath(String path, boolean forceOsSeparators)Removes exceeding separators in a given path.static StringformatDouble(Double value)Formats a double value so only the significant trailing zeros are displayed.static <T> Tget(T[] array, int index)Gets the element of an array for a given index.static chargetCharAt(String string, int pos)Gets a character at a given position in a string.static StringgetClassLocation(Class<?> theClass)Gets the directory location of a given class.static StringgetDirectoryName(String path)Gets the directory name of a full path.static StringgetExtension(String path)Gets the extension of a given path or filename.static StringgetFilename(String path, boolean keepExtension)Gets the filename of a path.static String[]getFilteredFiles(String directory, String suffix)Return a list of files based on suffix (i.e, .xml, .html etc.)static chargetLastChar(String string)Gets the last character of a given string.static chargetLastChar(StringBuilder sb)Gets the last character of a given StringBuilder object.static intgetLength(String string)Gets the length of a string, even a null one.static Util.SUPPORTED_OSgetOS()Get the operating systemstatic intgetPercentage(int part, int total)Calculates safely a percentage.static StringgetTempDirectory()Gets the default system temporary directory to use for the current user.static StringgetTextContent(Node node)Gets the text content of the first TEXT child of an element node.static <K,V>
VgetValue(Map<K,V> map, K key, V defaultValue)Safely returns a value for a given key in a given map.static StringintToStr(int value)Converts an integer value to a string.static booleanisEmpty(CharSequence sequence)Indicates if a givenCharSequenceis null or empty.static booleanisEmpty(Object[] e)Indicates if an array is null or empty.static booleanisEmpty(String string)Indicates if a given string is null or empty.static booleanisEmpty(StringBuilder sb)Indicates if a StringBuilder object is null or empty.static booleanisEmpty(String string, boolean ignoreWS)Indicates if a string is null or empty, optionally ignoring the white spaces.static <E> booleanisEmpty(List<E> e)Indicates if a given list is null or empty.static <K,V>
booleanisEmpty(Map<K,V> map)Indicates if a given map is null or empty.static <E> booleanisEmpty(Set<E> e)Indicates if a givenSetis null or empty.static booleanisNullOrEmpty(LocaleId locale)Indicates if a locale id is null or empty.static booleanisOSCaseSensitive()Indicates if the current OS is case-sensitive.static booleanisSameLanguage(String lang1, String lang2, boolean ignoreRegion)Indicates if two language codes are 'the same'.static booleanisValidInXML(int ch)Indicates if the given character is valid in XML.static StringlongestCommonDir(boolean ignoreCase, String... directories)Gets the longest common path between directories on a given list.static StringlongestCommonDir(String currentDir, String newDir, boolean ignoreCase)Gets the longest common path between an existing current directory and a new one.static StringmakeId(String text)Creates a string Identifier based on the hash code of the given text.static StringmakeURIFromPath(String pathOrUri)Makes a URI string from a path.static intmin(int... values)Returns the smallest value in a given array of values.static StringnormalizeNewlines(String text)Converts all \r\n and \r to linefeed (\n)static intnormalizeRange(double low, double high, double value)Given an integer range and a value normalize that value on a scale between 0 and 100.static voidopenURL(String url)Opens the specified page in a web browser (Java 1.5 compatible).static voidopenWikiTopic(String topic)Opens a given topic of the OkapiWiki.static ReaderskipBOM(Reader r)Given a Reader, discard any leading BOM.static doublestrToDouble(String value, double doubleDefault)Converts a string to a double.static intstrToInt(String value, int intDefault)Converts a string to an integer.static longstrToLong(String value, long longDefault)Converts a string to a long.static URItoURI(String pathOrUri)Creates a new URI object from a path or a URI string.static URLtoURL(String pathOrUri)Creates a new URL object from a path or a URI string.static StringtrimEnd(String text, String chars)Removes from the end of a string any of the specified characters.static StringtrimStart(String text, String chars)Removes from the start of a string any of the specified characters.static StringunescapeWhitespaceForXML(String text)static URLURItoURL(URI uri)Convert a URI to a URL.static StringURLDecodeUTF8(String s)Decodes a application/x-www-form-urlencoded string using UTF-8.static StringURLEncodeUTF8(String s)Translates a string into application/x-www-form-urlencoded format using UTF-8.static URIURLtoURI(URL url)Convert a URL to a URI.static booleanvalidateVariables(String text, boolean allowEnvar, boolean allowRootDir, boolean allowInputRootDir)Check a piece of text to make sure that all contained variables (${foo}) are resolvable by the fill...() methods in this class.static voidwriteBOMIfNeeded(Writer writer, boolean bomOnUTF8, String encoding)Writes a Byte-Order-Mark if the encoding indicates it is needed.
-
-
-
Field Detail
-
ROOT_DIRECTORY_VAR
public static final String ROOT_DIRECTORY_VAR
Name of the root directory variable.- See Also:
- Constant Field Values
-
INPUT_ROOT_DIRECTORY_VAR
public static final String INPUT_ROOT_DIRECTORY_VAR
Name of the input root directory variable.- See Also:
- Constant Field Values
-
LINEBREAK_DOS
public static final String LINEBREAK_DOS
Line-break string for DOS/Windows.- See Also:
- Constant Field Values
-
LINEBREAK_UNIX
public static final String LINEBREAK_UNIX
Line-break string for Unix/Linux- See Also:
- Constant Field Values
-
LINEBREAK_MAC
public static final String LINEBREAK_MAC
Line-break string for Macintosh- See Also:
- Constant Field Values
-
RTF_STARTCODE
public static final String RTF_STARTCODE
Default RTF style for starting an external code.- See Also:
- Constant Field Values
-
RTF_ENDCODE
public static final String RTF_ENDCODE
Default RTF style for ending an external code.- See Also:
- Constant Field Values
-
RTF_STARTINLINE
public static final String RTF_STARTINLINE
Default RTF style for starting an internal code.- See Also:
- Constant Field Values
-
RTF_ENDINLINE
public static final String RTF_ENDINLINE
Default RTF style for ending an internal code.- See Also:
- Constant Field Values
-
RTF_STARTMARKER
public static final String RTF_STARTMARKER
Default RTF style for starting an in-between source/target marker.- See Also:
- Constant Field Values
-
RTF_MIDMARKER1
public static final String RTF_MIDMARKER1
Default RTF style for the first half of a middle part of an in-between source/target marker.- See Also:
- Constant Field Values
-
RTF_MIDMARKER2
public static final String RTF_MIDMARKER2
Default RTF style for the second half of a middle part of an in-between source/target marker.- See Also:
- Constant Field Values
-
RTF_ENDMARKER
public static final String RTF_ENDMARKER
Default RTF style for ending an in-between source/target marker.- See Also:
- Constant Field Values
-
MTFLAG
public static final String MTFLAG
Shared flag indicating a translation that was generated using machine translation.- See Also:
- Constant Field Values
-
-
Method Detail
-
normalizeNewlines
public static String normalizeNewlines(String text)
Converts all \r\n and \r to linefeed (\n)- Parameters:
text- the text to convert- Returns:
- converted string
-
trimStart
public static String trimStart(String text, String chars)
Removes from the start of a string any of the specified characters.- Parameters:
text- string to trim.chars- list of the characters to trim.- Returns:
- The trimmed string.
-
trimEnd
public static String trimEnd(String text, String chars)
Removes from the end of a string any of the specified characters.- Parameters:
text- string to trim.chars- list of the characters to trim.- Returns:
- the trimmed string.
-
getDirectoryName
public static String getDirectoryName(String path)
Gets the directory name of a full path.- Parameters:
path- full path from where to extract the directory name. The path can be a URL path (e.g. "/C:/test/file.ext").- Returns:
- The directory name (without the final separator), or an empty string if path is a filename.
-
ensureSeparator
public static String ensureSeparator(String path, boolean forceForwardSlash)
Determines if a given path ends with a file name separator for the current platform. If not, the file separator is appended to the path.- Parameters:
path- the given path.forceForwardSlash- true if the ending separator must be a forward slash.- Returns:
- the given path ending with the file name separator.
-
ensureLeadingSeparator
public static String ensureLeadingSeparator(String path, boolean forceForwardSlash)
Determines if a given path starts with a file name separator for the current platform. If not, the file separator is prefixed to the path.- Parameters:
path- the given path.forceForwardSlash- true if the leading separator must be a forward slash.- Returns:
- the given path starting with the file name separator.
-
fixFilename
public static String fixFilename(String fileName, String replacer)
Replaces unsupported characters in a given short file name (no directory path) with a given replacer.- Parameters:
fileName- the given short file namereplacer- the given replacer- Returns:
- the given file name with fixed unsupported characters
-
fixPath
public static String fixPath(String path)
Removes exceeding separators in a given path. Normalizes the given path to contain OS-specific file separators.- Parameters:
path- the given path- Returns:
- the fixed given path
-
fixPath
public static String fixPath(String path, boolean forceOsSeparators)
Removes exceeding separators in a given path. Optionally normalizes the given path to contain OS-specific file separators.- Parameters:
path- the given pathforceOsSeparators- true to ensure the path contains only OS-specific separators- Returns:
- the fixed given path
-
fixFilename
public static String fixFilename(String fileName)
Replaces unsupported characters in a given short file name (no directory path) with underscore.- Parameters:
fileName- the given short file name- Returns:
- the given file name with fixed unsupported characters
-
buildPath
public static String buildPath(String... parts)
Builds a path from given parts. Path separators are normalized.- Parameters:
parts- parts of the path- Returns:
- path containing the given parts separated with a file name separator for the current platform.
-
getFilteredFiles
public static String[] getFilteredFiles(String directory, String suffix)
Return a list of files based on suffix (i.e, .xml, .html etc.)- Parameters:
directory- - directory where files are locatedsuffix- - the sufix used to filter files- Returns:
- - list of files matching the suffix
- Throws:
URISyntaxException- if the syntax is not correct.
-
createDirectories
public static boolean createDirectories(String path)
Creates the directory tree for the give full path (dir+filename)- Parameters:
path- directory to create and filename. If you want to pass only a directory name make sure it has a trailing separator (e.g. "c:\project\tmp\"). The path can be a URL path (e.g. "/C:/test/file.ext").- Returns:
- true if one of more directories were created or if there was no directory to create, false otherwise (an error occurred)
-
escapeWhitespaceForXML
public static String escapeWhitespaceForXML(String text)
Escape newlines and whitespace so they survive roundtrip as an xml attribute \n= \r= =- Parameters:
text- - original text- Returns:
- escaped string
-
escapeToXML
public static String escapeToXML(String text, int quoteMode, boolean escapeGT, CharsetEncoder encoder)
Escapes a string for XML.- Parameters:
text- string to escape.quoteMode- 0=no quote escaped, 1=apos and quot, 2=#39 and quot, and 3=quot only.escapeGT- true to always escape '>' to gtencoder- the character set encoder to use to detect un-supported character, or null to never escape normal characters.- Returns:
- the escaped string.
-
escapeToRTF
public static String escapeToRTF(String text, boolean convertLineBreaks, int lineBreakStyle, CharsetEncoder encoder)
Escapes a given string into RTF format.- Parameters:
text- the string to convert.convertLineBreaks- Indicates if the line-breaks should be converted.lineBreakStyle- Type of line-break conversion. 0=do nothing special, 1=close then re-open as external, 2=close then re-open as internal.encoder- Encoder to use for the extended characters.- Returns:
- The input string escaped to RTF.
-
deleteDirectory
public static boolean deleteDirectory(File directory)
Recursive function to delete the content of a given directory (including all its sub-directories. This does not delete the original parent directory.- Parameters:
directory- the directory of the content to delete.- Returns:
- true if the content was deleted, false otherwise.
-
deleteDirectory
public static void deleteDirectory(String directory, boolean contentOnly)
Deletes the content of a given directory, and if requested, the directory itself. Sub-directories and their content are part of the deleted content.- Parameters:
directory- the path of the directory to deletecontentOnly- indicates if the directory itself should be removed. If this flag is true, only the content is deleted.
-
getFilename
public static String getFilename(String path, boolean keepExtension)
Gets the filename of a path.- Parameters:
path- the path from where to get the filename. The path can be a URL path (e.g. "/C:/test/file.ext").keepExtension- true to keep the existing extension, false to remove it.- Returns:
- the filename with or without extension.
-
getExtension
public static String getExtension(String path)
Gets the extension of a given path or filename.- Parameters:
path- the original path or filename.- Returns:
- the last extension of the filename (including the period), or empty if there is no period in the filename. If the filename ends with a period, the return is a period. Never returns null.
-
makeURIFromPath
public static String makeURIFromPath(String pathOrUri)
Makes a URI string from a path. If the path itself can be recognized as a string URI already, it is passed unchanged. For example "C:\test" and "file:///C:/test" will both return "file:///C:/test" encoded as URI.- Parameters:
pathOrUri- the path to change to URI string.- Returns:
- the URI string.
- Throws:
OkapiUnsupportedEncodingException- if UTF-8 is not supported (can't happen).
-
toURI
public static URI toURI(String pathOrUri)
Creates a new URI object from a path or a URI string.- Parameters:
pathOrUri- the path or URI string to use.- Returns:
- the new URI object for the given path or URI string.
-
toURL
public static URL toURL(String pathOrUri)
Creates a new URL object from a path or a URI string. This is a convenience wrapper to catch the various conversion exceptions.- Parameters:
pathOrUri- the path or URI string to use.- Returns:
- the new URI object for the given path or URI string.
-
URLtoURI
public static URI URLtoURI(URL url)
Convert a URL to a URI. Convenience method to avoid catchingURISyntaxExceptionall over the place.- Parameters:
url- The URL to convert- Returns:
- The new URI object for the given URL
-
URItoURL
public static URL URItoURL(URI uri)
Convert a URI to a URL. Convenience method to avoid catchingMalformedURLException.- Parameters:
uri- to convert- Returns:
- the resulting url
-
longestCommonDir
public static String longestCommonDir(String currentDir, String newDir, boolean ignoreCase)
Gets the longest common path between an existing current directory and a new one.- Parameters:
currentDir- the current longest common path.newDir- the new directory to compare with.ignoreCase- true if the method should ignore cases differences.- Returns:
- the longest sub-directory that is common to both directories. This can be a null if the current directory is null, or empty if there is no common path.
-
longestCommonDir
public static String longestCommonDir(boolean ignoreCase, String... directories)
Gets the longest common path between directories on a given list.- Parameters:
ignoreCase- if the method should ignore cases differences.directories- the given list of directories.- Returns:
- the longest sub-directory that is common to all directories. This can be a null or empty string.
-
isOSCaseSensitive
public static boolean isOSCaseSensitive()
Indicates if the current OS is case-sensitive.- Returns:
- true if the current OS is case-sensitive, false if otherwise.
-
writeBOMIfNeeded
public static void writeBOMIfNeeded(Writer writer, boolean bomOnUTF8, String encoding)
Writes a Byte-Order-Mark if the encoding indicates it is needed. This methods must be the first call after opening the writer.- Parameters:
writer- writer where to output the BOM.bomOnUTF8- indicates if we should use a BOM on UTF-8 files.encoding- encoding of the output.- Throws:
OkapiIOException- if anything went wrong with the writing.
-
getTempDirectory
public static String getTempDirectory()
Gets the default system temporary directory to use for the current user. The directory path returned has never a trailing separator.- Returns:
- The directory path of the temporary directory to use, without trailing separator.
-
getTextContent
public static String getTextContent(Node node)
Gets the text content of the first TEXT child of an element node. This is to use instead of node.getTextContent() which does not work with some Macintosh Java VMs. Note this work-around get only the first TEXT node.- Parameters:
node- the container element.- Returns:
- the text of the first TEXT child node.
-
getPercentage
public static int getPercentage(int part, int total)Calculates safely a percentage. If the total is 0, the methods return 1.- Parameters:
part- the part of the total.total- the total.- Returns:
- the percentage of part in total.
-
makeId
public static String makeId(String text)
Creates a string Identifier based on the hash code of the given text.- Parameters:
text- the text to make an ID for.- Returns:
- The string identifier for the given text.
-
isSameLanguage
public static boolean isSameLanguage(String lang1, String lang2, boolean ignoreRegion)
Indicates if two language codes are 'the same'. The comparison ignores case differences, and if the parameter ignoreRegion is true, any part after the first '-' is also ignored. Note that the character '_' is treated like a character '-'.- Parameters:
lang1- first language code to compare.lang2- second language code to compare.ignoreRegion- True to ignore any part after the first separator, false to take it into account.- Returns:
- true if, according the given options, the two language codes are the same. False otherwise.
-
isEmpty
public static boolean isEmpty(String string)
Indicates if a given string is null or empty.- Parameters:
string- the string to check.- Returns:
- true if the given string is null or empty.
-
isEmpty
public static boolean isEmpty(CharSequence sequence)
Indicates if a givenCharSequenceis null or empty.- Parameters:
sequence- the sequence to check.- Returns:
- true if the given sequence is null or empty.
-
isNullOrEmpty
public static boolean isNullOrEmpty(LocaleId locale)
Indicates if a locale id is null or empty.- Parameters:
locale- the locale id to examine.- Returns:
- true if the given locale id is null or empty, false otherwise.
-
isEmpty
public static boolean isEmpty(String string, boolean ignoreWS)
Indicates if a string is null or empty, optionally ignoring the white spaces.- Parameters:
string- the string to examine.ignoreWS- true to ignore white spaces.- Returns:
- true if the given string is null, or empty. The argument ignoreWS is true a string with only white spaces is concidered empty.
-
isEmpty
public static boolean isEmpty(StringBuilder sb)
Indicates if a StringBuilder object is null or empty.- Parameters:
sb- the object to examine.- Returns:
- true if the given object is null or empty.
-
isEmpty
public static <E> boolean isEmpty(List<E> e)
Indicates if a given list is null or empty.- Type Parameters:
E- the type of the elements in the list.- Parameters:
e- the list to examine.- Returns:
- true if the list is null or empty.
-
isEmpty
public static <E> boolean isEmpty(Set<E> e)
Indicates if a givenSetis null or empty.- Type Parameters:
E- the type of the elements in the set.- Parameters:
e- the set to examine.- Returns:
- true if the set is null or empty.
-
isEmpty
public static <K,V> boolean isEmpty(Map<K,V> map)
Indicates if a given map is null or empty.- Type Parameters:
K- the type of the map's keys.V- the type of the map's values.- Parameters:
map- the map to examine.- Returns:
- true if the map is null or empty,
-
isEmpty
public static boolean isEmpty(Object[] e)
Indicates if an array is null or empty.- Parameters:
e- the array to examine.- Returns:
- true if the given array is null or empty.
-
getLength
public static int getLength(String string)
Gets the length of a string, even a null one.- Parameters:
string- the string to examine.- Returns:
- the length of the given string, 0 if the string is null.
-
getCharAt
public static char getCharAt(String string, int pos)
Gets a character at a given position in a string. The string can be null and the position can be beyond the last character.- Parameters:
string- the string to examine.pos- the position of the character to retrieve.- Returns:
- the character at the given position, or '\0' if the string is null or if the position is beyond the length of the string.
-
getLastChar
public static char getLastChar(String string)
Gets the last character of a given string. The string can be null or empty.- Parameters:
string- the string to examine.- Returns:
- the last character of the given string, or '\0' if the string is null or empty.
-
deleteLastChar
public static String deleteLastChar(String string)
Deletes the last character of a given string. The string can be null or empty.- Parameters:
string- the string where to remove the character.- Returns:
- a new string where the last character has been removed, or an empty string if the given string was null or empty.
-
getLastChar
public static char getLastChar(StringBuilder sb)
Gets the last character of a given StringBuilder object. The object can be null or empty.- Parameters:
sb- the StringBuilder object to examine.- Returns:
- the last character of the given StringBuilder object, or '\0' if the object is null or empty.
-
deleteLastChar
public static void deleteLastChar(StringBuilder sb)
Deletes the last character of a given StringBuilder object. If the object is null or empty no character are removed.- Parameters:
sb- the StringBuilder object where to remove the character.
-
checkIndex
public static <E> boolean checkIndex(int index, List<E> list)Indicates if a given index is within the list bounds.- Type Parameters:
E- the type of the list's elements.- Parameters:
index- the given index.list- the given list.- Returns:
- true if a given index is within the list bounds.
-
intToStr
public static String intToStr(int value)
Converts an integer value to a string. This method simply callsString.valueOf(intValue);.- Parameters:
value- the value to convert.- Returns:
- the string representation of the given value.
-
strToInt
public static int strToInt(String value, int intDefault)
Converts a string to an integer. If the conversion fails the method returns the given default value.- Parameters:
value- the string to convert.intDefault- the default value to use if the conversion fails.- Returns:
- the integer value of the string, or the provided default value if the conversion failed.
-
fastParseInt
public static int fastParseInt(String s)
Convert String to int . Almost 3x faster than Integer.valueOf()- Parameters:
s- - string to be converted to int- Returns:
- int represented by string
- Throws:
NumberFormatException- if theStringdoes not represent a number.
-
strToLong
public static long strToLong(String value, long longDefault)
Converts a string to a long. If the conversion fails the method returns the given default value.- Parameters:
value- the string to convert.longDefault- the default value to use if the conversion fails.- Returns:
- the long value of the string, or the provided default value if the conversion failed.
-
strToDouble
public static double strToDouble(String value, double doubleDefault)
Converts a string to a double. If the conversion fails the method returns the given default value.- Parameters:
value- the string to convert.doubleDefault- the default value to use if the conversion fails.- Returns:
- the double value of the string, or the provided default value if the conversion failed.
-
get
public static <T> T get(T[] array, int index)Gets the element of an array for a given index. the method returns null if the index is out of bounds.- Type Parameters:
T- the type of the array's elements.- Parameters:
array- the array where to lookup the element.index- the index.- Returns:
- the element of the array for the given index, or null if the index is out of bounds, or if the element is null.
-
checkIndex
public static <T> boolean checkIndex(int index, T[] array)Returns true if a given index is within the array bounds.- Type Parameters:
T- the type of the array's elements.- Parameters:
index- the given index.array- the given list.- Returns:
- true if a given index is within the array bounds.
-
checkFlag
public static boolean checkFlag(int value, int flag)Indicates whether a byte-flag is set or not in a given value.- Parameters:
value- the value to check.flag- the flag to look for.- Returns:
- true if the flag is set, false if it is not.
-
getOS
public static Util.SUPPORTED_OS getOS()
Get the operating system- Returns:
- one of WINDOWS, MAC or LINUX
-
openURL
public static void openURL(String url)
Opens the specified page in a web browser (Java 1.5 compatible).This is based on the public domain class BareBonesBrowserLaunch from Dem Pilafian at (www.centerkey.com/java/browser)
- Parameters:
url- the URL of the page to open.
-
openWikiTopic
public static void openWikiTopic(String topic)
Opens a given topic of the OkapiWiki.- Parameters:
topic- the title of the topic/page.
-
getClassLocation
public static String getClassLocation(Class<?> theClass)
Gets the directory location of a given class. The value returned can be the directory where the .class file is located, or, if the class in a JAR file, the directory where the .jar file is located.- Parameters:
theClass- the class to query.- Returns:
- the directory location of the given class, or null if an error occurs.
-
fillRootDirectoryVariable
public static String fillRootDirectoryVariable(String original, String rootDir)
Replaces in a given original string, a potential variable ROOT_DIRECTORY_VAR by a given root directory.- Parameters:
original- the original string where to perform the replacement.rootDir- the root directory. If null it will be automatically set to the user home directory.- Returns:
- the original string with ROOT_DIRECTORY_VAR replaced if it was there.
-
fillInputRootDirectoryVariable
public static String fillInputRootDirectoryVariable(String original, String inputRootDir)
Replaces in a given original string, a potential variable INPUT_ROOT_DIRECTORY_VAR by a given root directory.- Parameters:
original- the original string where to perform the replacement.inputRootDir- the input root directory. If null it will be automatically set to an empty string.- Returns:
- the original string with INPUT_ROOT_DIRECTORY_VAR replaced if it was there.
-
fillSystemEnvars
public static String fillSystemEnvars(String original)
Expands environment variables by replacing strings of the type ${varname} with their values as reported by the system.- Parameters:
original- The original string in which to perform the replacement- Returns:
- The original string with all environment variables expanded
-
validateVariables
public static boolean validateVariables(String text, boolean allowEnvar, boolean allowRootDir, boolean allowInputRootDir)
Check a piece of text to make sure that all contained variables (${foo}) are resolvable by the fill...() methods in this class.- Parameters:
text- The text to checkallowEnvar- Whether or not to allow system environment variablesallowRootDir- Whether or not to allow ${rootDir}allowInputRootDir- Whether or not to allow ${inputRootDir}- Returns:
- Whether or not the input text's variables are valid
-
expandPath
public static String expandPath(String path, String rootDir, String inputRootDir) throws IOException
Expand all supported variables and canonicalize (resolve ".." and ".") a path. If the input path has no variables, it is returned unchanged. rootDir and inputRootDir can be null.- Parameters:
path- The path to expandrootDir- The directory to expand ${rootDir} intoinputRootDir- The directory to expand ${inputRootDir} into- Returns:
- The expanded path
- Throws:
IOException- If canonicalizing fails
-
min
public static int min(int... values)
Returns the smallest value in a given array of values.- Parameters:
values- the given array- Returns:
- the smallest value in the array
-
getValue
public static <K,V> V getValue(Map<K,V> map, K key, V defaultValue)
Safely returns a value for a given key in a given map.- Type Parameters:
V- the type of keys maintained by the given mapK- the type of mapped values of the given map- Parameters:
map- the given mapkey- the key whose associated value is to be returneddefaultValue- the default value to be returned if the key is not found- Returns:
- the value to which the specified key is mapped, or defaultValue if the given map contains no mapping for the given key
-
normalizeRange
public static int normalizeRange(double low, double high, double value)Given an integer range and a value normalize that value on a scale between 0 and 100.- Parameters:
low- - lowest value of the rangehigh- - highest value of the rangevalue- - the value that needs to be mapped to 0-100- Returns:
- mapped value, a number between 0 and 100
-
formatDouble
public static String formatDouble(Double value)
Formats a double value so only the significant trailing zeros are displayed. Removes the decimal period if there are no significant decimal digits.- Parameters:
value- the double value to format (can be null).- Returns:
- the formatted value or an empty string.
-
isValidInXML
public static boolean isValidInXML(int ch)
Indicates if the given character is valid in XML. See http://www.w3.org/TR/xml/#charsets for details.- Parameters:
ch- the character to test.- Returns:
- true if the given character is valid in XML, false otherwise.
-
URLDecodeUTF8
public static String URLDecodeUTF8(String s)
Decodes a application/x-www-form-urlencoded string using UTF-8. This wraps a call toURLDecoder.decode(String, String), passing UTF-8 as the argument and wrapping the exception as anIllegalStateException. This exists because URLDecoder does not offer a signature that takes aCharset.- Parameters:
s- the String to decode- Returns:
- the newly decoded String
- Throws:
IllegalStateException- if UTF-8 isn't recognized as a valid encoding, which should never happen.
-
URLEncodeUTF8
public static String URLEncodeUTF8(String s)
Translates a string into application/x-www-form-urlencoded format using UTF-8. This wraps a call toURLEncoder.encode(String, String), passing UTF-8 as the argument and wrapping the exception as anIllegalStateException. This exists because URLEncoder does not offer a signature that takes aCharset.- Parameters:
s- the String to be translated- Returns:
- the translated String
- Throws:
IllegalStateException- if UTF-8 isn't recognized as a valid encoding, which should never happen.
-
charsetPrintWriter
public static PrintWriter charsetPrintWriter(String filePath, Charset charset) throws FileNotFoundException
Create a newPrintWriter, without automatic line flushing, writing to the specified file path and using the specified Charset. PrintWriter doesn't provide this signature and requires a charset name be passed instead, which requires additional exception handling.- Parameters:
filePath- the file to use as the destination of this writer.charset- charset to use when writing to the file- Returns:
- new PrintWriter instance
- Throws:
FileNotFoundException- if the given string does not denote an existing, writable regular file and a new regular file of that name can't be created.
-
skipBOM
public static Reader skipBOM(Reader r) throws IOException
Given a Reader, discard any leading BOM.- Parameters:
r- the reader.- Returns:
- a Reader instance representing the remaining content. This may not be the same Reader instance that was passed in.
- Throws:
IOException- if anything goes wrong when reading.
-
createComparatorHandlingNullKeys
public static <T extends Comparable<T>> Comparator<T> createComparatorHandlingNullKeys(Class<T> clazz)
- Type Parameters:
T- the type of the class.- Parameters:
clazz- the class.- Returns:
- a comparator for
TreeMapthat accepts null keys.
-
createXPathFactory
public static XPathFactory createXPathFactory()
creates an XPathFactory and tries to handle issues with saxon.- Returns:
- the
XPathFactorycreated. - See Also:
- https://saxonica.plan.io/issues/1944, http://sourceforge.net/p/saxon/mailman/message/33221102/
-
findMatch
public static <T> T findMatch(T orig, List<T> things, boolean[] matches, Comparator<T>... cmps)Find a match in things based on the list ofComparator- Type Parameters:
T- The type of the thing we are looking for- Parameters:
orig- what we are looking forthings- the things we are looking inmatches- boolean arrays marking the matches already foundcmps- the list ofComparator- Returns:
- the match or null if nothing found
-
-