public final class Utils extends java.lang.Object
Modifier and Type | Class and 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.
|
Modifier and Type | Field and Description |
---|---|
private static char[] |
DEFAULT_STRIP |
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.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 URLs
|
static java.util.regex.Pattern |
WHITE_SPACES_PATTERN
Pattern matching white spaces
|
Modifier | Constructor and Description |
---|---|
private |
Utils() |
Modifier and Type | Method and 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.awt.Color |
alphaMultiply(java.awt.Color color,
float alphaFactor)
Multiply the alpha value of the given color with the factor.
|
static <T> T |
cast(java.lang.Object o,
java.lang.Class<T> klass)
Cast an object savely.
|
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 range
|
static int |
clamp(int val,
int min,
int max)
Clamp a integer value to the given range
|
static void |
close(java.io.Closeable c)
Utility method for closing a
Closeable object. |
static void |
close(java.util.zip.ZipFile zip)
Utility method for closing a
ZipFile . |
static java.lang.Integer |
colorFloat2int(java.lang.Float val)
convert float range 0 <= x <= 1 to integer range 0..255
when dealing with colors and color alpha value
|
static java.lang.Float |
colorInt2float(java.lang.Integer val)
convert integer range 0..255 to float range 0 <= x <= 1
when dealing with colors and color alpha value
|
static java.awt.Color |
complement(java.awt.Color clr)
Returns the complementary color of
clr . |
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 function
|
static 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 |
decodeUrl(java.lang.String s)
Decodes a
application/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 into
application/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 <T> boolean |
exists(java.lang.Iterable<T> collection,
java.lang.Class<? extends T> clazz)
Checks if an item that is an instance of clazz exists in the collection
|
static java.net.URL |
fileToURL(java.io.File f)
Converts the given file to its URL.
|
static <S,T extends S> |
filteredCollection(java.util.Collection<S> collection,
java.lang.Class<T> clazz)
Filter a collection by (sub)class.
|
static <T> T |
find(java.lang.Iterable<? extends java.lang.Object> collection,
java.lang.Class<? extends T> clazz)
Finds the first item in the iterable which is of the given type.
|
static <T> T |
find(java.lang.Iterable<? extends T> collection,
java.util.function.Predicate<? super T> predicate)
Finds the first item in the iterable for which the predicate matches.
|
static <T> T |
firstNonNull(T... items)
Returns the first element from
items which is non-null, or null if all elements are null. |
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 of
GlyphVector 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 javax.script.ScriptEngine |
getJavaScriptEngine()
Returns JRE JavaScript Engine (Nashorn by default), if any.
|
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 java.util.List<java.lang.String> |
getMatches(java.util.regex.Matcher m)
Returns a list of capture groups if
Matcher.matches() , or null . |
static java.lang.String |
getPositionListString(java.util.List<java.lang.Integer> positionList)
Returns a human readable representation of a list of positions.
|
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 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 boolean |
isLocalUrl(java.lang.String url)
Determines if the given URL denotes a file on a local filesystem.
|
static boolean |
isStripEmpty(java.lang.String str)
Determines if the given String would be empty if stripped.
|
private static boolean |
isStrippedChar(char c,
char... skipChars) |
static boolean |
isValidUrl(java.lang.String url)
Determines if the given URL is valid.
|
static java.lang.String |
join(java.lang.String sep,
java.util.Collection<?> values)
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.
|
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 collection
elements is larger than maxElements elements,
the collection is shortened and the overflowIndicator 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)
Return the modulus in the range [0, n)
|
static java.util.concurrent.Executor |
newDirectExecutor()
Returns an executor which executes commands in the calling thread
|
static java.util.concurrent.ForkJoinPool |
newForkJoinPool(java.lang.String pref,
java.lang.String nameFormat,
int threadPriority)
Returns a
ForkJoinPool with the parallelism given by the preference key. |
static javax.xml.parsers.DocumentBuilder |
newSafeDOMBuilder()
Returns a new secure DOM builder, supporting XML namespaces.
|
static javax.xml.parsers.SAXParser |
newSafeSAXParser()
Returns a new secure SAX parser, supporting XML namespaces.
|
static java.util.concurrent.ThreadFactory |
newThreadFactory(java.lang.String nameFormat,
int threadPriority)
Creates a new
ThreadFactory which creates threads with names according to nameFormat . |
static java.io.InputStream |
openStream(java.net.URL url)
Convenient method to open an URL stream, using JOSM HTTP client if neeeded.
|
static org.w3c.dom.Document |
parseSafeDOM(java.io.InputStream is)
Parse the content given
InputStream as XML. |
static void |
parseSafeSAX(org.xml.sax.InputSource is,
org.xml.sax.helpers.DefaultHandler dh)
Parse the content given
InputSource as XML using the specified DefaultHandler . |
static byte[] |
readBytesFromStream(java.io.InputStream stream)
Reads the input stream and closes the stream at the end of processing (regardless if an exception was thrown)
|
static java.lang.String |
restrictStringLines(java.lang.String s,
int maxLines)
If the string
s is longer than maxLines lines, the string is cut and a "..." line is appended. |
static void |
setObjectsAccessible(java.lang.reflect.AccessibleObject... objects)
Sets
AccessibleObject (s) accessible. |
static java.lang.String |
shortenString(java.lang.String s,
int maxLength)
If the string
s is longer than maxLength , the string is cut and "..." is appended. |
static java.lang.String |
strip(java.lang.String str)
An alternative to
String.trim() to effectively remove all leading
and trailing white characters, including Unicode ones. |
private static java.lang.String |
strip(java.lang.String str,
char... skipChars) |
static java.lang.String |
strip(java.lang.String str,
java.lang.String skipChars)
An alternative to
String.trim() to effectively remove all leading
and trailing white characters, including Unicode ones. |
private static boolean |
stripChar(char[] strip,
char c) |
private static char[] |
stripChars(java.lang.String skipChars) |
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 java.lang.String |
toString(java.awt.Color c)
convert Color to String
(Color.toString() omits alpha value)
|
static <A,B> java.util.Collection<B> |
transform(java.util.Collection<? extends A> c,
java.util.function.Function<A,B> f)
Transforms the collection
c into an unmodifiable collection and
applies the Function 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 list
l into an unmodifiable list and
applies the Function f on each element upon access. |
static java.lang.String |
updateSystemProperty(java.lang.String key,
java.lang.String value)
Updates a given system property.
|
public static final java.util.regex.Pattern WHITE_SPACES_PATTERN
private static final long MILLIS_OF_SECOND
private static final long MILLIS_OF_MINUTE
private static final long MILLIS_OF_HOUR
private static final long MILLIS_OF_DAY
public static final java.lang.String URL_CHARS
private static final char[] DEFAULT_STRIP
private static final java.lang.String[] SIZE_UNITS
private static final double TO_DEGREES
private static final double TO_RADIANS
private static final double EPSILON
private static final char[] HEX_ARRAY
private Utils()
public static <T> boolean exists(java.lang.Iterable<T> collection, java.lang.Class<? extends T> clazz)
T
- The collection type.collection
- The collectionclazz
- The class to search for.true
if that item exists in the collection.public static <T> T find(java.lang.Iterable<? extends T> collection, java.util.function.Predicate<? super T> predicate)
T
- The iterable type.collection
- The iterable to search in.predicate
- The predicate to matchnull
if there was not match.public static <T> T find(java.lang.Iterable<? extends java.lang.Object> collection, java.lang.Class<? extends T> clazz)
T
- The iterable type.collection
- The iterable to search in.clazz
- The class to search for.null
if there was not match.@SafeVarargs public static <T> T firstNonNull(T... items)
items
which is non-null, or null if all elements are null.T
- type of itemsitems
- the items to look forpublic static <S,T extends S> SubclassFilteredCollection<S,T> filteredCollection(java.util.Collection<S> collection, java.lang.Class<T> clazz)
S
- Super type of itemsT
- type of itemscollection
- the collectionclazz
- the (sub)classpublic static <T> int indexOf(java.lang.Iterable<? extends T> collection, java.util.function.Predicate<? super T> predicate)
T
- The iterable typecollection
- The iterable to iterate over.predicate
- The predicate to search for.public static void ensure(boolean condition, java.lang.String message, java.lang.Object... data)
condition
- the condition to be metmessage
- Formatted error message to raise if condition is not metdata
- Message parameters, optionaljava.lang.AssertionError
- if the condition is not metpublic static int mod(int a, int n)
a
- dividendn
- divisorpublic static java.lang.String join(java.lang.String sep, java.util.Collection<?> values)
sep
- the separatorvalues
- collection of objects, null is converted to the
empty stringpublic static java.lang.String joinAsHtmlUnorderedList(java.lang.Iterable<?> values)
values
- The iterable collectionpublic static java.lang.String toString(java.awt.Color c)
c
- the colorpublic static java.lang.Integer colorFloat2int(java.lang.Float val)
val
- float value between 0 and 1public static java.lang.Float colorInt2float(java.lang.Integer val)
val
- integer valuepublic static java.awt.Color alphaMultiply(java.awt.Color color, float alphaFactor)
color
- The coloralphaFactor
- The factor to multiply alpha with.public static java.awt.Color complement(java.awt.Color clr)
clr
.clr
- the color to complementclr
public static <T> T[] copyArray(T[] array)
Arrays.copyOf(T[], int)
, this method is null-safe.T
- type of itemsarray
- The array to copynull
if array
is nullpublic static char[] copyArray(char... array)
Arrays.copyOf(T[], int)
, this method is null-safe.array
- The array to copynull
if array
is nullpublic static int[] copyArray(int... array)
Arrays.copyOf(T[], int)
, this method is null-safe.array
- The array to copynull
if array
is nullpublic static byte[] copyArray(byte... array)
Arrays.copyOf(T[], int)
, this method is null-safe.array
- The array to copynull
if array
is nullpublic static java.nio.file.Path copyFile(java.io.File in, java.io.File out) throws java.io.IOException
in
- The source fileout
- The destination filejava.io.IOException
- if any I/O error occursjava.lang.IllegalArgumentException
- if in
or out
is null
public static void copyDirectory(java.io.File in, java.io.File out) throws java.io.IOException
in
- The source directoryout
- The destination directoryjava.io.IOException
- if any I/O error ooccursjava.lang.IllegalArgumentException
- if in
or out
is null
public static boolean deleteDirectory(java.io.File path)
path
- The directory to deletetrue
if and only if the file or directory is
successfully deleted; false
otherwisepublic static boolean deleteFileIfExists(java.io.File file)
file
- file to deletetrue
if and only if the file does not exist or is successfully deleted; false
otherwisepublic static boolean deleteFile(java.io.File file)
file
- file to deletetrue
if and only if the file is successfully deleted; false
otherwisepublic static boolean deleteFile(java.io.File file, java.lang.String warnMsg)
file
- file to deletewarnMsg
- warning message. It will be translated with tr()
and must contain a single parameter {0}
for the file pathtrue
if and only if the file is successfully deleted; false
otherwisepublic static boolean mkDirs(java.io.File dir)
dir
- directory to createtrue
if and only if the directory is successfully created; false
otherwisepublic static boolean mkDirs(java.io.File dir, java.lang.String warnMsg)
dir
- directory to createwarnMsg
- warning message. It will be translated with tr()
and must contain a single parameter {0}
for the directory pathtrue
if and only if the directory is successfully created; false
otherwisepublic static void close(java.io.Closeable c)
Utility method for closing a Closeable
object.
c
- the closeable object. May be null.public static void close(java.util.zip.ZipFile zip)
Utility method for closing a ZipFile
.
zip
- the zip file. May be null.public static java.net.URL fileToURL(java.io.File f)
f
- The file to get URL fromnull
if not possible.public static boolean equalsEpsilon(double a, double b)
a
- The first double value to compareb
- The second double value to comparetrue
if abs(a - b) <= 1e-11
, false
otherwisepublic static java.lang.String md5Hex(java.lang.String data)
data
- arbitrary Stringpublic static java.lang.String toHexString(byte[] bytes)
bytes
- the byte arraypublic static <T> java.util.List<T> topologicalSort(MultiMap<T,T> dependencies)
T
- type of itemsdependencies
- 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.public static java.lang.String escapeReservedCharactersHTML(java.lang.String s)
s
- The unescaped stringpublic static <A,B> java.util.Collection<B> transform(java.util.Collection<? extends A> c, java.util.function.Function<A,B> f)
c
into an unmodifiable collection and
applies the Function
f
on each element upon access.A
- class of input collectionB
- class of transformed collectionc
- a collectionf
- a function that transforms objects of A
to objects of B
public static <A,B> java.util.List<B> transform(java.util.List<? extends A> l, java.util.function.Function<A,B> f)
l
into an unmodifiable list and
applies the Function
f
on each element upon access.A
- class of input collectionB
- class of transformed collectionl
- a collectionf
- a function that transforms objects of A
to objects of B
public static boolean isStripEmpty(java.lang.String str)
strip(s).isEmpty()
that avoids to create useless String object.str
- The string to testtrue
if the stripped version of s
would be empty.public static java.lang.String strip(java.lang.String str)
String.trim()
to effectively remove all leading
and trailing white characters, including Unicode ones.str
- The string to stripstr
, without leading and trailing characters, according to
Character.isWhitespace(char)
and Character.isSpaceChar(char)
.public static java.lang.String strip(java.lang.String str, java.lang.String skipChars)
String.trim()
to effectively remove all leading
and trailing white characters, including Unicode ones.str
- The string to stripskipChars
- additional characters to skipstr
, without leading and trailing characters, according to
Character.isWhitespace(char)
, Character.isSpaceChar(char)
and skipChars.private static java.lang.String strip(java.lang.String str, char... skipChars)
private static boolean isStrippedChar(char c, char... skipChars)
private static char[] stripChars(java.lang.String skipChars)
private static boolean stripChar(char[] strip, char c)
public static java.lang.String execOutput(java.util.List<java.lang.String> command) throws java.io.IOException, java.util.concurrent.ExecutionException, java.lang.InterruptedException
command
- the command with argumentsjava.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 waitingpublic 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
command
- the command with argumentstimeout
- the maximum time to waitunit
- the time unit of the timeout
argument. Must not be nulljava.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 waitingpublic static java.io.File getJosmTempDir()
<java.io.tmpdir>/JOSM
), or null
if java.io.tmpdir
is not definedpublic static java.lang.String getDurationString(long elapsedTime)
elapsedTime
- The duration in millisecondsjava.lang.IllegalArgumentException
- if elapsedTime is < 0public static java.lang.String getSizeString(long bytes, java.util.Locale locale)
bytes
- the number of byteslocale
- the locale used for formattingpublic static java.lang.String getPositionListString(java.util.List<java.lang.Integer> positionList)
For instance, [1,5,2,6,7
yields "1-2,5-7
positionList
- a list of positionspublic static java.util.List<java.lang.String> getMatches(java.util.regex.Matcher m)
Matcher.matches()
, or null
.
The first element (index 0) is the complete match.
Further elements correspond to the parts in parentheses of the regular expression.m
- the matcherMatcher.matches()
, or null
.public static <T> T cast(java.lang.Object o, java.lang.Class<T> klass)
T
- the target typeo
- the object to castklass
- the target class (same as T)o
is null or the type o
is not
a subclass of klass
. The casted value otherwise.public static java.lang.Throwable getRootCause(java.lang.Throwable t)
t
- The object to get root cause fort
public static <T> T[] addInArrayCopy(T[] array, T item)
T
- type of itemsarray
- The source arrayitem
- The item to addarray
containing item
as additional last elementpublic static java.lang.String shortenString(java.lang.String s, int maxLength)
s
is longer than maxLength
, the string is cut and "..." is appended.s
- String to shortenmaxLength
- maximum number of characters to keep (not including the "...")public static java.lang.String restrictStringLines(java.lang.String s, int maxLines)
s
is longer than maxLines
lines, the string is cut and a "..." line is appended.s
- String to shortenmaxLines
- maximum number of lines to keep (including including the "..." line)public static <T> java.util.Collection<T> limit(java.util.Collection<T> elements, int maxElements, T overflowIndicator)
elements
is larger than maxElements
elements,
the collection is shortened and the overflowIndicator
is appended.T
- type of elementselements
- collection to shortenmaxElements
- maximum number of elements to keep (including including the overflowIndicator
)overflowIndicator
- the element used to indicate that the collection has been shortenedpublic static java.lang.String fixURLQuery(java.lang.String url)
url
- the URL that should be fixedpublic static java.lang.String encodeUrl(java.lang.String s)
application/x-www-form-urlencoded
format. This method uses UTF-8 encoding scheme to obtain the bytes for unsafe
characters.s
- String
to be translated.String
.decodeUrl(String)
public static java.lang.String decodeUrl(java.lang.String s)
application/x-www-form-urlencoded
string.
UTF-8 encoding is used to determine
what characters are represented by any consecutive sequences of the
form "%xy
".s
- the String
to decodeString
encodeUrl(String)
public static boolean isLocalUrl(java.lang.String url)
url
- The URL to testtrue
if the url points to a local filepublic static boolean isValidUrl(java.lang.String url)
url
- The URL to testtrue
if the url is validpublic static java.util.concurrent.ThreadFactory newThreadFactory(java.lang.String nameFormat, int threadPriority)
ThreadFactory
which creates threads with names according to nameFormat
.nameFormat
- a String.format(String, Object...)
compatible name format; its first argument is a unique thread indexthreadPriority
- the priority of the created threads, see Thread.setPriority(int)
ThreadFactory
public static java.util.concurrent.ForkJoinPool newForkJoinPool(java.lang.String pref, java.lang.String nameFormat, int threadPriority)
ForkJoinPool
with the parallelism given by the preference key.pref
- The preference key to determine parallelismnameFormat
- see newThreadFactory(String, int)
threadPriority
- see newThreadFactory(String, int)
ForkJoinPool
public static java.util.concurrent.Executor newDirectExecutor()
public static java.lang.String updateSystemProperty(java.lang.String key, java.lang.String value)
key
- The property keyvalue
- The property valuenull
if it did not have one.public static javax.xml.parsers.DocumentBuilder newSafeDOMBuilder() throws javax.xml.parsers.ParserConfigurationException
javax.xml.parsers.ParserConfigurationException
- if a parser cannot be created which satisfies the requested configuration.public static org.w3c.dom.Document parseSafeDOM(java.io.InputStream is) throws javax.xml.parsers.ParserConfigurationException, java.io.IOException, org.xml.sax.SAXException
InputStream
as XML.
This method uses a secure DOM builder, supporting XML namespaces.is
- The InputStream containing the content to be parsed.javax.xml.parsers.ParserConfigurationException
- if a parser cannot be created which satisfies the requested configuration.java.io.IOException
- if any IO errors occur.org.xml.sax.SAXException
- for SAX errors.public static javax.xml.parsers.SAXParser newSafeSAXParser() throws javax.xml.parsers.ParserConfigurationException, org.xml.sax.SAXException
javax.xml.parsers.ParserConfigurationException
- if a parser cannot be created which satisfies the requested configuration.org.xml.sax.SAXException
- for SAX errors.public static void parseSafeSAX(org.xml.sax.InputSource is, org.xml.sax.helpers.DefaultHandler dh) throws javax.xml.parsers.ParserConfigurationException, org.xml.sax.SAXException, java.io.IOException
InputSource
as XML using the specified DefaultHandler
.
This method uses a secure SAX parser, supporting XML namespaces.is
- The InputSource containing the content to be parsed.dh
- The SAX DefaultHandler to use.javax.xml.parsers.ParserConfigurationException
- if a parser cannot be created which satisfies the requested configuration.org.xml.sax.SAXException
- for SAX errors.java.io.IOException
- if any IO errors occur.public static boolean hasExtension(java.lang.String filename, java.lang.String... extensions)
filename
- The file nameextensions
- The list of extensions to look for (without dot)true
if the filename has one of the given extensionspublic static boolean hasExtension(java.io.File file, java.lang.String... extensions)
file
- The fileextensions
- The list of extensions to look for (without dot)true
if the file's name has one of the given extensionspublic static byte[] readBytesFromStream(java.io.InputStream stream) throws java.io.IOException
stream
- input streamjava.io.IOException
- if any I/O error occurspublic static int hashMapInitialCapacity(int nEntries, double loadFactor)
nEntries
- the number of entries expectedloadFactor
- the load factorpublic static int hashMapInitialCapacity(int nEntries)
nEntries
- the number of entries expectedpublic static java.util.List<java.awt.font.GlyphVector> getGlyphVectorsBidi(java.lang.String string, java.awt.Font font, java.awt.font.FontRenderContext frc)
GlyphVector
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).string
- the string to renderfont
- the fontfrc
- a FontRenderContext objectpublic static void setObjectsAccessible(java.lang.reflect.AccessibleObject... objects)
AccessibleObject
(s) accessible.objects
- objectsAccessibleObject.setAccessible(java.lang.reflect.AccessibleObject[], boolean)
public static double clamp(double val, double min, double max)
val
- The valuemin
- minimum valuemax
- maximum valuejava.lang.IllegalArgumentException
- if min > max
public static int clamp(int val, int min, int max)
val
- The valuemin
- minimum valuemax
- maximum valuejava.lang.IllegalArgumentException
- if min > max
public static double toDegrees(double angleRad)
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.angleRad
- an angle in radianspublic static double toRadians(double angleDeg)
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.angleDeg
- an angle in degreespublic static int getJavaVersion()
public static int getJavaUpdate()
public static int getJavaBuild()
public static java.util.Date getJavaExpirationDate()
public static java.lang.String getJavaLatestVersion()
public static <T,U> java.util.function.Function<T,java.util.stream.Stream<U>> castToStream(java.lang.Class<U> klass)
T
- type of the objects to convertU
- type of the elements in the resulting streamklass
- the class Upublic static <T> void instanceOfThen(java.lang.Object o, java.lang.Class<T> klass, java.util.function.Consumer<? super T> consumer)
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.T
- the type for the instanceof check and casto
- the object to check and castklass
- the class Tconsumer
- action to take when o is and instance of Tpublic static <T> java.util.Optional<T> instanceOfAndCast(java.lang.Object o, java.lang.Class<T> klass)
instanceof
-check and cast" pattern.T
- the type for the instanceof check and casto
- the object to check and castklass
- the class TOptional
containing the result of the cast, if it is possible, an empty
Optional otherwisepublic static javax.script.ScriptEngine getJavaScriptEngine()
public static java.io.InputStream openStream(java.net.URL url) throws java.io.IOException
url
- URL for reading fromjava.io.IOException
- if any I/O error occurs