Class GeneralTools
- Author:
- Pete Bankhead
-
Field Summary
Modifier and TypeFieldDescriptionstatic final String
String to represent um (but with the proper 'mu' symbol)static final char
Small Greek mu (useful for micrometers)static final char
Small Greek sigma (useful for Gaussian filter sizes, standard deviations) -
Method Summary
Modifier and TypeMethodDescriptionstatic boolean
almostTheSame
(double n1, double n2, double tolerance) Test if two doubles are approximately equal, within a specified tolerance.static String
arrayToString
(Object[] array, String delimiter) Convert a String array to a single string, with a specified delimiter string.static String
arrayToString
(Locale locale, double[] array, int nDecimalPlaces) Convert a double array to a String using a space as a delimiter.static String
arrayToString
(Locale locale, double[] array, String delimiter, int nDecimalPlaces) Convert a double array to string, with a specified number of decimal places.static boolean
blankString
(String s, boolean trim) Check if a string is blank, i.e.static boolean
checkExtensions
(String path, String... extensions) Check whether a path ends with one of a number of specified extensions (case insensitive).static double
clipValue
(double value, double min, double max) Clip a value to be within a specific range.static int
clipValue
(int value, int min, int max) Clip a value to be within a specific range.static NumberFormat
createFormatter
(int nDecimalPlaces) Create a new DecimalFormat that may be used to convert a number to have a maximum of nDecimalPlaces (trailing zeros are not shown).static boolean
deleteFile
(File fileToDelete, boolean preferTrash) Delete a file, optionally requesting that it be moved to the trash rather than permanently deleted.static String
escapeFilePath
(String path) Escape backslashes in an absolute file path - useful when scripting.static long
Estimate the current available memory in bytes, based upon the JVM max and the memory currently used.static long
Estimate the current used memory.static String
formatNumber
(double value, int maxDecimalPlaces) Format a value with a maximum number of decimal places, using the default Locale.static String
formatNumber
(Locale locale, double value, int maxDecimalPlaces) Format a value with a maximum number of decimal places, using a specified Locale.static String
generateDistinctName
(String base, Collection<String> existingNames) Generate a name that is distinct from the names in an existing collection, while being based on a provided name.getExtension
(File file) Get filename extension.getExtension
(String name) Get extension from a filename.static String
getNameWithoutExtension
(File file) Get the file name with extension removed.static String
Deprecated.static String
getPackageVersion
(Class<?> cls) Try to determine the version of a jar containing a specified class.static Version
Get a representation of QuPath's version, parsed according to the rules of semantic versioning if possible.static String
Get a String representation of QuPath's version, if known.static boolean
isLinux()
Return true if running on Linux.static boolean
isMac()
Return true if running on macOS.static boolean
Returns true for file extensions containing multiple parts (or 'dots').static boolean
isValidFilename
(String name) Returns true if the output ofstripInvalidFilenameChars(String)
matches the provided name, and the name is not null or blank.static boolean
Return true if running on Windows.static final String
Get a string to represent um (but with the proper 'mu' symbol)static int
numNaNs
(double[] vals) Count the number of NaN values in an array.Parse the contents of a JSON String.static String
readFileAsString
(File file) Read the entire contents of a file into a single String.static String
readFileAsString
(String path) Read the entire contents of a file given by the specified path into a single String.static String
readInputStreamAsString
(InputStream stream) Read the entire contents of an InputStream into a single String.static String
readURLAsString
(URL url, int timeoutMillis) Read URL as String, with specified timeout in milliseconds.static String
replaceCurlyQuotes
(String text) Replace different kinds of 'curly quote' in a String with straight quotes.static String
replaceGremlins
(String text, CharSequence replacement) Replace non-printable characters from a String with a specified replacement (may be null).static Comparator
<String> Comparator for smart String sorting.static <T> void
smartStringSort
(Collection<T> collection) Smart-sort a collection using theObject.toString()
method applied to each element.static <T> void
smartStringSort
(Collection<T> collection, Function<T, String> extractor) Smart-sort a collection after extracting a String representation of each element.static String[]
splitLines
(String s) Split new lines (in a cross-platform way...static String
stripExtension
(String path) Strip the extension from a file name or path, leaving the rest of the string unchanged.static String
Strip characters that would make a String invalid as a filename.static long
sum
(long[] values) Compute the sum of elements in a long array (possibly representing a histogram).static URI
toEncodedURI
(String path) Try to convert a path to an encoded URI.static Path
Try to identify a Path from a URI, dropping any query or fragment elements.static URI
Try to convert a path to a URI.static String
zapGremlins
(String text) Remove non-printable characters from a String.
-
Field Details
-
SYMBOL_MU
public static final char SYMBOL_MUSmall Greek mu (useful for micrometers)- See Also:
-
SYMBOL_SIGMA
public static final char SYMBOL_SIGMASmall Greek sigma (useful for Gaussian filter sizes, standard deviations)- See Also:
-
SYMBOL_MICROMETER
String to represent um (but with the proper 'mu' symbol)- See Also:
-
-
Method Details
-
getVersion
Get a String representation of QuPath's version, if known.- Returns:
- a String representation of the version, or null if the version is unknown
- See Also:
-
getSemanticVersion
Get a representation of QuPath's version, parsed according to the rules of semantic versioning if possible.- Returns:
- the current version, or null if the version is unknown or cannot be parsed from
getVersion()
- See Also:
-
getPackageVersion
Try to determine the version of a jar containing a specified class. This first checks the implementation version in the package, then looks for a VERSION file stored as a resource.- Parameters:
cls
- class used to identify the package- Returns:
- the version, if available, or null if no version is known.
-
getExtension
Get filename extension. Some implementation notes:- Note that this is generally 'the final dot and beyond', however this method also handles several important special cases: ".ome.tif", ".ome.tiff" and ".tar.gz".
- The dot is included as the first character.
- No check is performed to see if the file is actually a directory, but if a dot is the final character then no extension is returned.
- The extension is returned as-is, without adjusting to be upper or lower case.
- Parameters:
file
-- Returns:
- see #getNameWithoutExtension(File)
-
getExtension
Get extension from a filename. Some implementation notes:- Note that this is generally 'the final dot and beyond', however this method also handles several important special cases: ".ome.tif", ".ome.tiff" and ".tar.gz".
- The dot is included as the first character.
- No check is performed to see if the file is actually a directory, but if a dot is the final character then no extension is returned.
- The extension is returned as-is, without adjusting to be upper or lower case.
- Parameters:
name
-- Returns:
- See Also:
-
stripInvalidFilenameChars
Strip characters that would make a String invalid as a filename. This test is very simple, and may not catch all problems; the behavior of the method may improve in future versions.Note that the test is not platform-dependent, and may be stricter than absolutely necessary - for example, by removing newline characters. This can result in some filenames that would be valid on the current platform being modified. This can however be necessary to help retain cross-platform portability.
- Parameters:
name
-- Returns:
- the (possibly-shortened) filename without invalid characters
-
isValidFilename
Returns true if the output ofstripInvalidFilenameChars(String)
matches the provided name, and the name is not null or blank.- Parameters:
name
-- Returns:
- true if the name is expected to be valid, false otherwise
- See Also:
-
getNameWithoutExtension
Get the file name with extension removed. Note that this generally means removing the text including and after the final dot, but also handles specific multi-part file extensions as well.- Parameters:
file
-- Returns:
- See Also:
-
getNameWithoutExtension
Deprecated.v0.5.0 in favor ofstripExtension(String)
, which does the same thing but has a more descriptive name. See https://github.com/qupath/qupath/pull/1275 for details.Strip the extension from a file name or path, leaving the rest of the string unchanged.- Parameters:
name
-- Returns:
getExtension(File)
-
stripExtension
Strip the extension from a file name or path, leaving the rest of the string unchanged. Note that this generally means removing the text including and after the final dot, but also handles specific multi-part file extensions as well.- Parameters:
path
-- Returns:
- See Also:
-
isMultipartExtension
Returns true for file extensions containing multiple parts (or 'dots'). Examples include ome.tif and tar.gz, which can be problematic with some file choosers.- Parameters:
ext
-- Returns:
-
blankString
Check if a string is blank, i.e. it is null or its length is 0.- Parameters:
s
-trim
- If true, any string will be trimmed before its length checked.- Returns:
- True if the string is null or empty.
-
escapeFilePath
Escape backslashes in an absolute file path - useful when scripting.- Parameters:
path
-- Returns:
-
clipValue
public static int clipValue(int value, int min, int max) Clip a value to be within a specific range.- Parameters:
value
-min
-max
-- Returns:
-
clipValue
public static double clipValue(double value, double min, double max) Clip a value to be within a specific range.- Parameters:
value
-min
-max
-- Returns:
-
almostTheSame
public static boolean almostTheSame(double n1, double n2, double tolerance) Test if two doubles are approximately equal, within a specified tolerance.Relies on apache.common's method as the history of this method proved this task not as straightforward as initially thought.
Note that this calculation changed in v0.2.0-m4 and in v0.3.0. The behavior prior to v0.2.0-m4 divided the absolute difference by the first value only, which is not robust to differences in the input order or if the first value is negative. The behavior before v0.3.0 returned whether the absolute difference divided by the average is less than the specified tolerance.
- Parameters:
n1
-n2
-tolerance
-- Returns:
-
toURI
Try to convert a path to a URI.This currently does a very simple check for a known scheme at the beginning ("http:", "https:" or ""file:") to see if it can construct the URI directly; if not, it assumes the path refers to a local file (as it generally did in QuPath 0.1.2 and earlier). This method does not encode special characters.
- Parameters:
path
-- Returns:
- Throws:
URISyntaxException
- See Also:
-
toEncodedURI
public static URI toEncodedURI(String path) throws URISyntaxException, UnsupportedEncodingException, MalformedURLException Try to convert a path to an encoded URI.URIs do not accept some characters (e.g. "|"). This method will perform a simple check for
http:
andhttps:
schemes at the beginning of the URI. It will then modify the Query (@see Query) to a valid form. Finally, a reconstructed valid URI is returned. Note: this method will only encode the Query part of the URI (i.e. Fragments, if present, will be ignored ).E.g. "
https://host?query=first|second
" will return "https://host?query%3Dfirst%7Csecond
".- Parameters:
path
-- Returns:
- encodedURI
- Throws:
URISyntaxException
UnsupportedEncodingException
MalformedURLException
-
toPath
Try to identify a Path from a URI, dropping any query or fragment elements.This returns the Path if successful and null otherwise (e.g. if the URI does not correspond to a file). There is no check whether the Path exists, and support for an authority is platform-dependent.
- Parameters:
uri
-- Returns:
-
arrayToString
public static String arrayToString(Locale locale, double[] array, String delimiter, int nDecimalPlaces) Convert a double array to string, with a specified number of decimal places. Trailing zeros are not included.- Parameters:
locale
-array
-delimiter
-nDecimalPlaces
-- Returns:
-
arrayToString
Convert a double array to a String using a space as a delimiter.- Parameters:
locale
-array
-nDecimalPlaces
-- Returns:
-
arrayToString
Convert a String array to a single string, with a specified delimiter string.- Parameters:
array
-delimiter
-- Returns:
-
splitLines
Split new lines (in a cross-platform way... i.e. not with s.split("\n"), which is asking for trouble).- Parameters:
s
-- Returns:
-
createFormatter
Create a new DecimalFormat that may be used to convert a number to have a maximum of nDecimalPlaces (trailing zeros are not shown). Important note: this always formats as 1.234 rather than 1,234 - regardless of Locale. Consequently its results are more predictable... but may not be consistent with other number formatting on the specified platform.- Parameters:
nDecimalPlaces
-- Returns:
-
formatNumber
Format a value with a maximum number of decimal places, using the default Locale.- Parameters:
value
-maxDecimalPlaces
-- Returns:
-
formatNumber
Format a value with a maximum number of decimal places, using a specified Locale.- Parameters:
locale
-value
-maxDecimalPlaces
-- Returns:
-
parseArgStringValues
Parse the contents of a JSON String.Note that this is pretty unsophisticated... also, no localization is performed (using Java's Locales, for example) - so that decimal values should be provided in the form 1.234 (and not e.g. 1,234).
- Parameters:
s
-- Returns:
-
micrometerSymbol
Get a string to represent um (but with the proper 'mu' symbol)- Returns:
-
readFileAsString
Read the entire contents of a file given by the specified path into a single String.Note that from QuPath v0.3 this assumes UTF8 encoding. Previously, platform-specific encoding was assumed.
- Parameters:
path
-- Returns:
- Throws:
IOException
-
readFileAsString
Read the entire contents of a file into a single String.Note that from QuPath v0.3 this assumes UTF8 encoding. Previously, platform-specific encoding was assumed.
- Parameters:
file
-- Returns:
- Throws:
IOException
-
readInputStreamAsString
Read the entire contents of an InputStream into a single String.Note that from QuPath v0.3 this assumes UTF8 encoding. Previously, platform-specific encoding was assumed.
- Parameters:
stream
-- Returns:
- Throws:
IOException
-
checkExtensions
Check whether a path ends with one of a number of specified extensions (case insensitive).- Parameters:
path
-extensions
-- Returns:
-
isMac
public static boolean isMac()Return true if running on macOS.- Returns:
-
isLinux
public static boolean isLinux()Return true if running on Linux.- Returns:
-
isWindows
public static boolean isWindows()Return true if running on Windows.- Returns:
-
deleteFile
Delete a file, optionally requesting that it be moved to the trash rather than permanently deleted.Note that the behavior of this method is system-dependent, and there is no guarantee the file will indeed be moved to the trash.
- Parameters:
fileToDelete
-preferTrash
-- Returns:
- true if the file is successfully deleted, false otherwise
-
readURLAsString
Read URL as String, with specified timeout in milliseconds.The content type is checked, and an IOException is thrown if this doesn't start with text/plain.
- Parameters:
url
-timeoutMillis
-- Returns:
- Throws:
IOException
-
numNaNs
public static int numNaNs(double[] vals) Count the number of NaN values in an array.- Parameters:
vals
-- Returns:
-
sum
public static long sum(long[] values) Compute the sum of elements in a long array (possibly representing a histogram).- Parameters:
values
-- Returns:
-
generateDistinctName
Generate a name that is distinct from the names in an existing collection, while being based on a provided name.This is useful, for example, when duplicating named items and requiring that the duplicates can be distinguished. The precise way in which the name is derived is implementation-dependent, with the only requirement that it be recognizably derived from the base name.
Currently, names are generated in the form
"base (i)"
wherei
is an integer.Note that if the base already has the same form, any existing integer will be stripped away; for example providing
"name (1)"
as the base will yield the output"name (2)"
, (assuming this name does not already exist), rather than"name (1) (1)"
.- Parameters:
base
- the (non-empty) base from which the name should be derivedexistingNames
- a collection of names that are already in use, and therefore must be avoided- Returns:
- the distinct name
-
estimateAvailableMemory
public static long estimateAvailableMemory()Estimate the current available memory in bytes, based upon the JVM max and the memory currently used.This may be used to help determine whether a memory-hungry operation should be attempted.
- Returns:
- the estimated unused memory in bytes
-
estimateUsedMemory
public static long estimateUsedMemory()Estimate the current used memory.- Returns:
- the estimated allocated memory in bytes
-
smartStringSort
Smart-sort a collection using theObject.toString()
method applied to each element. SeesmartStringSort(Collection, Function)
for more details.- Type Parameters:
T
-- Parameters:
collection
- collection to be sorted (results are retained in-place)- See Also:
-
smartStringSort
Smart-sort a collection after extracting a String representation of each element. This differs from a 'normal' sort by splitting the String into lists of numeric and non-numeric parts, and comparing corresponding elements separately. This can sometimes give more intuitive results than a simple String sort, which would treat "10" as 'less than' "2".For example, applying a simple sort to the list
["a1", "a2", "a10"]
will result in["a1", "a10", "a2]
. Smart-sorting would leave the list unchanged.Note: Currently this method considers only positive integer values, treating characters such as '+', '-', ',', '.' and 'e' as distinct elements of text.
- Type Parameters:
T
-- Parameters:
collection
- collection to be sorted (results are retained in-place)extractor
- function used to convert each element of the collection to a String representation
-
smartStringComparator
Comparator for smart String sorting. Note: This comparator is very inefficient. Where possiblesmartStringSort(Collection, Function)
should be used instead.- Returns:
- a String comparator that parses integers from within the String so they may be compared by value
-
zapGremlins
Remove non-printable characters from a String.- Parameters:
text
-- Returns:
- the modified String, or the original if no changes were made
-
replaceGremlins
Replace non-printable characters from a String with a specified replacement (may be null).- Parameters:
text
- the input textreplacement
- the replacement text (often an empty string or null)- Returns:
- the modified String, or the original if no changes were made
-
replaceCurlyQuotes
Replace different kinds of 'curly quote' in a String with straight quotes. This is particularly useful when working with a script editor.- Parameters:
text
-- Returns:
- the modified String, or the original if no changes were made
-
stripExtension(String)
, which does the same thing but has a more descriptive name.