Class Utils
- java.lang.Object
-
- org.openstreetmap.josm.tools.Utils
-
public final class Utils extends java.lang.Object
Basic utils, that can be useful in different parts of the program.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description private static class
Utils.DirectionString
Utility class to save a string along with its rendering direction (left-to-right or right-to-left).(package private) static class
Utils.JosmForkJoinWorkerThread
A ForkJoinWorkerThread that will always inherit caller permissions, unlike JDK's InnocuousForkJoinWorkerThread, used if a security manager exists.
-
Field Summary
Fields Modifier and Type Field Description private static java.lang.String
DEFAULT_STRIP
private static int[][]
EMPTY_INT_INT_ARRAY
private static double
EPSILON
private static char[]
HEX_ARRAY
private static long
MILLIS_OF_DAY
private static long
MILLIS_OF_HOUR
private static long
MILLIS_OF_MINUTE
private static long
MILLIS_OF_SECOND
private static java.util.regex.Pattern
PATTERN_LENGTH
private static java.util.regex.Pattern
PATTERN_LENGTH2
private static java.util.regex.Pattern
REMOVE_DIACRITICS
private static java.lang.String[]
SIZE_UNITS
private static double
TO_DEGREES
private static double
TO_RADIANS
static java.lang.String
URL_CHARS
A list of all characters allowed in URLsstatic java.util.regex.Pattern
WHITE_SPACES_PATTERN
Pattern matching white spaces
-
Constructor Summary
Constructors Modifier Constructor Description private
Utils()
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static <T> T[]
addInArrayCopy(T[] array, T item)
Adds the given item at the end of a new copy of given array.static java.net.URL
betterJarUrl(java.net.URL jarUrl)
Tries to build a better JAR URL if we find it concerned by a JDK bug.static java.net.URL
betterJarUrl(java.net.URL jarUrl, java.net.URL defaultUrl)
Tries to build a better JAR URL if we find it concerned by a JDK bug.static <T> T
cast(java.lang.Object o, java.lang.Class<T> klass)
Cast an object safely.static <T,U>
java.util.function.Function<T,java.util.stream.Stream<U>>castToStream(java.lang.Class<U> klass)
Get a function that converts an object to a singleton stream of a certain class (or null if the object cannot be cast to that class).static double
clamp(double val, double min, double max)
Clamp a value to the given rangestatic int
clamp(int val, int min, int max)
Clamp a integer value to the given rangestatic void
close(java.io.Closeable c)
Utility method for closing aCloseable
object.static void
close(java.util.zip.ZipFile zip)
Utility method for closing aZipFile
.static byte[]
copyArray(byte... array)
Copies the given array.static char[]
copyArray(char... array)
Copies the given array.static int[]
copyArray(int... array)
Copies the given array.static <T> T[]
copyArray(T[] array)
Copies the given array.static void
copyDirectory(java.io.File in, java.io.File out)
Recursive directory copy functionstatic java.nio.file.Path
copyFile(java.io.File in, java.io.File out)
Simple file copy function that will overwrite the target file.static java.lang.String
deAccent(java.lang.String str)
Removes diacritics (accents) from string.static java.lang.String
decodeUrl(java.lang.String s)
Decodes aapplication/x-www-form-urlencoded
string.static boolean
deleteDirectory(java.io.File path)
Deletes a directory recursively.static boolean
deleteFile(java.io.File file)
Deletes a file and log a default warning if the deletion fails.static boolean
deleteFile(java.io.File file, java.lang.String warnMsg)
Deletes a file and log a configurable warning if the deletion fails.static boolean
deleteFileIfExists(java.io.File file)
Deletes a file and log a default warning if the file exists but the deletion fails.static java.lang.String
encodeUrl(java.lang.String s)
Translates a string intoapplication/x-www-form-urlencoded
format.static void
ensure(boolean condition, java.lang.String message, java.lang.Object... data)
Ensures a logical condition is met.static boolean
equalsEpsilon(double a, double b)
Determines if the two given double values are equal (their delta being smaller than a fixed epsilon)static java.lang.String
escapeReservedCharactersHTML(java.lang.String s)
Replaces some HTML reserved characters (<, > and &) by their equivalent entity (<, > and &);static java.lang.String
execOutput(java.util.List<java.lang.String> command)
Runs an external command and returns the standard output.static java.lang.String
execOutput(java.util.List<java.lang.String> command, long timeout, java.util.concurrent.TimeUnit unit)
Runs an external command and returns the standard output.static java.net.URL
fileToURL(java.io.File f)
Converts the given file to its URL.static <S,T extends S>
SubclassFilteredCollection<S,T>filteredCollection(java.util.Collection<S> collection, java.lang.Class<T> clazz)
Filter a collection by (sub)class.static <T> T
firstNonNull(T... items)
Returns the first element fromitems
which is non-null, or null if all elements are null.static java.lang.String
firstNotEmptyString(java.lang.String defaultString, java.lang.String... candidates)
Returns the first not empty string in the given candidates, otherwise the default string.static java.lang.String
fixURLQuery(java.lang.String url)
Fixes URL with illegal characters in the query (and fragment) part by percent encoding those characters.static java.lang.String
getDurationString(long elapsedTime)
Returns a simple human readable (hours, minutes, seconds) string for a given duration in milliseconds.static java.util.List<java.awt.font.GlyphVector>
getGlyphVectorsBidi(java.lang.String string, java.awt.Font font, java.awt.font.FontRenderContext frc)
Convert a string to a list ofGlyphVector
s.static int
getJavaBuild()
Returns the Java build number as an int value.static java.util.Date
getJavaExpirationDate()
Returns the JRE expiration date.static java.lang.String
getJavaLatestVersion()
Returns the latest version of Java, from Oracle website.static int
getJavaUpdate()
Returns the Java update as an int value.static int
getJavaVersion()
Returns the Java version as an int value.static java.io.File
getJosmTempDir()
Returns the JOSM temp directory.static int
getLevenshteinDistance(java.lang.String s, java.lang.String t)
Compute Levenshtein distancestatic java.util.List<java.lang.String>
getMatches(java.util.regex.Matcher m)
Returns a list of capture groups ifMatcher.matches()
, ornull
.static java.lang.String
getPositionListString(java.util.List<java.lang.Integer> positionList)
Returns a human readable representation of a list of positions.static java.io.InputStream
getResourceAsStream(java.lang.Class<?> klass, java.lang.String path)
Finds a resource with a given name, with robustness to known JDK bugs.static java.io.InputStream
getResourceAsStream(java.lang.ClassLoader cl, java.lang.String path)
Finds a resource with a given name, with robustness to known JDK bugs.static java.lang.Throwable
getRootCause(java.lang.Throwable t)
Returns the root cause of a throwable object.static java.lang.String
getSizeString(long bytes, java.util.Locale locale)
Returns a human readable representation (B, kB, MB, ...) for the given number of byes.static double
getStandardDeviation(double[] values)
Calculates the standard deviation of population.static double
getStandardDeviation(double[] values, double mean)
Calculates the standard deviation of population with the given mean value.static java.lang.String
getSystemEnv(java.lang.String name)
Gets the value of the specified environment variable.static java.lang.String
getSystemProperty(java.lang.String key)
Gets the system property indicated by the specified key.static int[][]
groupIntegers(int... integers)
Group a list of integers, mostly useful to avoid calling many selection change events for a logical interval.static boolean
hasExtension(java.io.File file, java.lang.String... extensions)
Determines if the file's name has one of the given extensions, in a robust manner.static boolean
hasExtension(java.lang.String filename, java.lang.String... extensions)
Determines if the filename has one of the given extensions, in a robust manner.static int
hashMapInitialCapacity(int nEntries)
Returns the initial capacity to pass to the HashMap / HashSet constructor when it is initialized with a known number of entries.static int
hashMapInitialCapacity(int nEntries, double loadFactor)
Returns the initial capacity to pass to the HashMap / HashSet constructor when it is initialized with a known number of entries.static <T> int
indexOf(java.lang.Iterable<? extends T> collection, java.util.function.Predicate<? super T> predicate)
Find the index of the first item that matches the predicate.static <T> java.util.Optional<T>
instanceOfAndCast(java.lang.Object o, java.lang.Class<T> klass)
Helper method to replace the "instanceof
-check and cast" pattern.static <T> void
instanceOfThen(java.lang.Object o, java.lang.Class<T> klass, java.util.function.Consumer<? super T> consumer)
Helper method to replace the "instanceof
-check and cast" pattern.static java.lang.String
intern(java.lang.String string)
Intern a stringstatic boolean
isClassFound(java.lang.String className)
Determines if a class can be found for the given name.static boolean
isEmpty(java.lang.String string)
Determines if a string is null or empty.static boolean
isEmpty(java.util.Collection<?> collection)
Determines if a collection is null or empty.static boolean
isEmpty(java.util.Map<?,?> map)
Determines if a map is null or empty.static boolean
isEmpty(MultiMap<?,?> map)
Determines if a multimap is null or empty.static boolean
isLocalUrl(java.lang.String url)
Determines if the given URL denotes a file on a local filesystem.static boolean
isRunningOpenWebStart()
Determines whether JOSM has been started via Open Web Start (IcedTea-Web).static boolean
isRunningWebStart()
Determines whether JOSM has been started via Web Start (JNLP).static boolean
isSimilar(java.lang.String string1, java.lang.String string2)
Check if two strings are similar, but not identical, i.e., have a Levenshtein distance of 1 or 2.static boolean
isStripEmpty(java.lang.String str)
Determines if the given String would be empty if stripped.private static boolean
isStrippedChar(char c, java.lang.String skipChars)
static boolean
isValidUrl(java.lang.String url)
Determines if the given URL is valid.static java.lang.String
joinAsHtmlUnorderedList(java.lang.Iterable<?> values)
Converts the given iterable collection as an unordered HTML list.static <T> java.util.Collection<T>
limit(java.util.Collection<T> elements, int maxElements, T overflowIndicator)
If the collectionelements
is larger thanmaxElements
elements, the collection is shortened and theoverflowIndicator
is appended.static java.lang.String
md5Hex(java.lang.String data)
Calculate MD5 hash of a string and output in hexadecimal format.static boolean
mkDirs(java.io.File dir)
Creates a directory and log a default warning if the creation fails.static boolean
mkDirs(java.io.File dir, java.lang.String warnMsg)
Creates a directory and log a configurable warning if the creation fails.static int
mod(int a, int n)
Returns the modulo in the range [0, n) for the given dividend and divisor.static java.util.concurrent.Executor
newDirectExecutor()
Returns an executor which executes commands in the calling threadstatic java.util.concurrent.ForkJoinPool
newForkJoinPool(java.lang.String pref, java.lang.String nameFormat, int threadPriority)
Returns aForkJoinPool
with the parallelism given by the preference key.static java.util.concurrent.ThreadFactory
newThreadFactory(java.lang.String nameFormat, int threadPriority)
Creates a newThreadFactory
which creates threads with names according tonameFormat
.static java.io.InputStream
openStream(java.net.URL url)
Convenient method to open an URL stream, using JOSM HTTP client if needed.static java.lang.String
removeWhiteSpaces(java.lang.String s)
Removes leading, trailing, and multiple inner whitespaces from the given string, to be used as a key or value.static java.lang.String
removeWhiteSpaces(java.util.regex.Pattern whitespaces, java.lang.String s)
Removes leading, trailing, and multiple inner whitespaces from the given string, to be used as a key or value.static java.lang.String
restrictStringLines(java.lang.String s, int maxLines)
If the strings
is longer thanmaxLines
lines, the string is cut and a "..." line is appended.static java.lang.String
shortenString(java.lang.String s, int maxLength)
If the strings
is longer thanmaxLength
, the string is cut and "..." is appended.static java.lang.String
strip(java.lang.String str)
An alternative toString.trim()
to effectively remove all leading and trailing white characters, including Unicode ones.static java.lang.String
strip(java.lang.String str, java.lang.String skipChars)
An alternative toString.trim()
to effectively remove all leading and trailing white characters, including Unicode ones.static java.lang.String
stripHtml(java.lang.String rawString)
Strips all HTML characters and return the result.static double
toDegrees(double angleRad)
Convert angle from radians to degrees.static java.lang.String
toHexString(byte[] bytes)
Converts a byte array to a string of hexadecimal characters.static <T> java.util.List<T>
topologicalSort(MultiMap<T,T> dependencies)
Topological sort.static double
toRadians(double angleDeg)
Convert angle from degrees to radians.static <T> java.util.List<T>
toUnmodifiableList(java.util.Collection<T> collection)
Returns an unmodifiable list for the given collection.static <K,V>
java.util.Map<K,V>toUnmodifiableMap(java.util.Map<K,V> map)
Returns an unmodifiable map for the given map.static <A,B>
java.util.Collection<B>transform(java.util.Collection<? extends A> c, java.util.function.Function<A,B> f)
Transforms the collectionc
into an unmodifiable collection and applies theFunction
f
on each element upon access.static <A,B>
java.util.List<B>transform(java.util.List<? extends A> l, java.util.function.Function<A,B> f)
Transforms the listl
into an unmodifiable list and applies theFunction
f
on each element upon access.static java.lang.Double
unitToMeter(java.lang.String s)
Convert a length unit to metersprivate static double
unitToMeterConversion(java.lang.String unit)
Get the conversion factor for a specified unit to metersstatic java.lang.String
updateSystemProperty(java.lang.String key, java.lang.String value)
Updates a given system property.static java.net.URI
urlToURI(java.lang.String url)
Converts the given URL to its URI.static java.net.URI
urlToURI(java.net.URL url)
Converts the given URL to its URI.
-
-
-
Field Detail
-
WHITE_SPACES_PATTERN
public static final java.util.regex.Pattern WHITE_SPACES_PATTERN
Pattern matching white spaces
-
MILLIS_OF_SECOND
private static final long MILLIS_OF_SECOND
-
MILLIS_OF_MINUTE
private static final long MILLIS_OF_MINUTE
-
MILLIS_OF_HOUR
private static final long MILLIS_OF_HOUR
-
MILLIS_OF_DAY
private static final long MILLIS_OF_DAY
-
EMPTY_INT_INT_ARRAY
private static final int[][] EMPTY_INT_INT_ARRAY
-
URL_CHARS
public static final java.lang.String URL_CHARS
A list of all characters allowed in URLs- See Also:
- Constant Field Values
-
REMOVE_DIACRITICS
private static final java.util.regex.Pattern REMOVE_DIACRITICS
-
PATTERN_LENGTH
private static final java.util.regex.Pattern PATTERN_LENGTH
-
PATTERN_LENGTH2
private static final java.util.regex.Pattern PATTERN_LENGTH2
-
DEFAULT_STRIP
private static final java.lang.String DEFAULT_STRIP
- See Also:
- Constant Field Values
-
SIZE_UNITS
private static final java.lang.String[] SIZE_UNITS
-
TO_DEGREES
private static final double TO_DEGREES
- See Also:
- Constant Field Values
-
TO_RADIANS
private static final double TO_RADIANS
- See Also:
- Constant Field Values
-
EPSILON
private static final double EPSILON
- See Also:
- Constant Field Values
-
HEX_ARRAY
private static final char[] HEX_ARRAY
-
-
Constructor Detail
-
Utils
private Utils()
-
-
Method Detail
-
firstNonNull
@SafeVarargs public static <T> T firstNonNull(T... items)
Returns the first element fromitems
which is non-null, or null if all elements are null.- Type Parameters:
T
- type of items- Parameters:
items
- the items to look for- Returns:
- first non-null item if there is one
-
filteredCollection
public static <S,T extends S> SubclassFilteredCollection<S,T> filteredCollection(java.util.Collection<S> collection, java.lang.Class<T> clazz)
Filter a collection by (sub)class. This is an efficient read-only implementation.- Type Parameters:
S
- Super type of itemsT
- type of items- Parameters:
collection
- the collectionclazz
- the (sub)class- Returns:
- a read-only filtered collection
-
indexOf
public static <T> int indexOf(java.lang.Iterable<? extends T> collection, java.util.function.Predicate<? super T> predicate)
Find the index of the first item that matches the predicate.- Type Parameters:
T
- The iterable type- Parameters:
collection
- The iterable to iterate over.predicate
- The predicate to search for.- Returns:
- The index of the first item or -1 if none was found.
-
ensure
public static void ensure(boolean condition, java.lang.String message, java.lang.Object... data)
Ensures a logical condition is met. Otherwise throws an assertion error.- Parameters:
condition
- the condition to be metmessage
- Formatted error message to raise if condition is not metdata
- Message parameters, optional- Throws:
java.lang.AssertionError
- if the condition is not met
-
mod
public static int mod(int a, int n)
Returns the modulo in the range [0, n) for the given dividend and divisor.- Parameters:
a
- the dividendn
- the divisor- Returns:
- the modulo, which is the remainder of the Euclidean division of a by n, in the range [0, n)
- Throws:
java.lang.IllegalArgumentException
- if n is less than or equal to 0
-
joinAsHtmlUnorderedList
public static java.lang.String joinAsHtmlUnorderedList(java.lang.Iterable<?> values)
Converts the given iterable collection as an unordered HTML list.- Parameters:
values
- The iterable collection- Returns:
- An unordered HTML list
-
copyArray
public static <T> T[] copyArray(T[] array)
Copies the given array. UnlikeArrays.copyOf(T[], int)
, this method is null-safe.- Type Parameters:
T
- type of items- Parameters:
array
- The array to copy- Returns:
- A copy of the original array, or
null
ifarray
is null - Since:
- 6221
-
copyArray
public static char[] copyArray(char... array)
Copies the given array. UnlikeArrays.copyOf(T[], int)
, this method is null-safe.- Parameters:
array
- The array to copy- Returns:
- A copy of the original array, or
null
ifarray
is null - Since:
- 6222
-
copyArray
public static int[] copyArray(int... array)
Copies the given array. UnlikeArrays.copyOf(T[], int)
, this method is null-safe.- Parameters:
array
- The array to copy- Returns:
- A copy of the original array, or
null
ifarray
is null - Since:
- 7436
-
copyArray
public static byte[] copyArray(byte... array)
Copies the given array. UnlikeArrays.copyOf(T[], int)
, this method is null-safe.- Parameters:
array
- The array to copy- Returns:
- A copy of the original array, or
null
ifarray
is null - Since:
- 11879
-
copyFile
public static java.nio.file.Path copyFile(java.io.File in, java.io.File out) throws java.io.IOException
Simple file copy function that will overwrite the target file.- Parameters:
in
- The source fileout
- The destination file- Returns:
- the path to the target file
- Throws:
java.io.IOException
- if any I/O error occursjava.lang.IllegalArgumentException
- ifin
orout
isnull
java.nio.file.InvalidPathException
- if a Path object cannot be constructed from the abstract path- Since:
- 7003
-
copyDirectory
public static void copyDirectory(java.io.File in, java.io.File out) throws java.io.IOException
Recursive directory copy function- Parameters:
in
- The source directoryout
- The destination directory- Throws:
java.io.IOException
- if any I/O error occursjava.lang.IllegalArgumentException
- ifin
orout
isnull
- Since:
- 7835
-
deleteDirectory
public static boolean deleteDirectory(java.io.File path)
Deletes a directory recursively.- Parameters:
path
- The directory to delete- Returns:
true
if and only if the file or directory is successfully deleted;false
otherwise
-
deleteFileIfExists
public static boolean deleteFileIfExists(java.io.File file)
Deletes a file and log a default warning if the file exists but the deletion fails.- Parameters:
file
- file to delete- Returns:
true
if and only if the file does not exist or is successfully deleted;false
otherwise- Since:
- 10569
-
deleteFile
public static boolean deleteFile(java.io.File file)
Deletes a file and log a default warning if the deletion fails.- Parameters:
file
- file to delete- Returns:
true
if and only if the file is successfully deleted;false
otherwise- Since:
- 9296
-
deleteFile
public static boolean deleteFile(java.io.File file, java.lang.String warnMsg)
Deletes a file and log a configurable warning if the deletion fails.- Parameters:
file
- file to deletewarnMsg
- warning message. It will be translated withtr()
and must contain a single parameter{0}
for the file path- Returns:
true
if and only if the file is successfully deleted;false
otherwise- Since:
- 9296
-
mkDirs
public static boolean mkDirs(java.io.File dir)
Creates a directory and log a default warning if the creation fails.- Parameters:
dir
- directory to create- Returns:
true
if and only if the directory is successfully created;false
otherwise- Since:
- 9645
-
mkDirs
public static boolean mkDirs(java.io.File dir, java.lang.String warnMsg)
Creates a directory and log a configurable warning if the creation fails.- Parameters:
dir
- directory to createwarnMsg
- warning message. It will be translated withtr()
and must contain a single parameter{0}
for the directory path- Returns:
true
if and only if the directory is successfully created;false
otherwise- Since:
- 9645
-
close
public static void close(java.io.Closeable c)
Utility method for closing a
Closeable
object.- Parameters:
c
- the closeable object. May be null.
-
close
public static void close(java.util.zip.ZipFile zip)
Utility method for closing a
ZipFile
.- Parameters:
zip
- the zip file. May be null.
-
fileToURL
public static java.net.URL fileToURL(java.io.File f)
Converts the given file to its URL.- Parameters:
f
- The file to get URL from- Returns:
- The URL of the given file, or
null
if not possible. - Since:
- 6615
-
urlToURI
public static java.net.URI urlToURI(java.lang.String url) throws java.net.URISyntaxException, java.net.MalformedURLException
Converts the given URL to its URI.- Parameters:
url
- the URL to get URI from- Returns:
- the URI of given URL
- Throws:
java.net.URISyntaxException
- if the URL cannot be converted to an URIjava.net.MalformedURLException
- if no protocol is specified, or an unknown protocol is found, orspec
isnull
.- Since:
- 15543
-
urlToURI
public static java.net.URI urlToURI(java.net.URL url) throws java.net.URISyntaxException
Converts the given URL to its URI.- Parameters:
url
- the URL to get URI from- Returns:
- the URI of given URL
- Throws:
java.net.URISyntaxException
- if the URL cannot be converted to an URI- Since:
- 15543
-
equalsEpsilon
public static boolean equalsEpsilon(double a, double b)
Determines if the two given double values are equal (their delta being smaller than a fixed epsilon)- Parameters:
a
- The first double value to compareb
- The second double value to compare- Returns:
true
ifabs(a - b) <= 1e-11
,false
otherwise
-
md5Hex
public static java.lang.String md5Hex(java.lang.String data)
Calculate MD5 hash of a string and output in hexadecimal format.- Parameters:
data
- arbitrary String- Returns:
- MD5 hash of data, string of length 32 with characters in range [0-9a-f]
-
toHexString
public static java.lang.String toHexString(byte[] bytes)
Converts a byte array to a string of hexadecimal characters. Preserves leading zeros, so the size of the output string is always twice the number of input bytes.- Parameters:
bytes
- the byte array- Returns:
- hexadecimal representation
-
topologicalSort
public static <T> java.util.List<T> topologicalSort(MultiMap<T,T> dependencies)
Topological sort.- Type Parameters:
T
- type of items- Parameters:
dependencies
- contains mappings (key → value). In the final list of sorted objects, the key will come after the value. (In other words, the key depends on the value(s).) There must not be cyclic dependencies.- Returns:
- the list of sorted objects
-
escapeReservedCharactersHTML
public static java.lang.String escapeReservedCharactersHTML(java.lang.String s)
Replaces some HTML reserved characters (<, > and &) by their equivalent entity (<, > and &);- Parameters:
s
- The unescaped string- Returns:
- The escaped string
-
transform
public static <A,B> java.util.Collection<B> transform(java.util.Collection<? extends A> c, java.util.function.Function<A,B> f)
Transforms the collectionc
into an unmodifiable collection and applies theFunction
f
on each element upon access.- Type Parameters:
A
- class of input collectionB
- class of transformed collection- Parameters:
c
- a collectionf
- a function that transforms objects ofA
to objects ofB
- Returns:
- the transformed unmodifiable collection
-
transform
public static <A,B> java.util.List<B> transform(java.util.List<? extends A> l, java.util.function.Function<A,B> f)
Transforms the listl
into an unmodifiable list and applies theFunction
f
on each element upon access.- Type Parameters:
A
- class of input collectionB
- class of transformed collection- Parameters:
l
- a collectionf
- a function that transforms objects ofA
to objects ofB
- Returns:
- the transformed unmodifiable list
-
toUnmodifiableList
public static <T> java.util.List<T> toUnmodifiableList(java.util.Collection<T> collection)
Returns an unmodifiable list for the given collection. Makes use ofCollections.emptySet()
andCollections.singleton(T)
andArrays.asList(T...)
to save memory.- Type Parameters:
T
- the class of the objects in the array- Parameters:
collection
- the collection for which an unmodifiable collection is to be returned- Returns:
- an unmodifiable list
- See Also:
- How to Prevent Your Java Collections From Wasting Memory
-
toUnmodifiableMap
public static <K,V> java.util.Map<K,V> toUnmodifiableMap(java.util.Map<K,V> map)
Returns an unmodifiable map for the given map. Makes use ofCollections.emptyMap()
andCollections.singletonMap(K, V)
andMap#ofEntries
to save memory.- Type Parameters:
K
- the type of keys maintained by this mapV
- the type of mapped values- Parameters:
map
- the map for which an unmodifiable map is to be returned- Returns:
- an unmodifiable map
- See Also:
- How to Prevent Your Java Collections From Wasting Memory
-
isEmpty
public static boolean isEmpty(java.util.Collection<?> collection)
Determines if a collection is null or empty.- Parameters:
collection
- collection- Returns:
true
if collection is null or empty- Since:
- 18207
-
isEmpty
public static boolean isEmpty(java.util.Map<?,?> map)
Determines if a map is null or empty.- Parameters:
map
- map- Returns:
true
if map is null or empty- Since:
- 18207
-
isEmpty
public static boolean isEmpty(MultiMap<?,?> map)
Determines if a multimap is null or empty.- Parameters:
map
- map- Returns:
true
if map is null or empty- Since:
- 18208
-
isEmpty
public static boolean isEmpty(java.lang.String string)
Determines if a string is null or empty.- Parameters:
string
- string- Returns:
true
if string is null or empty- Since:
- 18207
-
firstNotEmptyString
public static java.lang.String firstNotEmptyString(java.lang.String defaultString, java.lang.String... candidates)
Returns the first not empty string in the given candidates, otherwise the default string.- Parameters:
defaultString
- default string returned if all candidates would be empty if strippedcandidates
- string candidates to consider- Returns:
- the first not empty string in the given candidates, otherwise the default string
- Since:
- 15646
-
isStripEmpty
public static boolean isStripEmpty(java.lang.String str)
Determines if the given String would be empty if stripped. This is an efficient alternative tostrip(s).isEmpty()
that avoids to create useless String object.- Parameters:
str
- The string to test- Returns:
true
if the stripped version ofs
would be empty.- Since:
- 11435
-
strip
public static java.lang.String strip(java.lang.String str)
An alternative toString.trim()
to effectively remove all leading and trailing white characters, including Unicode ones.- Parameters:
str
- The string to strip- Returns:
str
, without leading and trailing characters, according toCharacter.isWhitespace(char)
andCharacter.isSpaceChar(char)
.- Since:
- 5772
- See Also:
- Java String.trim has a strange idea of whitespace, JDK bug 4080617, JDK bug 7190385
-
strip
public static java.lang.String strip(java.lang.String str, java.lang.String skipChars)
An alternative toString.trim()
to effectively remove all leading and trailing white characters, including Unicode ones.- Parameters:
str
- The string to stripskipChars
- additional characters to skip- Returns:
str
, without leading and trailing characters, according toCharacter.isWhitespace(char)
,Character.isSpaceChar(char)
and skipChars.- Since:
- 8435
-
isStrippedChar
private static boolean isStrippedChar(char c, java.lang.String skipChars)
-
removeWhiteSpaces
public static java.lang.String removeWhiteSpaces(java.lang.String s)
Removes leading, trailing, and multiple inner whitespaces from the given string, to be used as a key or value.- Parameters:
s
- The string- Returns:
- The string without leading, trailing or multiple inner whitespaces
- Since:
- 13597
-
removeWhiteSpaces
public static java.lang.String removeWhiteSpaces(java.util.regex.Pattern whitespaces, java.lang.String s)
Removes leading, trailing, and multiple inner whitespaces from the given string, to be used as a key or value.- Parameters:
s
- The stringwhitespaces
- The regex for whitespaces to remove outside the leading and trailing whitespaces (seestrip(String)
)- Returns:
- The string without leading, trailing or multiple inner whitespaces
- Since:
- 19261
-
execOutput
public static java.lang.String execOutput(java.util.List<java.lang.String> command) throws java.io.IOException, java.util.concurrent.ExecutionException, java.lang.InterruptedException
Runs an external command and returns the standard output.The program is expected to execute fast, as this call waits 10 seconds at most.
- Parameters:
command
- the command with arguments- Returns:
- the output
- Throws:
java.io.IOException
- when there was an error, e.g. command does not existjava.util.concurrent.ExecutionException
- when the return code is != 0. The output is can be retrieved in the exception messagejava.lang.InterruptedException
- if the current thread is interrupted by another thread while waiting
-
execOutput
public static java.lang.String execOutput(java.util.List<java.lang.String> command, long timeout, java.util.concurrent.TimeUnit unit) throws java.io.IOException, java.util.concurrent.ExecutionException, java.lang.InterruptedException
Runs an external command and returns the standard output. Waits at most the specified time.- Parameters:
command
- the command with argumentstimeout
- the maximum time to waitunit
- the time unit of thetimeout
argument. Must not be null- Returns:
- the output
- Throws:
java.io.IOException
- when there was an error, e.g. command does not existjava.util.concurrent.ExecutionException
- when the return code is != 0. The output is can be retrieved in the exception messagejava.lang.InterruptedException
- if the current thread is interrupted by another thread while waiting- Since:
- 13467
-
getJosmTempDir
public static java.io.File getJosmTempDir()
Returns the JOSM temp directory.- Returns:
- The JOSM temp directory (
<java.io.tmpdir>/JOSM
), ornull
ifjava.io.tmpdir
is not defined - Since:
- 6245
-
getDurationString
public static java.lang.String getDurationString(long elapsedTime)
Returns a simple human readable (hours, minutes, seconds) string for a given duration in milliseconds.- Parameters:
elapsedTime
- The duration in milliseconds- Returns:
- A human readable string for the given duration
- Throws:
java.lang.IllegalArgumentException
- if elapsedTime is < 0- Since:
- 6354
-
getSizeString
public static java.lang.String getSizeString(long bytes, java.util.Locale locale)
Returns a human readable representation (B, kB, MB, ...) for the given number of byes.- Parameters:
bytes
- the number of byteslocale
- the locale used for formatting- Returns:
- a human readable representation
- Since:
- 9274
-
getPositionListString
public static java.lang.String getPositionListString(java.util.List<java.lang.Integer> positionList)
Returns a human readable representation of a list of positions.For instance,
[1,5,2,6,7
yields "1-2,5-7- Parameters:
positionList
- a list of positions- Returns:
- a human readable representation
-
getMatches
public static java.util.List<java.lang.String> getMatches(java.util.regex.Matcher m)
Returns a list of capture groups ifMatcher.matches()
, ornull
. The first element (index 0) is the complete match. Further elements correspond to the parts in parentheses of the regular expression.- Parameters:
m
- the matcher- Returns:
- a list of capture groups if
Matcher.matches()
, ornull
.
-
cast
public static <T> T cast(java.lang.Object o, java.lang.Class<T> klass)
Cast an object safely.- Type Parameters:
T
- the target type- Parameters:
o
- the object to castklass
- the target class (same as T)- Returns:
- null if
o
is null or the typeo
is not a subclass ofklass
. The casted value otherwise.
-
getRootCause
public static java.lang.Throwable getRootCause(java.lang.Throwable t)
Returns the root cause of a throwable object.- Parameters:
t
- The object to get root cause for- Returns:
- the root cause of
t
- Since:
- 6639
-
addInArrayCopy
public static <T> T[] addInArrayCopy(T[] array, T item)
Adds the given item at the end of a new copy of given array.- Type Parameters:
T
- type of items- Parameters:
array
- The source arrayitem
- The item to add- Returns:
- An extended copy of
array
containingitem
as additional last element - Since:
- 6717
-
shortenString
public static java.lang.String shortenString(java.lang.String s, int maxLength)
If the strings
is longer thanmaxLength
, the string is cut and "..." is appended.- Parameters:
s
- String to shortenmaxLength
- maximum number of characters to keep (not including the "...")- Returns:
- the shortened string
- Throws:
java.lang.IllegalArgumentException
- if maxLength is less than the length of "..."
-
restrictStringLines
public static java.lang.String restrictStringLines(java.lang.String s, int maxLines)
If the strings
is longer thanmaxLines
lines, the string is cut and a "..." line is appended.- Parameters:
s
- String to shortenmaxLines
- maximum number of lines to keep (including including the "..." line)- Returns:
- the shortened string
-
limit
public static <T> java.util.Collection<T> limit(java.util.Collection<T> elements, int maxElements, T overflowIndicator)
If the collectionelements
is larger thanmaxElements
elements, the collection is shortened and theoverflowIndicator
is appended.- Type Parameters:
T
- type of elements- Parameters:
elements
- collection to shortenmaxElements
- maximum number of elements to keep (including theoverflowIndicator
)overflowIndicator
- the element used to indicate that the collection has been shortened- Returns:
- the shortened collection
-
fixURLQuery
public static java.lang.String fixURLQuery(java.lang.String url)
Fixes URL with illegal characters in the query (and fragment) part by percent encoding those characters.special characters like & and # are not encoded
- Parameters:
url
- the URL that should be fixed- Returns:
- the repaired URL
-
encodeUrl
public static java.lang.String encodeUrl(java.lang.String s)
Translates a string intoapplication/x-www-form-urlencoded
format. This method uses UTF-8 encoding scheme to obtain the bytes for unsafe characters.- Parameters:
s
-String
to be translated.- Returns:
- the translated
String
. - Since:
- 8304
- See Also:
decodeUrl(String)
-
decodeUrl
public static java.lang.String decodeUrl(java.lang.String s)
Decodes aapplication/x-www-form-urlencoded
string. UTF-8 encoding is used to determine what characters are represented by any consecutive sequences of the form "%xy
".- Parameters:
s
- theString
to decode- Returns:
- the newly decoded
String
- Since:
- 8304
- See Also:
encodeUrl(String)
-
isLocalUrl
public static boolean isLocalUrl(java.lang.String url)
Determines if the given URL denotes a file on a local filesystem.- Parameters:
url
- The URL to test- Returns:
true
if the url points to a local file- Since:
- 7356
-
isValidUrl
public static boolean isValidUrl(java.lang.String url)
Determines if the given URL is valid.- Parameters:
url
- The URL to test- Returns:
true
if the url is valid- Since:
- 10294
-
newThreadFactory
public static java.util.concurrent.ThreadFactory newThreadFactory(java.lang.String nameFormat, int threadPriority)
Creates a newThreadFactory
which creates threads with names according tonameFormat
.- Parameters:
nameFormat
- aString.format(String, Object...)
compatible name format; its first argument is a unique thread indexthreadPriority
- the priority of the created threads, seeThread.setPriority(int)
- Returns:
- a new
ThreadFactory
-
getLevenshteinDistance
public static int getLevenshteinDistance(java.lang.String s, java.lang.String t)
Compute Levenshtein distance- Parameters:
s
- First wordt
- Second word- Returns:
- The distance between words
- Since:
- 14371
-
isSimilar
public static boolean isSimilar(java.lang.String string1, java.lang.String string2)
Check if two strings are similar, but not identical, i.e., have a Levenshtein distance of 1 or 2.- Parameters:
string1
- first string to comparestring2
- second string to compare- Returns:
- true if the normalized strings are different but only a "little bit"
- Since:
- 14371
- See Also:
getLevenshteinDistance(java.lang.String, java.lang.String)
-
getStandardDeviation
public static double getStandardDeviation(double[] values)
Calculates the standard deviation of population.- Parameters:
values
- an array of values- Returns:
- standard deviation of the given array, or -1.0 if the array has less than two values
- Since:
- 18553
- See Also:
getStandardDeviation(double[], double)
-
getStandardDeviation
public static double getStandardDeviation(double[] values, double mean)
Calculates the standard deviation of population with the given mean value.- Parameters:
values
- an array of valuesmean
- precalculated average value of the array- Returns:
- standard deviation of the given array, or -1.0 if the array has less than two values
- Since:
- 18553
- See Also:
getStandardDeviation(double[])
-
groupIntegers
public static int[][] groupIntegers(int... integers)
Group a list of integers, mostly useful to avoid calling many selection change events for a logical interval.
Example:groupIntegers(1, 2, 3, 5, 6, 7, 8, 9)
becomes[[1, 3], [5, 9]]
- Parameters:
integers
- The integers to group- Returns:
- The integers grouped into logical blocks, [lower, higher] (inclusive)
- Since:
- 18556
-
newForkJoinPool
public static java.util.concurrent.ForkJoinPool newForkJoinPool(java.lang.String pref, java.lang.String nameFormat, int threadPriority)
Returns aForkJoinPool
with the parallelism given by the preference key.- Parameters:
pref
- The preference key to determine parallelismnameFormat
- seenewThreadFactory(String, int)
threadPriority
- seenewThreadFactory(String, int)
- Returns:
- a
ForkJoinPool
-
newDirectExecutor
public static java.util.concurrent.Executor newDirectExecutor()
Returns an executor which executes commands in the calling thread- Returns:
- an executor
-
getSystemEnv
public static java.lang.String getSystemEnv(java.lang.String name)
Gets the value of the specified environment variable. An environment variable is a system-dependent external named value.- Parameters:
name
- name the name of the environment variable- Returns:
- the string value of the variable;
null
if the variable is not defined in the system environment or if a security exception occurs. - Since:
- 13647
- See Also:
System.getenv(String)
-
getSystemProperty
public static java.lang.String getSystemProperty(java.lang.String key)
Gets the system property indicated by the specified key.- Parameters:
key
- the name of the system property.- Returns:
- the string value of the system property;
null
if there is no property with that key or if a security exception occurs. - Since:
- 13647
- See Also:
System.getProperty(String)
-
updateSystemProperty
public static java.lang.String updateSystemProperty(java.lang.String key, java.lang.String value)
Updates a given system property.- Parameters:
key
- The property keyvalue
- The property value- Returns:
- the previous value of the system property, or
null
if it did not have one. - Since:
- 7894
-
hasExtension
public static boolean hasExtension(java.lang.String filename, java.lang.String... extensions)
Determines if the filename has one of the given extensions, in a robust manner. The comparison is case and locale insensitive.- Parameters:
filename
- The file nameextensions
- The list of extensions to look for (without dot)- Returns:
true
if the filename has one of the given extensions- Since:
- 8404
-
hasExtension
public static boolean hasExtension(java.io.File file, java.lang.String... extensions)
Determines if the file's name has one of the given extensions, in a robust manner. The comparison is case and locale insensitive.- Parameters:
file
- The fileextensions
- The list of extensions to look for (without dot)- Returns:
true
if the file's name has one of the given extensions- Since:
- 8404
-
hashMapInitialCapacity
public static int hashMapInitialCapacity(int nEntries, double loadFactor)
Returns the initial capacity to pass to the HashMap / HashSet constructor when it is initialized with a known number of entries.When a HashMap is filled with entries, the underlying array is copied over to a larger one multiple times. To avoid this process when the number of entries is known in advance, the initial capacity of the array can be given to the HashMap constructor. This method returns a suitable value that avoids rehashing but doesn't waste memory.
- Parameters:
nEntries
- the number of entries expectedloadFactor
- the load factor- Returns:
- the initial capacity for the HashMap constructor
-
hashMapInitialCapacity
public static int hashMapInitialCapacity(int nEntries)
Returns the initial capacity to pass to the HashMap / HashSet constructor when it is initialized with a known number of entries.When a HashMap is filled with entries, the underlying array is copied over to a larger one multiple times. To avoid this process when the number of entries is known in advance, the initial capacity of the array can be given to the HashMap constructor. This method returns a suitable value that avoids rehashing but doesn't waste memory.
Assumes default load factor (0.75).
- Parameters:
nEntries
- the number of entries expected- Returns:
- the initial capacity for the HashMap constructor
-
getGlyphVectorsBidi
public static java.util.List<java.awt.font.GlyphVector> getGlyphVectorsBidi(java.lang.String string, java.awt.Font font, java.awt.font.FontRenderContext frc)
Convert a string to a list ofGlyphVector
s. The string may contain bi-directional text. The result will be in correct visual order. Each element of the resulting list corresponds to one section of the string with consistent writing direction (left-to-right or right-to-left).- Parameters:
string
- the string to renderfont
- the fontfrc
- a FontRenderContext object- Returns:
- a list of GlyphVectors
-
deAccent
public static java.lang.String deAccent(java.lang.String str)
Removes diacritics (accents) from string.- Parameters:
str
- string- Returns:
str
without any diacritic (accent)- Since:
- 13836 (moved from SimilarNamedWays)
-
clamp
public static double clamp(double val, double min, double max)
Clamp a value to the given range- Parameters:
val
- The valuemin
- minimum valuemax
- maximum value- Returns:
- the value
- Throws:
java.lang.IllegalArgumentException
- ifmin > max
- Since:
- 10805
-
clamp
public static int clamp(int val, int min, int max)
Clamp a integer value to the given range- Parameters:
val
- The valuemin
- minimum valuemax
- maximum value- Returns:
- the value
- Throws:
java.lang.IllegalArgumentException
- ifmin > max
- Since:
- 11055
-
toDegrees
public static double toDegrees(double angleRad)
Convert angle from radians to degrees.Replacement for
Math.toDegrees(double)
to match the Java 9 version of that method. (Can be removed when JOSM support for Java 8 ends.) Only relevant in relation to ProjectionRegressionTest.- Parameters:
angleRad
- an angle in radians- Returns:
- the same angle in degrees
- Since:
- 12013
- See Also:
- #11889
-
toRadians
public static double toRadians(double angleDeg)
Convert angle from degrees to radians.Replacement for
Math.toRadians(double)
to match the Java 9 version of that method. (Can be removed when JOSM support for Java 8 ends.) Only relevant in relation to ProjectionRegressionTest.- Parameters:
angleDeg
- an angle in degrees- Returns:
- the same angle in radians
- Since:
- 12013
- See Also:
- #11889
-
getJavaVersion
public static int getJavaVersion()
Returns the Java version as an int value.- Returns:
- the Java version as an int value (8, 9, 10, etc.)
- Since:
- 12130
-
getJavaUpdate
public static int getJavaUpdate()
Returns the Java update as an int value.- Returns:
- the Java update as an int value (121, 131, etc.)
- Since:
- 12217
-
getJavaBuild
public static int getJavaBuild()
Returns the Java build number as an int value.- Returns:
- the Java build number as an int value (0, 1, etc.)
- Since:
- 12217
-
getJavaExpirationDate
public static java.util.Date getJavaExpirationDate()
Returns the JRE expiration date.- Returns:
- the JRE expiration date, or null
- Since:
- 12219
-
getJavaLatestVersion
public static java.lang.String getJavaLatestVersion()
Returns the latest version of Java, from Oracle website.- Returns:
- the latest version of Java, from Oracle website
- Since:
- 12219
-
isClassFound
public static boolean isClassFound(java.lang.String className)
Determines if a class can be found for the given name.- Parameters:
className
- class name to find- Returns:
true
if the class can be found,false
otherwise- Since:
- 17692
-
isRunningWebStart
public static boolean isRunningWebStart()
Determines whether JOSM has been started via Web Start (JNLP).- Returns:
- true if JOSM has been started via Web Start (JNLP)
- Since:
- 17679
-
isRunningOpenWebStart
public static boolean isRunningOpenWebStart()
Determines whether JOSM has been started via Open Web Start (IcedTea-Web).- Returns:
- true if JOSM has been started via Open Web Start (IcedTea-Web)
- Since:
- 17679
-
castToStream
public static <T,U> java.util.function.Function<T,java.util.stream.Stream<U>> castToStream(java.lang.Class<U> klass)
Get a function that converts an object to a singleton stream of a certain class (or null if the object cannot be cast to that class).Can be useful in relation with streams, but be aware of the performance implications of creating a stream for each element.
- Type Parameters:
T
- type of the objects to convertU
- type of the elements in the resulting stream- Parameters:
klass
- the class U- Returns:
- function converting an object to a singleton stream or null
- Since:
- 12594
-
instanceOfThen
public static <T> void instanceOfThen(java.lang.Object o, java.lang.Class<T> klass, java.util.function.Consumer<? super T> consumer)
Helper method to replace the "instanceof
-check and cast" pattern. Checks if an object is instance of class T and performs an action if that is the case. Syntactic sugar to avoid typing the class name two times, when one time would suffice.- Type Parameters:
T
- the type for the instanceof check and cast- Parameters:
o
- the object to check and castklass
- the class Tconsumer
- action to take when o is and instance of T- Since:
- 12604
-
instanceOfAndCast
public static <T> java.util.Optional<T> instanceOfAndCast(java.lang.Object o, java.lang.Class<T> klass)
Helper method to replace the "instanceof
-check and cast" pattern.- Type Parameters:
T
- the type for the instanceof check and cast- Parameters:
o
- the object to check and castklass
- the class T- Returns:
Optional
containing the result of the cast, if it is possible, an empty Optional otherwise
-
openStream
public static java.io.InputStream openStream(java.net.URL url) throws java.io.IOException
Convenient method to open an URL stream, using JOSM HTTP client if needed.- Parameters:
url
- URL for reading from- Returns:
- an input stream for reading from the URL
- Throws:
java.io.IOException
- if any I/O error occurs- Since:
- 13356
-
betterJarUrl
public static java.net.URL betterJarUrl(java.net.URL jarUrl) throws java.io.IOException
Tries to build a better JAR URL if we find it concerned by a JDK bug.- Parameters:
jarUrl
- jar URL to test- Returns:
- potentially a better URL that won't provoke a JDK bug, or null
- Throws:
java.io.IOException
- if an I/O error occurs- Since:
- 14404
-
betterJarUrl
public static java.net.URL betterJarUrl(java.net.URL jarUrl, java.net.URL defaultUrl) throws java.io.IOException
Tries to build a better JAR URL if we find it concerned by a JDK bug.- Parameters:
jarUrl
- jar URL to testdefaultUrl
- default URL to return- Returns:
- potentially a better URL that won't provoke a JDK bug, or
defaultUrl
- Throws:
java.io.IOException
- if an I/O error occurs- Since:
- 14480
-
getResourceAsStream
public static java.io.InputStream getResourceAsStream(java.lang.Class<?> klass, java.lang.String path)
Finds a resource with a given name, with robustness to known JDK bugs.- Parameters:
klass
- class on whichClassLoader.getResourceAsStream(java.lang.String)
will be calledpath
- name of the desired resource- Returns:
- A
InputStream
object ornull
if no resource with this name is found - Since:
- 14480
-
getResourceAsStream
public static java.io.InputStream getResourceAsStream(java.lang.ClassLoader cl, java.lang.String path)
Finds a resource with a given name, with robustness to known JDK bugs.- Parameters:
cl
- classloader on whichClassLoader.getResourceAsStream(java.lang.String)
will be calledpath
- name of the desired resource- Returns:
- A
InputStream
object ornull
if no resource with this name is found - Since:
- 15416
-
stripHtml
public static java.lang.String stripHtml(java.lang.String rawString)
Strips all HTML characters and return the result.- Parameters:
rawString
- The raw HTML string- Returns:
- the plain text from the HTML string
- Since:
- 15760
-
intern
public static java.lang.String intern(java.lang.String string)
Intern a string- Parameters:
string
- The string to intern- Returns:
- The interned string
- Since:
- 16545
-
unitToMeter
public static java.lang.Double unitToMeter(java.lang.String s) throws java.lang.IllegalArgumentException
Convert a length unit to meters- Parameters:
s
- arbitrary string representing a length- Returns:
- the length converted to meters
- Throws:
java.lang.IllegalArgumentException
- if input is no valid length- Since:
- 19089
-
unitToMeterConversion
private static double unitToMeterConversion(java.lang.String unit) throws java.lang.IllegalArgumentException
Get the conversion factor for a specified unit to meters- Parameters:
unit
- The unit to convert to meters- Returns:
- The conversion factor or 1.
- Throws:
java.lang.IllegalArgumentException
- if the unit does not currently have a conversion
-
-