Package org.openstreetmap.josm.tools
Class Utils
- java.lang.Object
-
- org.openstreetmap.josm.tools.Utils
-
-
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 String
DEFAULT_STRIP
private static double
EPSILON
private static char[]
HEX_ARRAY
(package private) static Method
mapOfEntries
A reference toMap.ofEntries()
available since Java 9private 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 Pattern
REMOVE_DIACRITICS
private static String[]
SIZE_UNITS
private static double
TO_DEGREES
private static double
TO_RADIANS
static String
URL_CHARS
A list of all characters allowed in URLsstatic Pattern
WHITE_SPACES_PATTERN
Pattern matching white spaces
-
Constructor Summary
Constructors Modifier Constructor Description private
Utils()
-
Method Summary
All Methods Static Methods Concrete Methods Deprecated 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 URL
betterJarUrl(URL jarUrl)
Tries to build a better JAR URL if we find it concerned by a JDK bug.static URL
betterJarUrl(URL jarUrl, URL defaultUrl)
Tries to build a better JAR URL if we find it concerned by a JDK bug.static <T> T
cast(Object o, Class<T> klass)
Cast an object savely.static <T,U>
Function<T,Stream<U>>castToStream(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(Closeable c)
Utility method for closing aCloseable
object.static void
close(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(File in, File out)
Recursive directory copy functionstatic Path
copyFile(File in, File out)
Simple file copy function that will overwrite the target file.static String
deAccent(String str)
Removes diacritics (accents) from string.static String
decodeUrl(String s)
Decodes aapplication/x-www-form-urlencoded
string.static boolean
deleteDirectory(File path)
Deletes a directory recursively.static boolean
deleteFile(File file)
Deletes a file and log a default warning if the deletion fails.static boolean
deleteFile(File file, String warnMsg)
Deletes a file and log a configurable warning if the deletion fails.static boolean
deleteFileIfExists(File file)
Deletes a file and log a default warning if the file exists but the deletion fails.static String
encodeUrl(String s)
Translates a string intoapplication/x-www-form-urlencoded
format.static void
ensure(boolean condition, String message, 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 String
escapeReservedCharactersHTML(String s)
Replaces some HTML reserved characters (<, > and &) by their equivalent entity (<, > and &);static String
execOutput(List<String> command)
Runs an external command and returns the standard output.static String
execOutput(List<String> command, long timeout, TimeUnit unit)
Runs an external command and returns the standard output.static URL
fileToURL(File f)
Converts the given file to its URL.static <S,T extends S>
SubclassFilteredCollection<S,T>filteredCollection(Collection<S> collection, 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 String
firstNotEmptyString(String defaultString, String... candidates)
Returns the first not empty string in the given candidates, otherwise the default string.static String
fixURLQuery(String url)
Fixes URL with illegal characters in the query (and fragment) part by percent encoding those characters.static String
getDurationString(long elapsedTime)
Returns a simple human readable (hours, minutes, seconds) string for a given duration in milliseconds.static List<GlyphVector>
getGlyphVectorsBidi(String string, Font font, FontRenderContext frc)
Convert a string to a list ofGlyphVector
s.static int
getJavaBuild()
Returns the Java build number as an int value.static Date
getJavaExpirationDate()
Returns the JRE expiration date.static 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 File
getJosmTempDir()
Returns the JOSM temp directory.static int
getLevenshteinDistance(String s, String t)
Compute Levenshtein distancestatic List<String>
getMatches(Matcher m)
Returns a list of capture groups ifMatcher.matches()
, ornull
.static String
getPositionListString(List<Integer> positionList)
Returns a human readable representation of a list of positions.static InputStream
getResourceAsStream(Class<?> klass, String path)
Finds a resource with a given name, with robustness to known JDK bugs.static InputStream
getResourceAsStream(ClassLoader cl, String path)
Finds a resource with a given name, with robustness to known JDK bugs.static Throwable
getRootCause(Throwable t)
Returns the root cause of a throwable object.static String
getSizeString(long bytes, Locale locale)
Returns a human readable representation (B, kB, MB, ...) for the given number of byes.static String
getSystemEnv(String name)
Gets the value of the specified environment variable.static String
getSystemProperty(String key)
Gets the system property indicated by the specified key.static boolean
hasExtension(File file, String... extensions)
Determines if the file's name has one of the given extensions, in a robust manner.static boolean
hasExtension(String filename, 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(Iterable<? extends T> collection, Predicate<? super T> predicate)
Find the index of the first item that matches the predicate.static <T> Optional<T>
instanceOfAndCast(Object o, Class<T> klass)
Helper method to replace the "instanceof
-check and cast" pattern.static <T> void
instanceOfThen(Object o, Class<T> klass, Consumer<? super T> consumer)
Helper method to replace the "instanceof
-check and cast" pattern.static String
intern(String string)
Intern a stringstatic boolean
isBlank(String string)
Determines if a string is null or blank.static boolean
isClassFound(String className)
Determines if a class can be found for the given name.static boolean
isEmpty(String string)
Determines if a string is null or empty.static boolean
isEmpty(Collection<?> collection)
Determines if a collection is null or empty.static boolean
isEmpty(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(String url)
Determines if the given URL denotes a file on a local filesystem.static boolean
isRunningJavaWebStart()
Determines whether JOSM has been started via Oracle Java Web Start.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(String string1, String string2)
Check if two strings are similar, but not identical, i.e., have a Levenshtein distance of 1 or 2.static boolean
isStripEmpty(String str)
Determines if the given String would be empty if stripped.private static boolean
isStrippedChar(char c, String skipChars)
static boolean
isValidUrl(String url)
Determines if the given URL is valid.static String
join(String sep, Collection<?> values)
static String
joinAsHtmlUnorderedList(Iterable<?> values)
Converts the given iterable collection as an unordered HTML list.static <T> Collection<T>
limit(Collection<T> elements, int maxElements, T overflowIndicator)
If the collectionelements
is larger thanmaxElements
elements, the collection is shortened and theoverflowIndicator
is appended.private static Method
mapOfEntriesMethod()
static String
md5Hex(String data)
Calculate MD5 hash of a string and output in hexadecimal format.static boolean
mkDirs(File dir)
Creates a directory and log a default warning if the creation fails.static boolean
mkDirs(File dir, String warnMsg)
Creates a directory and log a configurable warning if the creation fails.static int
mod(int a, int n)
Return the modulus in the range [0, n)static Executor
newDirectExecutor()
Returns an executor which executes commands in the calling threadstatic ForkJoinPool
newForkJoinPool(String pref, String nameFormat, int threadPriority)
Returns aForkJoinPool
with the parallelism given by the preference key.static ThreadFactory
newThreadFactory(String nameFormat, int threadPriority)
Creates a newThreadFactory
which creates threads with names according tonameFormat
.static InputStream
openStream(URL url)
Convenient method to open an URL stream, using JOSM HTTP client if neeeded.static byte[]
readBytesFromStream(InputStream stream)
Reads the input stream and closes the stream at the end of processing (regardless if an exception was thrown)static String
removeWhiteSpaces(String s)
Removes leading, trailing, and multiple inner whitespaces from the given string, to be used as a key or value.static String
restrictStringLines(String s, int maxLines)
If the strings
is longer thanmaxLines
lines, the string is cut and a "..." line is appended.static String
shortenString(String s, int maxLength)
If the strings
is longer thanmaxLength
, the string is cut and "..." is appended.static String
strip(String str)
An alternative toString.trim()
to effectively remove all leading and trailing white characters, including Unicode ones.static String
strip(String str, String skipChars)
An alternative toString.trim()
to effectively remove all leading and trailing white characters, including Unicode ones.static String
stripHtml(String rawString)
Strips all HTML characters and return the result.static double
toDegrees(double angleRad)
Convert angle from radians to degrees.static String
toHexString(byte[] bytes)
Converts a byte array to a string of hexadecimal characters.static <T> List<T>
topologicalSort(MultiMap<T,T> dependencies)
Topological sort.static double
toRadians(double angleDeg)
Convert angle from degrees to radians.static <T> List<T>
toUnmodifiableList(Collection<T> collection)
Returns an unmodifiable list for the given collection.static <K,V>
Map<K,V>toUnmodifiableMap(Map<K,V> map)
Returns an unmodifiable map for the given map.static <A,B>
Collection<B>transform(Collection<? extends A> c, Function<A,B> f)
Transforms the collectionc
into an unmodifiable collection and applies theFunction
f
on each element upon access.static <A,B>
List<B>transform(List<? extends A> l, Function<A,B> f)
Transforms the listl
into an unmodifiable list and applies theFunction
f
on each element upon access.static String
updateSystemProperty(String key, String value)
Updates a given system property.static URI
urlToURI(String url)
Converts the given URL to its URI.static URI
urlToURI(URL url)
Converts the given URL to its URI.
-
-
-
Field Detail
-
WHITE_SPACES_PATTERN
public static final 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
-
URL_CHARS
public static final String URL_CHARS
A list of all characters allowed in URLs- See Also:
- Constant Field Values
-
REMOVE_DIACRITICS
private static final Pattern REMOVE_DIACRITICS
-
DEFAULT_STRIP
private static final String DEFAULT_STRIP
- See Also:
- Constant Field Values
-
SIZE_UNITS
private static final 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
-
mapOfEntries
static final Method mapOfEntries
A reference toMap.ofEntries()
available since Java 9
-
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
-
mapOfEntriesMethod
private static Method mapOfEntriesMethod()
-
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(Collection<S> collection, 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(Iterable<? extends T> collection, 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, String message, 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:
AssertionError
- if the condition is not met
-
mod
public static int mod(int a, int n)
Return the modulus in the range [0, n)- Parameters:
a
- dividendn
- divisor- Returns:
- modulo (remainder of the Euclidian division of a by n)
-
join
@Deprecated public static String join(String sep, Collection<?> values)
Deprecated.Joins a list of strings (or objects that can be converted to string via Object.toString()) into a single string with fields separated by sep.- Parameters:
sep
- the separatorvalues
- collection of objects, null is converted to the empty string- Returns:
- null if values is null. The joined string otherwise.
-
joinAsHtmlUnorderedList
public static String joinAsHtmlUnorderedList(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 Path copyFile(File in, File out) throws 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:
IOException
- if any I/O error occursIllegalArgumentException
- ifin
orout
isnull
InvalidPathException
- if a Path object cannot be constructed from the abstract path- Since:
- 7003
-
copyDirectory
public static void copyDirectory(File in, File out) throws IOException
Recursive directory copy function- Parameters:
in
- The source directoryout
- The destination directory- Throws:
IOException
- if any I/O error ooccursIllegalArgumentException
- ifin
orout
isnull
- Since:
- 7835
-
deleteDirectory
public static boolean deleteDirectory(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(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(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(File file, 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(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(File dir, 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(Closeable c)
Utility method for closing a
Closeable
object.- Parameters:
c
- the closeable object. May be null.
-
close
public static void close(ZipFile zip)
Utility method for closing a
ZipFile
.- Parameters:
zip
- the zip file. May be null.
-
fileToURL
public static URL fileToURL(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 URI urlToURI(String url) throws URISyntaxException, MalformedURLException
Converts the given URL to its URI.- Parameters:
url
- the URL to get URI from- Returns:
- the URI of given URL
- Throws:
URISyntaxException
- if the URL cannot be converted to an URIMalformedURLException
- if no protocol is specified, or an unknown protocol is found, orspec
isnull
.- Since:
- 15543
-
urlToURI
public static URI urlToURI(URL url) throws URISyntaxException
Converts the given URL to its URI.- Parameters:
url
- the URL to get URI from- Returns:
- the URI of given URL
- Throws:
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 String md5Hex(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 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> 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 String escapeReservedCharactersHTML(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> Collection<B> transform(Collection<? extends A> c, 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> List<B> transform(List<? extends A> l, 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> List<T> toUnmodifiableList(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> Map<K,V> toUnmodifiableMap(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(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(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(String string)
Determines if a string is null or empty.- Parameters:
string
- string- Returns:
true
if string is null or empty- Since:
- 18207
-
isBlank
public static boolean isBlank(String string)
Determines if a string is null or blank.- Parameters:
string
- string- Returns:
true
if string is null or blank- Since:
- 18208
-
firstNotEmptyString
public static String firstNotEmptyString(String defaultString, 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(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 String strip(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 String strip(String str, 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, String skipChars)
-
removeWhiteSpaces
public static String removeWhiteSpaces(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
-
execOutput
public static String execOutput(List<String> command) throws IOException, ExecutionException, 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:
IOException
- when there was an error, e.g. command does not existExecutionException
- when the return code is != 0. The output is can be retrieved in the exception messageInterruptedException
- if the current thread is interrupted by another thread while waiting
-
execOutput
public static String execOutput(List<String> command, long timeout, TimeUnit unit) throws IOException, ExecutionException, 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:
IOException
- when there was an error, e.g. command does not existExecutionException
- when the return code is != 0. The output is can be retrieved in the exception messageInterruptedException
- if the current thread is interrupted by another thread while waiting- Since:
- 13467
-
getJosmTempDir
public static 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 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:
IllegalArgumentException
- if elapsedTime is < 0- Since:
- 6354
-
getSizeString
public static String getSizeString(long bytes, 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 String getPositionListString(List<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 List<String> getMatches(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(Object o, Class<T> klass)
Cast an object savely.- 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 Throwable getRootCause(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 String shortenString(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:
IllegalArgumentException
- if maxLength is less than the length of "..."
-
restrictStringLines
public static String restrictStringLines(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> Collection<T> limit(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 including theoverflowIndicator
)overflowIndicator
- the element used to indicate that the collection has been shortened- Returns:
- the shortened collection
-
fixURLQuery
public static String fixURLQuery(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 String encodeUrl(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 String decodeUrl(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(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(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 ThreadFactory newThreadFactory(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(String s, String t)
Compute Levenshtein distance- Parameters:
s
- First wordt
- Second word- Returns:
- The distance between words
- Since:
- 14371
-
isSimilar
public static boolean isSimilar(String string1, 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)
-
newForkJoinPool
public static ForkJoinPool newForkJoinPool(String pref, 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 Executor newDirectExecutor()
Returns an executor which executes commands in the calling thread- Returns:
- an executor
-
getSystemEnv
public static String getSystemEnv(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 String getSystemProperty(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 String updateSystemProperty(String key, 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(String filename, 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(File file, 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
-
readBytesFromStream
public static byte[] readBytesFromStream(InputStream stream) throws IOException
Reads the input stream and closes the stream at the end of processing (regardless if an exception was thrown)- Parameters:
stream
- input stream- Returns:
- byte array of data in input stream (empty if stream is null)
- Throws:
IOException
- if any I/O error occurs
-
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 List<GlyphVector> getGlyphVectorsBidi(String string, Font 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 String deAccent(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:
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:
IllegalArgumentException
- ifmin > max
- Since:
- 11055
-
toDegrees
public static double toDegrees(double angleRad)
Convert angle from radians to degrees. Replacement forMath.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 forMath.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 Date getJavaExpirationDate()
Returns the JRE expiration date.- Returns:
- the JRE expiration date, or null
- Since:
- 12219
-
getJavaLatestVersion
public static 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(String className)
Determines if a class can be found for the given name.- Parameters:
className
- class nmae 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
-
isRunningJavaWebStart
public static boolean isRunningJavaWebStart()
Determines whether JOSM has been started via Oracle Java Web Start.- Returns:
- true if JOSM has been started via Oracle Java Web Start
- Since:
- 15740
-
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> Function<T,Stream<U>> castToStream(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(Object o, Class<T> klass, 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> Optional<T> instanceOfAndCast(Object o, 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 InputStream openStream(URL url) throws IOException
Convenient method to open an URL stream, using JOSM HTTP client if neeeded.- Parameters:
url
- URL for reading from- Returns:
- an input stream for reading from the URL
- Throws:
IOException
- if any I/O error occurs- Since:
- 13356
-
betterJarUrl
public static URL betterJarUrl(URL jarUrl) throws 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:
IOException
- if an I/O error occurs- Since:
- 14404
-
betterJarUrl
public static URL betterJarUrl(URL jarUrl, URL defaultUrl) throws 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:
IOException
- if an I/O error occurs- Since:
- 14480
-
getResourceAsStream
public static InputStream getResourceAsStream(Class<?> klass, 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 InputStream getResourceAsStream(ClassLoader cl, 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 String stripHtml(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
-
-