Class 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.
    • 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 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 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 deAccent​(java.lang.String str)
      Removes diacritics (accents) from string.
      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 (&lt;, &gt; and &amp;);
      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 from items 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 of GlyphVectors.
      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)
      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.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 string
      static 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 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)
      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 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 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 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 string s is longer than maxLines lines, the string is cut and a "..." line is appended.
      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.
      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.
      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 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.Double unitToMeter​(java.lang.String s)
      Convert a length unit to meters
      private static double unitToMeterConversion​(java.lang.String unit)
      Get the conversion factor for a specified unit to meters
      static 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.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Constructor Detail

    • Method Detail

      • firstNonNull

        @SafeVarargs
        public static <T> T firstNonNull​(T... items)
        Returns the first element from items 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 items
        T - type of items
        Parameters:
        collection - the collection
        clazz - 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 met
        message - Formatted error message to raise if condition is not met
        data - 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 dividend
        n - 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. Unlike Arrays.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 if array is null
        Since:
        6221
      • copyArray

        public static char[] copyArray​(char... array)
        Copies the given array. Unlike Arrays.copyOf(T[], int), this method is null-safe.
        Parameters:
        array - The array to copy
        Returns:
        A copy of the original array, or null if array is null
        Since:
        6222
      • copyArray

        public static int[] copyArray​(int... array)
        Copies the given array. Unlike Arrays.copyOf(T[], int), this method is null-safe.
        Parameters:
        array - The array to copy
        Returns:
        A copy of the original array, or null if array is null
        Since:
        7436
      • copyArray

        public static byte[] copyArray​(byte... array)
        Copies the given array. Unlike Arrays.copyOf(T[], int), this method is null-safe.
        Parameters:
        array - The array to copy
        Returns:
        A copy of the original array, or null if array 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 file
        out - The destination file
        Returns:
        the path to the target file
        Throws:
        java.io.IOException - if any I/O error occurs
        java.lang.IllegalArgumentException - if in or out is null
        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 directory
        out - The destination directory
        Throws:
        java.io.IOException - if any I/O error occurs
        java.lang.IllegalArgumentException - if in or out is null
        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 delete
        warnMsg - warning message. It will be translated with tr() 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 create
        warnMsg - warning message. It will be translated with tr() 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 URI
        java.net.MalformedURLException - if no protocol is specified, or an unknown protocol is found, or spec is null.
        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 compare
        b - The second double value to compare
        Returns:
        true if abs(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 (&lt;, &gt; and &amp;);
        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 collection c into an unmodifiable collection and applies the Function f on each element upon access.
        Type Parameters:
        A - class of input collection
        B - class of transformed collection
        Parameters:
        c - a collection
        f - a function that transforms objects of A to objects of B
        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 list l into an unmodifiable list and applies the Function f on each element upon access.
        Type Parameters:
        A - class of input collection
        B - class of transformed collection
        Parameters:
        l - a collection
        f - a function that transforms objects of A to objects of B
        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 of Collections.emptySet() and Collections.singleton(T) and Arrays.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 of Collections.emptyMap() and Collections.singletonMap(K, V) and Map#ofEntries to save memory.
        Type Parameters:
        K - the type of keys maintained by this map
        V - 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 stripped
        candidates - 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 to strip(s).isEmpty() that avoids to create useless String object.
        Parameters:
        str - The string to test
        Returns:
        true if the stripped version of s would be empty.
        Since:
        11435
      • strip

        public 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.
        Parameters:
        str - The string to strip
        Returns:
        str, without leading and trailing characters, according to Character.isWhitespace(char) and Character.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 to String.trim() to effectively remove all leading and trailing white characters, including Unicode ones.
        Parameters:
        str - The string to strip
        skipChars - additional characters to skip
        Returns:
        str, without leading and trailing characters, according to Character.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 string
        whitespaces - The regex for whitespaces to remove outside the leading and trailing whitespaces (see strip(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 exist
        java.util.concurrent.ExecutionException - when the return code is != 0. The output is can be retrieved in the exception message
        java.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 arguments
        timeout - the maximum time to wait
        unit - the time unit of the timeout argument. Must not be null
        Returns:
        the output
        Throws:
        java.io.IOException - when there was an error, e.g. command does not exist
        java.util.concurrent.ExecutionException - when the return code is != 0. The output is can be retrieved in the exception message
        java.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), or null if java.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 bytes
        locale - 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 if 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.
        Parameters:
        m - the matcher
        Returns:
        a list of capture groups if Matcher.matches(), or null.
      • 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 cast
        klass - the target class (same as T)
        Returns:
        null if o is null or the type o is not a subclass of klass. 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 array
        item - The item to add
        Returns:
        An extended copy of array containing item as additional last element
        Since:
        6717
      • shortenString

        public 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.
        Parameters:
        s - String to shorten
        maxLength - 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 string s is longer than maxLines lines, the string is cut and a "..." line is appended.
        Parameters:
        s - String to shorten
        maxLines - 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 collection elements is larger than maxElements elements, the collection is shortened and the overflowIndicator is appended.
        Type Parameters:
        T - type of elements
        Parameters:
        elements - collection to shorten
        maxElements - maximum number of elements to keep (including the overflowIndicator)
        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 into application/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 a 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".
        Parameters:
        s - the String 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 new ThreadFactory which creates threads with names according to nameFormat.
        Parameters:
        nameFormat - a String.format(String, Object...) compatible name format; its first argument is a unique thread index
        threadPriority - the priority of the created threads, see Thread.setPriority(int)
        Returns:
        a new ThreadFactory
      • getLevenshteinDistance

        public static int getLevenshteinDistance​(java.lang.String s,
                                                 java.lang.String t)
        Parameters:
        s - First word
        t - 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 compare
        string2 - 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,
                                                  double mean)
        Calculates the standard deviation of population with the given mean value.
        Parameters:
        values - an array of values
        mean - 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 a ForkJoinPool with the parallelism given by the preference key.
        Parameters:
        pref - The preference key to determine parallelism
        nameFormat - see newThreadFactory(String, int)
        threadPriority - see newThreadFactory(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 key
        value - 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 name
        extensions - 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 file
        extensions - 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 expected
        loadFactor - 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 of GlyphVectors. 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 render
        font - the font
        frc - 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 value
        min - minimum value
        max - maximum value
        Returns:
        the value
        Throws:
        java.lang.IllegalArgumentException - if min > 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 value
        min - minimum value
        max - maximum value
        Returns:
        the value
        Throws:
        java.lang.IllegalArgumentException - if min > 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 convert
        U - 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 cast
        klass - the class T
        consumer - 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 cast
        klass - 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 test
        defaultUrl - 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 which ClassLoader.getResourceAsStream(java.lang.String) will be called
        path - name of the desired resource
        Returns:
        A InputStream object or null 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 which ClassLoader.getResourceAsStream(java.lang.String) will be called
        path - name of the desired resource
        Returns:
        A InputStream object or null 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