public final class Util extends Object
| Modifier and Type | Class and Description |
|---|---|
static class |
Util.SUPPORTED_OS
Enumeration of supported OSes
|
| Modifier and Type | Field and Description |
|---|---|
static String |
INPUT_ROOT_DIRECTORY_VAR
Name of the input root directory variable.
|
static String |
LINEBREAK_DOS
Line-break string for DOS/Windows.
|
static String |
LINEBREAK_MAC
Line-break string for Macintosh
|
static String |
LINEBREAK_UNIX
Line-break string for Unix/Linux
|
static String |
MTFLAG
Shared flag indicating a translation that was generated using machine translation.
|
static String |
ROOT_DIRECTORY_VAR
Name of the root directory variable.
|
static String |
RTF_ENDCODE
Default RTF style for ending an external code.
|
static String |
RTF_ENDINLINE
Default RTF style for ending an internal code.
|
static String |
RTF_ENDMARKER
Default RTF style for ending an in-between source/target marker.
|
static String |
RTF_MIDMARKER1
Default RTF style for the first half of a middle part of an in-between source/target marker.
|
static String |
RTF_MIDMARKER2
Default RTF style for the second half of a middle part of an in-between source/target marker.
|
static String |
RTF_STARTCODE
Default RTF style for starting an external code.
|
static String |
RTF_STARTINLINE
Default RTF style for starting an internal code.
|
static String |
RTF_STARTMARKER
Default RTF style for starting an in-between source/target marker.
|
| Constructor and Description |
|---|
Util() |
| Modifier and Type | Method and Description |
|---|---|
static String |
buildPath(String... parts)
Builds a path from given parts.
|
static PrintWriter |
charsetPrintWriter(String filePath,
Charset charset)
Create a new
PrintWriter, without automatic line flushing,
writing to the specified file path and using the specified Charset. |
static boolean |
checkFlag(int value,
int flag)
Indicates whether a byte-flag is set or not in a given value.
|
static <E> boolean |
checkIndex(int index,
List<E> list)
Indicates if a given index is within the list bounds.
|
static <T> boolean |
checkIndex(int index,
T[] array)
Returns true if a given index is within the array bounds.
|
static <T extends Comparable<T>> |
createComparatorHandlingNullKeys(Class<T> clazz) |
static boolean |
createDirectories(String path)
Creates the directory tree for the give full path (dir+filename)
|
static XPathFactory |
createXPathFactory()
creates an XPathFactory and tries to handle issues with saxon.
|
static boolean |
deleteDirectory(File directory)
Recursive function to delete the content of a given directory (including
all its sub-directories.
|
static void |
deleteDirectory(String directory,
boolean contentOnly)
Deletes the content of a given directory, and if requested, the directory
itself.
|
static String |
deleteLastChar(String string)
Deletes the last character of a given string.
|
static void |
deleteLastChar(StringBuilder sb)
Deletes the last character of a given StringBuilder object.
|
static String |
ensureLeadingSeparator(String path,
boolean forceForwardSlash)
Determines if a given path starts with a file name separator for the current platform.
|
static String |
ensureSeparator(String path,
boolean forceForwardSlash)
Determines if a given path ends with a file name separator for the current platform.
|
static String |
escapeToRTF(String text,
boolean convertLineBreaks,
int lineBreakStyle,
CharsetEncoder encoder)
Escapes a given string into RTF format.
|
static String |
escapeToXML(String text,
int quoteMode,
boolean escapeGT,
CharsetEncoder encoder)
Escapes a string for XML.
|
static String |
escapeWhitespaceForXML(String text)
Escape newlines and whitespace so they survive roundtrip as an xml attribute
\n=
\r=
=
|
static String |
expandPath(String path,
String rootDir,
String inputRootDir)
Expand all supported variables and canonicalize (resolve ".." and ".")
a path.
|
static int |
fastParseInt(String s)
Convert String to int .
|
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.
|
static String |
fillRootDirectoryVariable(String original,
String rootDir)
Replaces in a given original string, a potential variable ROOT_DIRECTORY_VAR by a given root directory.
|
static String |
fillSystemEnvars(String original)
Expands environment variables by replacing strings of the type
${varname} with their values as reported by the system.
|
static <T> T |
findMatch(T orig,
List<T> things,
boolean[] matches,
Comparator<T>... cmps)
Find a match in things based on the list of
Comparator |
static String |
fixFilename(String fileName)
Replaces unsupported characters in a given short file name (no directory path) with underscore.
|
static String |
fixFilename(String fileName,
String replacer)
Replaces unsupported characters in a given short file name (no directory path) with a given replacer.
|
static String |
fixPath(String path)
Removes exceeding separators in a given path.
|
static String |
fixPath(String path,
boolean forceOsSeparators)
Removes exceeding separators in a given path.
|
static String |
formatDouble(Double value)
Formats a double value so only the significant trailing zeros are displayed.
|
static <T> T |
get(T[] array,
int index)
Gets the element of an array for a given index.
|
static char |
getCharAt(String string,
int pos)
Gets a character at a given position in a string.
|
static String |
getClassLocation(Class<?> theClass)
Gets the directory location of a given class.
|
static String |
getDirectoryName(String path)
Gets the directory name of a full path.
|
static String |
getExtension(String path)
Gets the extension of a given path or filename.
|
static String |
getFilename(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 char |
getLastChar(String string)
Gets the last character of a given string.
|
static char |
getLastChar(StringBuilder sb)
Gets the last character of a given StringBuilder object.
|
static int |
getLength(String string)
Gets the length of a string, even a null one.
|
static Util.SUPPORTED_OS |
getOS()
Get the operating system
|
static int |
getPercentage(int part,
int total)
Calculates safely a percentage.
|
static String |
getTempDirectory()
Gets the default system temporary directory to use for the current user.
|
static String |
getTextContent(Node node)
Gets the text content of the first TEXT child of an element node.
|
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.
|
static String |
intToStr(int value)
Converts an integer value to a string.
|
static boolean |
isEmpty(CharSequence sequence)
Indicates if a given
CharSequence is null or empty. |
static <E> boolean |
isEmpty(List<E> e)
Indicates if a given list is null or empty.
|
static <K,V> boolean |
isEmpty(Map<K,V> map)
Indicates if a given map is null or empty.
|
static boolean |
isEmpty(Object[] e)
Indicates if an array is null or empty.
|
static <E> boolean |
isEmpty(Set<E> e)
Indicates if a given
Set is null or empty. |
static boolean |
isEmpty(String string)
Indicates if a given string is null or empty.
|
static boolean |
isEmpty(String string,
boolean ignoreWS)
Indicates if a string is null or empty, optionally ignoring the white spaces.
|
static boolean |
isEmpty(StringBuilder sb)
Indicates if a StringBuilder object is null or empty.
|
static boolean |
isNullOrEmpty(LocaleId locale)
Indicates if a locale id is null or empty.
|
static boolean |
isOSCaseSensitive()
Indicates if the current OS is case-sensitive.
|
static boolean |
isSameLanguage(String lang1,
String lang2,
boolean ignoreRegion)
Indicates if two language codes are 'the same'.
|
static boolean |
isValidInXML(int ch)
Indicates if the given character is valid in XML.
|
static String |
longestCommonDir(boolean ignoreCase,
String... directories)
Gets the longest common path between directories on a given list.
|
static String |
longestCommonDir(String currentDir,
String newDir,
boolean ignoreCase)
Gets the longest common path between an existing current directory and a
new one.
|
static String |
makeId(String text)
Creates a string Identifier based on the hash code of the given text.
|
static String |
makeURIFromPath(String pathOrUri)
Makes a URI string from a path.
|
static int |
min(int... values)
Returns the smallest value in a given array of values.
|
static String |
normalizeNewlines(String text)
Converts all \r\n and \r to linefeed (\n)
|
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.
|
static void |
openURL(String url)
Opens the specified page in a web browser (Java 1.5 compatible).
|
static void |
openWikiTopic(String topic)
Opens a given topic of the OkapiWiki.
|
static Reader |
skipBOM(Reader r)
Given a Reader, discard any leading BOM.
|
static double |
strToDouble(String value,
double doubleDefault)
Converts a string to a double.
|
static int |
strToInt(String value,
int intDefault)
Converts a string to an integer.
|
static long |
strToLong(String value,
long longDefault)
Converts a string to a long.
|
static URI |
toURI(String pathOrUri)
Creates a new URI object from a path or a URI string.
|
static URL |
toURL(String pathOrUri)
Creates a new URL object from a path or a URI string.
|
static String |
trimEnd(String text,
String chars)
Removes from the end of a string any of the specified characters.
|
static String |
trimStart(String text,
String chars)
Removes from the start of a string any of the specified characters.
|
static String |
unescapeWhitespaceForXML(String text) |
static URL |
URItoURL(URI uri)
Convert a URI to a URL.
|
static String |
URLDecodeUTF8(String s)
Decodes a application/x-www-form-urlencoded string using UTF-8.
|
static String |
URLEncodeUTF8(String s)
Translates a string into application/x-www-form-urlencoded format using
UTF-8.
|
static URI |
URLtoURI(URL url)
Convert a URL to a URI.
|
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.
|
static void |
writeBOMIfNeeded(Writer writer,
boolean bomOnUTF8,
String encoding)
Writes a Byte-Order-Mark if the encoding indicates it is needed.
|
public static final String ROOT_DIRECTORY_VAR
public static final String INPUT_ROOT_DIRECTORY_VAR
public static final String LINEBREAK_DOS
public static final String LINEBREAK_UNIX
public static final String LINEBREAK_MAC
public static final String RTF_STARTCODE
public static final String RTF_ENDCODE
public static final String RTF_STARTINLINE
public static final String RTF_ENDINLINE
public static final String RTF_STARTMARKER
public static final String RTF_MIDMARKER1
public static final String RTF_MIDMARKER2
public static final String RTF_ENDMARKER
public static final String MTFLAG
public static String normalizeNewlines(String text)
text - the text to convertpublic static String trimStart(String text, String chars)
text - string to trim.chars - list of the characters to trim.public static String trimEnd(String text, String chars)
text - string to trim.chars - list of the characters to trim.public static String getDirectoryName(String path)
path - full path from where to extract the directory name. The path
can be a URL path (e.g. "/C:/test/file.ext").public static String ensureSeparator(String path, boolean forceForwardSlash)
path - the given path.forceForwardSlash - true if the ending separator must be a forward slash.public static String ensureLeadingSeparator(String path, boolean forceForwardSlash)
path - the given path.forceForwardSlash - true if the leading separator must be a forward slash.public static String fixFilename(String fileName, String replacer)
fileName - the given short file namereplacer - the given replacerpublic static String fixPath(String path)
path - the given pathpublic static String fixPath(String path, boolean forceOsSeparators)
path - the given pathforceOsSeparators - true to ensure the path contains only OS-specific separatorspublic static String fixFilename(String fileName)
fileName - the given short file namepublic static String buildPath(String... parts)
parts - parts of the pathpublic static String[] getFilteredFiles(String directory, String suffix)
directory - - directory where files are locatedsuffix - - the sufix used to filter filesURISyntaxException - if the syntax is not correct.public static boolean createDirectories(String path)
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").public static String escapeWhitespaceForXML(String text)
text - - original textpublic static String escapeToXML(String text, int quoteMode, boolean escapeGT, CharsetEncoder encoder)
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.public static String escapeToRTF(String text, boolean convertLineBreaks, int lineBreakStyle, CharsetEncoder encoder)
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.public static boolean deleteDirectory(File directory)
directory - the directory of the content to delete.public static void deleteDirectory(String directory, boolean contentOnly)
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.public static String getFilename(String path, boolean keepExtension)
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.public static String getExtension(String path)
path - the original path or filename.public static String makeURIFromPath(String pathOrUri)
pathOrUri - the path to change to URI string.OkapiUnsupportedEncodingException - if UTF-8 is not supported (can't happen).public static URI toURI(String pathOrUri)
pathOrUri - the path or URI string to use.public static URL toURL(String pathOrUri)
pathOrUri - the path or URI string to use.public static URI URLtoURI(URL url)
URISyntaxException all over the place.url - The URL to convertpublic static URL URItoURL(URI uri)
MalformedURLException.uri - to convertpublic static String longestCommonDir(String currentDir, String newDir, boolean ignoreCase)
currentDir - the current longest common path.newDir - the new directory to compare with.ignoreCase - true if the method should ignore cases differences.public static String longestCommonDir(boolean ignoreCase, String... directories)
ignoreCase - if the method should ignore cases differences.directories - the given list of directories.public static boolean isOSCaseSensitive()
public static void writeBOMIfNeeded(Writer writer, boolean bomOnUTF8, String encoding)
writer - writer where to output the BOM.bomOnUTF8 - indicates if we should use a BOM on UTF-8 files.encoding - encoding of the output.OkapiIOException - if anything went wrong with the writing.public static String getTempDirectory()
public static String getTextContent(Node node)
node - the container element.public static int getPercentage(int part,
int total)
part - the part of the total.total - the total.public static String makeId(String text)
text - the text to make an ID for.public static boolean isSameLanguage(String lang1, String lang2, boolean ignoreRegion)
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.public static boolean isEmpty(String string)
string - the string to check.public static boolean isEmpty(CharSequence sequence)
CharSequence is null or empty.sequence - the sequence to check.public static boolean isNullOrEmpty(LocaleId locale)
locale - the locale id to examine.public static boolean isEmpty(String string, boolean ignoreWS)
string - the string to examine.ignoreWS - true to ignore white spaces.public static boolean isEmpty(StringBuilder sb)
sb - the object to examine.public static <E> boolean isEmpty(List<E> e)
E - the type of the elements in the list.e - the list to examine.public static <E> boolean isEmpty(Set<E> e)
Set is null or empty.E - the type of the elements in the set.e - the set to examine.public static <K,V> boolean isEmpty(Map<K,V> map)
K - the type of the map's keys.V - the type of the map's values.map - the map to examine.public static boolean isEmpty(Object[] e)
e - the array to examine.public static int getLength(String string)
string - the string to examine.public static char getCharAt(String string, int pos)
string - the string to examine.pos - the position of the character to retrieve.public static char getLastChar(String string)
string - the string to examine.public static String deleteLastChar(String string)
string - the string where to remove the character.public static char getLastChar(StringBuilder sb)
sb - the StringBuilder object to examine.public static void deleteLastChar(StringBuilder sb)
sb - the StringBuilder object where to remove the character.public static <E> boolean checkIndex(int index,
List<E> list)
E - the type of the list's elements.index - the given index.list - the given list.public static String intToStr(int value)
String.valueOf(intValue);.value - the value to convert.public static int strToInt(String value, int intDefault)
value - the string to convert.intDefault - the default value to use if the conversion fails.public static int fastParseInt(String s)
s - - string to be converted to intNumberFormatException - if the String does not represent a number.public static long strToLong(String value, long longDefault)
value - the string to convert.longDefault - the default value to use if the conversion fails.public static double strToDouble(String value, double doubleDefault)
value - the string to convert.doubleDefault - the default value to use if the conversion fails.public static <T> T get(T[] array,
int index)
T - the type of the array's elements.array - the array where to lookup the element.index - the index.public static <T> boolean checkIndex(int index,
T[] array)
T - the type of the array's elements.index - the given index.array - the given list.public static boolean checkFlag(int value,
int flag)
value - the value to check.flag - the flag to look for.public static Util.SUPPORTED_OS getOS()
public static void openURL(String url)
This is based on the public domain class BareBonesBrowserLaunch from Dem Pilafian at (www.centerkey.com/java/browser)
url - the URL of the page to open.public static void openWikiTopic(String topic)
topic - the title of the topic/page.public static String getClassLocation(Class<?> theClass)
theClass - the class to query.public static String fillRootDirectoryVariable(String original, String rootDir)
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.public static String fillInputRootDirectoryVariable(String original, String inputRootDir)
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.public static String fillSystemEnvars(String original)
original - The original string in which to perform the replacementpublic static boolean validateVariables(String text, boolean allowEnvar, boolean allowRootDir, boolean allowInputRootDir)
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}public static String expandPath(String path, String rootDir, String inputRootDir) throws IOException
path - The path to expandrootDir - The directory to expand ${rootDir} intoinputRootDir - The directory to expand ${inputRootDir} intoIOException - If canonicalizing failspublic static int min(int... values)
values - the given arraypublic static <K,V> V getValue(Map<K,V> map, K key, V defaultValue)
V - the type of keys maintained by the given mapK - the type of mapped values of the given mapmap - the given mapkey - the key whose associated value is to be returneddefaultValue - the default value to be returned if the key is not foundpublic static int normalizeRange(double low,
double high,
double value)
low - - lowest value of the rangehigh - - highest value of the rangevalue - - the value that needs to be mapped to 0-100public static String formatDouble(Double value)
value - the double value to format (can be null).public static boolean isValidInXML(int ch)
ch - the character to test.public static String URLDecodeUTF8(String s)
URLDecoder.decode(String, String), passing
UTF-8 as the argument and wrapping the exception as an
IllegalStateException. This exists because URLDecoder does not
offer a signature that takes a Charset.s - the String to decodeIllegalStateException - if UTF-8 isn't recognized as a valid
encoding, which should never happen.public static String URLEncodeUTF8(String s)
URLEncoder.encode(String, String), passing
UTF-8 as the argument and wrapping the exception as an
IllegalStateException. This exists because URLEncoder does not
offer a signature that takes a Charset.s - the String to be translatedIllegalStateException - if UTF-8 isn't recognized as a valid
encoding, which should never happen.public static PrintWriter charsetPrintWriter(String filePath, Charset charset) throws FileNotFoundException
PrintWriter, 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.filePath - the file to use as the destination of this writer.charset - charset to use when writing to the fileFileNotFoundException - if the given string does not denote an
existing, writable regular file and a new regular file of that
name can't be created.public static Reader skipBOM(Reader r) throws IOException
r - the reader.IOException - if anything goes wrong when reading.public static <T extends Comparable<T>> Comparator<T> createComparatorHandlingNullKeys(Class<T> clazz)
T - the type of the class.clazz - the class.TreeMap that accepts null keys.public static XPathFactory createXPathFactory()
XPathFactory created.public static <T> T findMatch(T orig,
List<T> things,
boolean[] matches,
Comparator<T>... cmps)
ComparatorT - The type of the thing we are looking fororig - what we are looking forthings - the things we are looking inmatches - boolean arrays marking the matches already foundcmps - the list of ComparatorCopyright © 2022. All rights reserved.