001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.tools; 003 004import static org.openstreetmap.josm.tools.I18n.marktr; 005import static org.openstreetmap.josm.tools.I18n.tr; 006import static org.openstreetmap.josm.tools.I18n.trn; 007 008import java.awt.Color; 009import java.awt.Font; 010import java.awt.font.FontRenderContext; 011import java.awt.font.GlyphVector; 012import java.io.ByteArrayOutputStream; 013import java.io.Closeable; 014import java.io.File; 015import java.io.FileNotFoundException; 016import java.io.IOException; 017import java.io.InputStream; 018import java.io.UnsupportedEncodingException; 019import java.lang.reflect.AccessibleObject; 020import java.net.MalformedURLException; 021import java.net.URL; 022import java.net.URLDecoder; 023import java.net.URLEncoder; 024import java.nio.charset.StandardCharsets; 025import java.nio.file.Files; 026import java.nio.file.Path; 027import java.nio.file.Paths; 028import java.nio.file.StandardCopyOption; 029import java.nio.file.attribute.BasicFileAttributes; 030import java.nio.file.attribute.FileTime; 031import java.security.AccessController; 032import java.security.MessageDigest; 033import java.security.NoSuchAlgorithmException; 034import java.security.PrivilegedAction; 035import java.text.Bidi; 036import java.text.DateFormat; 037import java.text.MessageFormat; 038import java.text.ParseException; 039import java.util.AbstractCollection; 040import java.util.AbstractList; 041import java.util.ArrayList; 042import java.util.Arrays; 043import java.util.Collection; 044import java.util.Collections; 045import java.util.Date; 046import java.util.Iterator; 047import java.util.List; 048import java.util.Locale; 049import java.util.Optional; 050import java.util.concurrent.ExecutionException; 051import java.util.concurrent.Executor; 052import java.util.concurrent.ForkJoinPool; 053import java.util.concurrent.ForkJoinWorkerThread; 054import java.util.concurrent.ThreadFactory; 055import java.util.concurrent.TimeUnit; 056import java.util.concurrent.atomic.AtomicLong; 057import java.util.function.Consumer; 058import java.util.function.Function; 059import java.util.function.Predicate; 060import java.util.regex.Matcher; 061import java.util.regex.Pattern; 062import java.util.stream.Stream; 063import java.util.zip.ZipFile; 064 065import javax.script.ScriptEngine; 066import javax.script.ScriptEngineManager; 067import javax.xml.XMLConstants; 068import javax.xml.parsers.DocumentBuilder; 069import javax.xml.parsers.DocumentBuilderFactory; 070import javax.xml.parsers.ParserConfigurationException; 071import javax.xml.parsers.SAXParser; 072import javax.xml.parsers.SAXParserFactory; 073 074import org.openstreetmap.josm.spi.preferences.Config; 075import org.w3c.dom.Document; 076import org.xml.sax.InputSource; 077import org.xml.sax.SAXException; 078import org.xml.sax.helpers.DefaultHandler; 079 080/** 081 * Basic utils, that can be useful in different parts of the program. 082 */ 083public final class Utils { 084 085 /** Pattern matching white spaces */ 086 public static final Pattern WHITE_SPACES_PATTERN = Pattern.compile("\\s+"); 087 088 private static final long MILLIS_OF_SECOND = TimeUnit.SECONDS.toMillis(1); 089 private static final long MILLIS_OF_MINUTE = TimeUnit.MINUTES.toMillis(1); 090 private static final long MILLIS_OF_HOUR = TimeUnit.HOURS.toMillis(1); 091 private static final long MILLIS_OF_DAY = TimeUnit.DAYS.toMillis(1); 092 093 /** 094 * A list of all characters allowed in URLs 095 */ 096 public static final String URL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=%"; 097 098 private static final char[] DEFAULT_STRIP = {'\u200B', '\uFEFF'}; 099 100 private static final String[] SIZE_UNITS = {"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}; 101 102 // Constants backported from Java 9, see https://bugs.openjdk.java.net/browse/JDK-4477961 103 private static final double TO_DEGREES = 180.0 / Math.PI; 104 private static final double TO_RADIANS = Math.PI / 180.0; 105 106 private Utils() { 107 // Hide default constructor for utils classes 108 } 109 110 /** 111 * Checks if an item that is an instance of clazz exists in the collection 112 * @param <T> The collection type. 113 * @param collection The collection 114 * @param clazz The class to search for. 115 * @return <code>true</code> if that item exists in the collection. 116 */ 117 public static <T> boolean exists(Iterable<T> collection, Class<? extends T> clazz) { 118 CheckParameterUtil.ensureParameterNotNull(clazz, "clazz"); 119 return StreamUtils.toStream(collection).anyMatch(clazz::isInstance); 120 } 121 122 /** 123 * Finds the first item in the iterable for which the predicate matches. 124 * @param <T> The iterable type. 125 * @param collection The iterable to search in. 126 * @param predicate The predicate to match 127 * @return the item or <code>null</code> if there was not match. 128 */ 129 public static <T> T find(Iterable<? extends T> collection, Predicate<? super T> predicate) { 130 for (T item : collection) { 131 if (predicate.test(item)) { 132 return item; 133 } 134 } 135 return null; 136 } 137 138 /** 139 * Finds the first item in the iterable which is of the given type. 140 * @param <T> The iterable type. 141 * @param collection The iterable to search in. 142 * @param clazz The class to search for. 143 * @return the item or <code>null</code> if there was not match. 144 */ 145 @SuppressWarnings("unchecked") 146 public static <T> T find(Iterable<? extends Object> collection, Class<? extends T> clazz) { 147 CheckParameterUtil.ensureParameterNotNull(clazz, "clazz"); 148 return (T) find(collection, clazz::isInstance); 149 } 150 151 /** 152 * Returns the first element from {@code items} which is non-null, or null if all elements are null. 153 * @param <T> type of items 154 * @param items the items to look for 155 * @return first non-null item if there is one 156 */ 157 @SafeVarargs 158 public static <T> T firstNonNull(T... items) { 159 for (T i : items) { 160 if (i != null) { 161 return i; 162 } 163 } 164 return null; 165 } 166 167 /** 168 * Filter a collection by (sub)class. 169 * This is an efficient read-only implementation. 170 * @param <S> Super type of items 171 * @param <T> type of items 172 * @param collection the collection 173 * @param clazz the (sub)class 174 * @return a read-only filtered collection 175 */ 176 public static <S, T extends S> SubclassFilteredCollection<S, T> filteredCollection(Collection<S> collection, final Class<T> clazz) { 177 CheckParameterUtil.ensureParameterNotNull(clazz, "clazz"); 178 return new SubclassFilteredCollection<>(collection, clazz::isInstance); 179 } 180 181 /** 182 * Find the index of the first item that matches the predicate. 183 * @param <T> The iterable type 184 * @param collection The iterable to iterate over. 185 * @param predicate The predicate to search for. 186 * @return The index of the first item or -1 if none was found. 187 */ 188 public static <T> int indexOf(Iterable<? extends T> collection, Predicate<? super T> predicate) { 189 int i = 0; 190 for (T item : collection) { 191 if (predicate.test(item)) 192 return i; 193 i++; 194 } 195 return -1; 196 } 197 198 /** 199 * Ensures a logical condition is met. Otherwise throws an assertion error. 200 * @param condition the condition to be met 201 * @param message Formatted error message to raise if condition is not met 202 * @param data Message parameters, optional 203 * @throws AssertionError if the condition is not met 204 */ 205 public static void ensure(boolean condition, String message, Object...data) { 206 if (!condition) 207 throw new AssertionError( 208 MessageFormat.format(message, data) 209 ); 210 } 211 212 /** 213 * Return the modulus in the range [0, n) 214 * @param a dividend 215 * @param n divisor 216 * @return modulo (remainder of the Euclidian division of a by n) 217 */ 218 public static int mod(int a, int n) { 219 if (n <= 0) 220 throw new IllegalArgumentException("n must be <= 0 but is "+n); 221 int res = a % n; 222 if (res < 0) { 223 res += n; 224 } 225 return res; 226 } 227 228 /** 229 * Joins a list of strings (or objects that can be converted to string via 230 * Object.toString()) into a single string with fields separated by sep. 231 * @param sep the separator 232 * @param values collection of objects, null is converted to the 233 * empty string 234 * @return null if values is null. The joined string otherwise. 235 */ 236 public static String join(String sep, Collection<?> values) { 237 CheckParameterUtil.ensureParameterNotNull(sep, "sep"); 238 if (values == null) 239 return null; 240 StringBuilder s = null; 241 for (Object a : values) { 242 if (a == null) { 243 a = ""; 244 } 245 if (s != null) { 246 s.append(sep).append(a); 247 } else { 248 s = new StringBuilder(a.toString()); 249 } 250 } 251 return s != null ? s.toString() : ""; 252 } 253 254 /** 255 * Converts the given iterable collection as an unordered HTML list. 256 * @param values The iterable collection 257 * @return An unordered HTML list 258 */ 259 public static String joinAsHtmlUnorderedList(Iterable<?> values) { 260 return StreamUtils.toStream(values).map(Object::toString).collect(StreamUtils.toHtmlList()); 261 } 262 263 /** 264 * convert Color to String 265 * (Color.toString() omits alpha value) 266 * @param c the color 267 * @return the String representation, including alpha 268 */ 269 public static String toString(Color c) { 270 if (c == null) 271 return "null"; 272 if (c.getAlpha() == 255) 273 return String.format("#%06x", c.getRGB() & 0x00ffffff); 274 else 275 return String.format("#%06x(alpha=%d)", c.getRGB() & 0x00ffffff, c.getAlpha()); 276 } 277 278 /** 279 * convert float range 0 <= x <= 1 to integer range 0..255 280 * when dealing with colors and color alpha value 281 * @param val float value between 0 and 1 282 * @return null if val is null, the corresponding int if val is in the 283 * range 0...1. If val is outside that range, return 255 284 */ 285 public static Integer colorFloat2int(Float val) { 286 if (val == null) 287 return null; 288 if (val < 0 || val > 1) 289 return 255; 290 return (int) (255f * val + 0.5f); 291 } 292 293 /** 294 * convert integer range 0..255 to float range 0 <= x <= 1 295 * when dealing with colors and color alpha value 296 * @param val integer value 297 * @return corresponding float value in range 0 <= x <= 1 298 */ 299 public static Float colorInt2float(Integer val) { 300 if (val == null) 301 return null; 302 if (val < 0 || val > 255) 303 return 1f; 304 return ((float) val) / 255f; 305 } 306 307 /** 308 * Multiply the alpha value of the given color with the factor. The alpha value is clamped to 0..255 309 * @param color The color 310 * @param alphaFactor The factor to multiply alpha with. 311 * @return The new color. 312 * @since 11692 313 */ 314 public static Color alphaMultiply(Color color, float alphaFactor) { 315 int alpha = Utils.colorFloat2int(Utils.colorInt2float(color.getAlpha()) * alphaFactor); 316 alpha = clamp(alpha, 0, 255); 317 return new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha); 318 } 319 320 /** 321 * Returns the complementary color of {@code clr}. 322 * @param clr the color to complement 323 * @return the complementary color of {@code clr} 324 */ 325 public static Color complement(Color clr) { 326 return new Color(255 - clr.getRed(), 255 - clr.getGreen(), 255 - clr.getBlue(), clr.getAlpha()); 327 } 328 329 /** 330 * Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe. 331 * @param <T> type of items 332 * @param array The array to copy 333 * @return A copy of the original array, or {@code null} if {@code array} is null 334 * @since 6221 335 */ 336 public static <T> T[] copyArray(T[] array) { 337 if (array != null) { 338 return Arrays.copyOf(array, array.length); 339 } 340 return array; 341 } 342 343 /** 344 * Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe. 345 * @param array The array to copy 346 * @return A copy of the original array, or {@code null} if {@code array} is null 347 * @since 6222 348 */ 349 public static char[] copyArray(char... array) { 350 if (array != null) { 351 return Arrays.copyOf(array, array.length); 352 } 353 return array; 354 } 355 356 /** 357 * Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe. 358 * @param array The array to copy 359 * @return A copy of the original array, or {@code null} if {@code array} is null 360 * @since 7436 361 */ 362 public static int[] copyArray(int... array) { 363 if (array != null) { 364 return Arrays.copyOf(array, array.length); 365 } 366 return array; 367 } 368 369 /** 370 * Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe. 371 * @param array The array to copy 372 * @return A copy of the original array, or {@code null} if {@code array} is null 373 * @since 11879 374 */ 375 public static byte[] copyArray(byte... array) { 376 if (array != null) { 377 return Arrays.copyOf(array, array.length); 378 } 379 return array; 380 } 381 382 /** 383 * Simple file copy function that will overwrite the target file. 384 * @param in The source file 385 * @param out The destination file 386 * @return the path to the target file 387 * @throws IOException if any I/O error occurs 388 * @throws IllegalArgumentException if {@code in} or {@code out} is {@code null} 389 * @since 7003 390 */ 391 public static Path copyFile(File in, File out) throws IOException { 392 CheckParameterUtil.ensureParameterNotNull(in, "in"); 393 CheckParameterUtil.ensureParameterNotNull(out, "out"); 394 return Files.copy(in.toPath(), out.toPath(), StandardCopyOption.REPLACE_EXISTING); 395 } 396 397 /** 398 * Recursive directory copy function 399 * @param in The source directory 400 * @param out The destination directory 401 * @throws IOException if any I/O error ooccurs 402 * @throws IllegalArgumentException if {@code in} or {@code out} is {@code null} 403 * @since 7835 404 */ 405 public static void copyDirectory(File in, File out) throws IOException { 406 CheckParameterUtil.ensureParameterNotNull(in, "in"); 407 CheckParameterUtil.ensureParameterNotNull(out, "out"); 408 if (!out.exists() && !out.mkdirs()) { 409 Logging.warn("Unable to create directory "+out.getPath()); 410 } 411 File[] files = in.listFiles(); 412 if (files != null) { 413 for (File f : files) { 414 File target = new File(out, f.getName()); 415 if (f.isDirectory()) { 416 copyDirectory(f, target); 417 } else { 418 copyFile(f, target); 419 } 420 } 421 } 422 } 423 424 /** 425 * Deletes a directory recursively. 426 * @param path The directory to delete 427 * @return <code>true</code> if and only if the file or directory is 428 * successfully deleted; <code>false</code> otherwise 429 */ 430 public static boolean deleteDirectory(File path) { 431 if (path.exists()) { 432 File[] files = path.listFiles(); 433 if (files != null) { 434 for (File file : files) { 435 if (file.isDirectory()) { 436 deleteDirectory(file); 437 } else { 438 deleteFile(file); 439 } 440 } 441 } 442 } 443 return path.delete(); 444 } 445 446 /** 447 * Deletes a file and log a default warning if the file exists but the deletion fails. 448 * @param file file to delete 449 * @return {@code true} if and only if the file does not exist or is successfully deleted; {@code false} otherwise 450 * @since 10569 451 */ 452 public static boolean deleteFileIfExists(File file) { 453 if (file.exists()) { 454 return deleteFile(file); 455 } else { 456 return true; 457 } 458 } 459 460 /** 461 * Deletes a file and log a default warning if the deletion fails. 462 * @param file file to delete 463 * @return {@code true} if and only if the file is successfully deleted; {@code false} otherwise 464 * @since 9296 465 */ 466 public static boolean deleteFile(File file) { 467 return deleteFile(file, marktr("Unable to delete file {0}")); 468 } 469 470 /** 471 * Deletes a file and log a configurable warning if the deletion fails. 472 * @param file file to delete 473 * @param warnMsg warning message. It will be translated with {@code tr()} 474 * and must contain a single parameter <code>{0}</code> for the file path 475 * @return {@code true} if and only if the file is successfully deleted; {@code false} otherwise 476 * @since 9296 477 */ 478 public static boolean deleteFile(File file, String warnMsg) { 479 boolean result = file.delete(); 480 if (!result) { 481 Logging.warn(tr(warnMsg, file.getPath())); 482 } 483 return result; 484 } 485 486 /** 487 * Creates a directory and log a default warning if the creation fails. 488 * @param dir directory to create 489 * @return {@code true} if and only if the directory is successfully created; {@code false} otherwise 490 * @since 9645 491 */ 492 public static boolean mkDirs(File dir) { 493 return mkDirs(dir, marktr("Unable to create directory {0}")); 494 } 495 496 /** 497 * Creates a directory and log a configurable warning if the creation fails. 498 * @param dir directory to create 499 * @param warnMsg warning message. It will be translated with {@code tr()} 500 * and must contain a single parameter <code>{0}</code> for the directory path 501 * @return {@code true} if and only if the directory is successfully created; {@code false} otherwise 502 * @since 9645 503 */ 504 public static boolean mkDirs(File dir, String warnMsg) { 505 boolean result = dir.mkdirs(); 506 if (!result) { 507 Logging.warn(tr(warnMsg, dir.getPath())); 508 } 509 return result; 510 } 511 512 /** 513 * <p>Utility method for closing a {@link java.io.Closeable} object.</p> 514 * 515 * @param c the closeable object. May be null. 516 */ 517 public static void close(Closeable c) { 518 if (c == null) return; 519 try { 520 c.close(); 521 } catch (IOException e) { 522 Logging.warn(e); 523 } 524 } 525 526 /** 527 * <p>Utility method for closing a {@link java.util.zip.ZipFile}.</p> 528 * 529 * @param zip the zip file. May be null. 530 */ 531 public static void close(ZipFile zip) { 532 close((Closeable) zip); 533 } 534 535 /** 536 * Converts the given file to its URL. 537 * @param f The file to get URL from 538 * @return The URL of the given file, or {@code null} if not possible. 539 * @since 6615 540 */ 541 public static URL fileToURL(File f) { 542 if (f != null) { 543 try { 544 return f.toURI().toURL(); 545 } catch (MalformedURLException ex) { 546 Logging.error("Unable to convert filename " + f.getAbsolutePath() + " to URL"); 547 } 548 } 549 return null; 550 } 551 552 private static final double EPSILON = 1e-11; 553 554 /** 555 * Determines if the two given double values are equal (their delta being smaller than a fixed epsilon) 556 * @param a The first double value to compare 557 * @param b The second double value to compare 558 * @return {@code true} if {@code abs(a - b) <= 1e-11}, {@code false} otherwise 559 */ 560 public static boolean equalsEpsilon(double a, double b) { 561 return Math.abs(a - b) <= EPSILON; 562 } 563 564 /** 565 * Calculate MD5 hash of a string and output in hexadecimal format. 566 * @param data arbitrary String 567 * @return MD5 hash of data, string of length 32 with characters in range [0-9a-f] 568 */ 569 public static String md5Hex(String data) { 570 MessageDigest md = null; 571 try { 572 md = MessageDigest.getInstance("MD5"); 573 } catch (NoSuchAlgorithmException e) { 574 throw new JosmRuntimeException(e); 575 } 576 byte[] byteData = data.getBytes(StandardCharsets.UTF_8); 577 byte[] byteDigest = md.digest(byteData); 578 return toHexString(byteDigest); 579 } 580 581 private static final char[] HEX_ARRAY = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; 582 583 /** 584 * Converts a byte array to a string of hexadecimal characters. 585 * Preserves leading zeros, so the size of the output string is always twice 586 * the number of input bytes. 587 * @param bytes the byte array 588 * @return hexadecimal representation 589 */ 590 public static String toHexString(byte[] bytes) { 591 592 if (bytes == null) { 593 return ""; 594 } 595 596 final int len = bytes.length; 597 if (len == 0) { 598 return ""; 599 } 600 601 char[] hexChars = new char[len * 2]; 602 for (int i = 0, j = 0; i < len; i++) { 603 final int v = bytes[i]; 604 hexChars[j++] = HEX_ARRAY[(v & 0xf0) >> 4]; 605 hexChars[j++] = HEX_ARRAY[v & 0xf]; 606 } 607 return new String(hexChars); 608 } 609 610 /** 611 * Topological sort. 612 * @param <T> type of items 613 * 614 * @param dependencies contains mappings (key -> value). In the final list of sorted objects, the key will come 615 * after the value. (In other words, the key depends on the value(s).) 616 * There must not be cyclic dependencies. 617 * @return the list of sorted objects 618 */ 619 public static <T> List<T> topologicalSort(final MultiMap<T, T> dependencies) { 620 MultiMap<T, T> deps = new MultiMap<>(); 621 for (T key : dependencies.keySet()) { 622 deps.putVoid(key); 623 for (T val : dependencies.get(key)) { 624 deps.putVoid(val); 625 deps.put(key, val); 626 } 627 } 628 629 int size = deps.size(); 630 List<T> sorted = new ArrayList<>(); 631 for (int i = 0; i < size; ++i) { 632 T parentless = null; 633 for (T key : deps.keySet()) { 634 if (deps.get(key).isEmpty()) { 635 parentless = key; 636 break; 637 } 638 } 639 if (parentless == null) throw new JosmRuntimeException("parentless"); 640 sorted.add(parentless); 641 deps.remove(parentless); 642 for (T key : deps.keySet()) { 643 deps.remove(key, parentless); 644 } 645 } 646 if (sorted.size() != size) throw new JosmRuntimeException("Wrong size"); 647 return sorted; 648 } 649 650 /** 651 * Replaces some HTML reserved characters (<, > and &) by their equivalent entity (&lt;, &gt; and &amp;); 652 * @param s The unescaped string 653 * @return The escaped string 654 */ 655 public static String escapeReservedCharactersHTML(String s) { 656 return s == null ? "" : s.replace("&", "&").replace("<", "<").replace(">", ">"); 657 } 658 659 /** 660 * Transforms the collection {@code c} into an unmodifiable collection and 661 * applies the {@link Function} {@code f} on each element upon access. 662 * @param <A> class of input collection 663 * @param <B> class of transformed collection 664 * @param c a collection 665 * @param f a function that transforms objects of {@code A} to objects of {@code B} 666 * @return the transformed unmodifiable collection 667 */ 668 public static <A, B> Collection<B> transform(final Collection<? extends A> c, final Function<A, B> f) { 669 return new AbstractCollection<B>() { 670 671 @Override 672 public int size() { 673 return c.size(); 674 } 675 676 @Override 677 public Iterator<B> iterator() { 678 return new Iterator<B>() { 679 680 private final Iterator<? extends A> it = c.iterator(); 681 682 @Override 683 public boolean hasNext() { 684 return it.hasNext(); 685 } 686 687 @Override 688 public B next() { 689 return f.apply(it.next()); 690 } 691 692 @Override 693 public void remove() { 694 throw new UnsupportedOperationException(); 695 } 696 }; 697 } 698 }; 699 } 700 701 /** 702 * Transforms the list {@code l} into an unmodifiable list and 703 * applies the {@link Function} {@code f} on each element upon access. 704 * @param <A> class of input collection 705 * @param <B> class of transformed collection 706 * @param l a collection 707 * @param f a function that transforms objects of {@code A} to objects of {@code B} 708 * @return the transformed unmodifiable list 709 */ 710 public static <A, B> List<B> transform(final List<? extends A> l, final Function<A, B> f) { 711 return new AbstractList<B>() { 712 713 @Override 714 public int size() { 715 return l.size(); 716 } 717 718 @Override 719 public B get(int index) { 720 return f.apply(l.get(index)); 721 } 722 }; 723 } 724 725 /** 726 * Determines if the given String would be empty if stripped. 727 * This is an efficient alternative to {@code strip(s).isEmpty()} that avoids to create useless String object. 728 * @param str The string to test 729 * @return {@code true} if the stripped version of {@code s} would be empty. 730 * @since 11435 731 */ 732 public static boolean isStripEmpty(String str) { 733 if (str != null) { 734 for (int i = 0; i < str.length(); i++) { 735 if (!isStrippedChar(str.charAt(i), DEFAULT_STRIP)) { 736 return false; 737 } 738 } 739 } 740 return true; 741 } 742 743 /** 744 * An alternative to {@link String#trim()} to effectively remove all leading 745 * and trailing white characters, including Unicode ones. 746 * @param str The string to strip 747 * @return <code>str</code>, without leading and trailing characters, according to 748 * {@link Character#isWhitespace(char)} and {@link Character#isSpaceChar(char)}. 749 * @see <a href="http://closingbraces.net/2008/11/11/javastringtrim/">Java String.trim has a strange idea of whitespace</a> 750 * @see <a href="https://bugs.openjdk.java.net/browse/JDK-4080617">JDK bug 4080617</a> 751 * @see <a href="https://bugs.openjdk.java.net/browse/JDK-7190385">JDK bug 7190385</a> 752 * @since 5772 753 */ 754 public static String strip(final String str) { 755 if (str == null || str.isEmpty()) { 756 return str; 757 } 758 return strip(str, DEFAULT_STRIP); 759 } 760 761 /** 762 * An alternative to {@link String#trim()} to effectively remove all leading 763 * and trailing white characters, including Unicode ones. 764 * @param str The string to strip 765 * @param skipChars additional characters to skip 766 * @return <code>str</code>, without leading and trailing characters, according to 767 * {@link Character#isWhitespace(char)}, {@link Character#isSpaceChar(char)} and skipChars. 768 * @since 8435 769 */ 770 public static String strip(final String str, final String skipChars) { 771 if (str == null || str.isEmpty()) { 772 return str; 773 } 774 return strip(str, stripChars(skipChars)); 775 } 776 777 private static String strip(final String str, final char... skipChars) { 778 779 int start = 0; 780 int end = str.length(); 781 boolean leadingSkipChar = true; 782 while (leadingSkipChar && start < end) { 783 leadingSkipChar = isStrippedChar(str.charAt(start), skipChars); 784 if (leadingSkipChar) { 785 start++; 786 } 787 } 788 boolean trailingSkipChar = true; 789 while (trailingSkipChar && end > start + 1) { 790 trailingSkipChar = isStrippedChar(str.charAt(end - 1), skipChars); 791 if (trailingSkipChar) { 792 end--; 793 } 794 } 795 796 return str.substring(start, end); 797 } 798 799 private static boolean isStrippedChar(char c, final char... skipChars) { 800 return Character.isWhitespace(c) || Character.isSpaceChar(c) || stripChar(skipChars, c); 801 } 802 803 private static char[] stripChars(final String skipChars) { 804 if (skipChars == null || skipChars.isEmpty()) { 805 return DEFAULT_STRIP; 806 } 807 808 char[] chars = new char[DEFAULT_STRIP.length + skipChars.length()]; 809 System.arraycopy(DEFAULT_STRIP, 0, chars, 0, DEFAULT_STRIP.length); 810 skipChars.getChars(0, skipChars.length(), chars, DEFAULT_STRIP.length); 811 812 return chars; 813 } 814 815 private static boolean stripChar(final char[] strip, char c) { 816 for (char s : strip) { 817 if (c == s) { 818 return true; 819 } 820 } 821 return false; 822 } 823 824 /** 825 * Runs an external command and returns the standard output. 826 * 827 * The program is expected to execute fast, as this call waits 10 seconds at most. 828 * 829 * @param command the command with arguments 830 * @return the output 831 * @throws IOException when there was an error, e.g. command does not exist 832 * @throws ExecutionException when the return code is != 0. The output is can be retrieved in the exception message 833 * @throws InterruptedException if the current thread is {@linkplain Thread#interrupt() interrupted} by another thread while waiting 834 */ 835 public static String execOutput(List<String> command) throws IOException, ExecutionException, InterruptedException { 836 return execOutput(command, 10, TimeUnit.SECONDS); 837 } 838 839 /** 840 * Runs an external command and returns the standard output. Waits at most the specified time. 841 * 842 * @param command the command with arguments 843 * @param timeout the maximum time to wait 844 * @param unit the time unit of the {@code timeout} argument. Must not be null 845 * @return the output 846 * @throws IOException when there was an error, e.g. command does not exist 847 * @throws ExecutionException when the return code is != 0. The output is can be retrieved in the exception message 848 * @throws InterruptedException if the current thread is {@linkplain Thread#interrupt() interrupted} by another thread while waiting 849 * @since 13467 850 */ 851 public static String execOutput(List<String> command, long timeout, TimeUnit unit) 852 throws IOException, ExecutionException, InterruptedException { 853 if (Logging.isDebugEnabled()) { 854 Logging.debug(join(" ", command)); 855 } 856 Path out = Files.createTempFile("josm_exec_", ".txt"); 857 Process p = new ProcessBuilder(command).redirectErrorStream(true).redirectOutput(out.toFile()).start(); 858 if (!p.waitFor(timeout, unit) || p.exitValue() != 0) { 859 throw new ExecutionException(command.toString(), null); 860 } 861 String msg = String.join("\n", Files.readAllLines(out)).trim(); 862 try { 863 Files.delete(out); 864 } catch (IOException e) { 865 Logging.warn(e); 866 } 867 return msg; 868 } 869 870 /** 871 * Returns the JOSM temp directory. 872 * @return The JOSM temp directory ({@code <java.io.tmpdir>/JOSM}), or {@code null} if {@code java.io.tmpdir} is not defined 873 * @since 6245 874 */ 875 public static File getJosmTempDir() { 876 String tmpDir = System.getProperty("java.io.tmpdir"); 877 if (tmpDir == null) { 878 return null; 879 } 880 File josmTmpDir = new File(tmpDir, "JOSM"); 881 if (!josmTmpDir.exists() && !josmTmpDir.mkdirs()) { 882 Logging.warn("Unable to create temp directory " + josmTmpDir); 883 } 884 return josmTmpDir; 885 } 886 887 /** 888 * Returns a simple human readable (hours, minutes, seconds) string for a given duration in milliseconds. 889 * @param elapsedTime The duration in milliseconds 890 * @return A human readable string for the given duration 891 * @throws IllegalArgumentException if elapsedTime is < 0 892 * @since 6354 893 */ 894 public static String getDurationString(long elapsedTime) { 895 if (elapsedTime < 0) { 896 throw new IllegalArgumentException("elapsedTime must be >= 0"); 897 } 898 // Is it less than 1 second ? 899 if (elapsedTime < MILLIS_OF_SECOND) { 900 return String.format("%d %s", elapsedTime, tr("ms")); 901 } 902 // Is it less than 1 minute ? 903 if (elapsedTime < MILLIS_OF_MINUTE) { 904 return String.format("%.1f %s", elapsedTime / (double) MILLIS_OF_SECOND, tr("s")); 905 } 906 // Is it less than 1 hour ? 907 if (elapsedTime < MILLIS_OF_HOUR) { 908 final long min = elapsedTime / MILLIS_OF_MINUTE; 909 return String.format("%d %s %d %s", min, tr("min"), (elapsedTime - min * MILLIS_OF_MINUTE) / MILLIS_OF_SECOND, tr("s")); 910 } 911 // Is it less than 1 day ? 912 if (elapsedTime < MILLIS_OF_DAY) { 913 final long hour = elapsedTime / MILLIS_OF_HOUR; 914 return String.format("%d %s %d %s", hour, tr("h"), (elapsedTime - hour * MILLIS_OF_HOUR) / MILLIS_OF_MINUTE, tr("min")); 915 } 916 long days = elapsedTime / MILLIS_OF_DAY; 917 return String.format("%d %s %d %s", days, trn("day", "days", days), (elapsedTime - days * MILLIS_OF_DAY) / MILLIS_OF_HOUR, tr("h")); 918 } 919 920 /** 921 * Returns a human readable representation (B, kB, MB, ...) for the given number of byes. 922 * @param bytes the number of bytes 923 * @param locale the locale used for formatting 924 * @return a human readable representation 925 * @since 9274 926 */ 927 public static String getSizeString(long bytes, Locale locale) { 928 if (bytes < 0) { 929 throw new IllegalArgumentException("bytes must be >= 0"); 930 } 931 int unitIndex = 0; 932 double value = bytes; 933 while (value >= 1024 && unitIndex < SIZE_UNITS.length) { 934 value /= 1024; 935 unitIndex++; 936 } 937 if (value > 100 || unitIndex == 0) { 938 return String.format(locale, "%.0f %s", value, SIZE_UNITS[unitIndex]); 939 } else if (value > 10) { 940 return String.format(locale, "%.1f %s", value, SIZE_UNITS[unitIndex]); 941 } else { 942 return String.format(locale, "%.2f %s", value, SIZE_UNITS[unitIndex]); 943 } 944 } 945 946 /** 947 * Returns a human readable representation of a list of positions. 948 * <p> 949 * For instance, {@code [1,5,2,6,7} yields "1-2,5-7 950 * @param positionList a list of positions 951 * @return a human readable representation 952 */ 953 public static String getPositionListString(List<Integer> positionList) { 954 Collections.sort(positionList); 955 final StringBuilder sb = new StringBuilder(32); 956 sb.append(positionList.get(0)); 957 int cnt = 0; 958 int last = positionList.get(0); 959 for (int i = 1; i < positionList.size(); ++i) { 960 int cur = positionList.get(i); 961 if (cur == last + 1) { 962 ++cnt; 963 } else if (cnt == 0) { 964 sb.append(',').append(cur); 965 } else { 966 sb.append('-').append(last); 967 sb.append(',').append(cur); 968 cnt = 0; 969 } 970 last = cur; 971 } 972 if (cnt >= 1) { 973 sb.append('-').append(last); 974 } 975 return sb.toString(); 976 } 977 978 /** 979 * Returns a list of capture groups if {@link Matcher#matches()}, or {@code null}. 980 * The first element (index 0) is the complete match. 981 * Further elements correspond to the parts in parentheses of the regular expression. 982 * @param m the matcher 983 * @return a list of capture groups if {@link Matcher#matches()}, or {@code null}. 984 */ 985 public static List<String> getMatches(final Matcher m) { 986 if (m.matches()) { 987 List<String> result = new ArrayList<>(m.groupCount() + 1); 988 for (int i = 0; i <= m.groupCount(); i++) { 989 result.add(m.group(i)); 990 } 991 return result; 992 } else { 993 return null; 994 } 995 } 996 997 /** 998 * Cast an object savely. 999 * @param <T> the target type 1000 * @param o the object to cast 1001 * @param klass the target class (same as T) 1002 * @return null if <code>o</code> is null or the type <code>o</code> is not 1003 * a subclass of <code>klass</code>. The casted value otherwise. 1004 */ 1005 @SuppressWarnings("unchecked") 1006 public static <T> T cast(Object o, Class<T> klass) { 1007 if (klass.isInstance(o)) { 1008 return (T) o; 1009 } 1010 return null; 1011 } 1012 1013 /** 1014 * Returns the root cause of a throwable object. 1015 * @param t The object to get root cause for 1016 * @return the root cause of {@code t} 1017 * @since 6639 1018 */ 1019 public static Throwable getRootCause(Throwable t) { 1020 Throwable result = t; 1021 if (result != null) { 1022 Throwable cause = result.getCause(); 1023 while (cause != null && !cause.equals(result)) { 1024 result = cause; 1025 cause = result.getCause(); 1026 } 1027 } 1028 return result; 1029 } 1030 1031 /** 1032 * Adds the given item at the end of a new copy of given array. 1033 * @param <T> type of items 1034 * @param array The source array 1035 * @param item The item to add 1036 * @return An extended copy of {@code array} containing {@code item} as additional last element 1037 * @since 6717 1038 */ 1039 public static <T> T[] addInArrayCopy(T[] array, T item) { 1040 T[] biggerCopy = Arrays.copyOf(array, array.length + 1); 1041 biggerCopy[array.length] = item; 1042 return biggerCopy; 1043 } 1044 1045 /** 1046 * If the string {@code s} is longer than {@code maxLength}, the string is cut and "..." is appended. 1047 * @param s String to shorten 1048 * @param maxLength maximum number of characters to keep (not including the "...") 1049 * @return the shortened string 1050 */ 1051 public static String shortenString(String s, int maxLength) { 1052 if (s != null && s.length() > maxLength) { 1053 return s.substring(0, maxLength - 3) + "..."; 1054 } else { 1055 return s; 1056 } 1057 } 1058 1059 /** 1060 * If the string {@code s} is longer than {@code maxLines} lines, the string is cut and a "..." line is appended. 1061 * @param s String to shorten 1062 * @param maxLines maximum number of lines to keep (including including the "..." line) 1063 * @return the shortened string 1064 */ 1065 public static String restrictStringLines(String s, int maxLines) { 1066 if (s == null) { 1067 return null; 1068 } else { 1069 return join("\n", limit(Arrays.asList(s.split("\\n")), maxLines, "...")); 1070 } 1071 } 1072 1073 /** 1074 * If the collection {@code elements} is larger than {@code maxElements} elements, 1075 * the collection is shortened and the {@code overflowIndicator} is appended. 1076 * @param <T> type of elements 1077 * @param elements collection to shorten 1078 * @param maxElements maximum number of elements to keep (including including the {@code overflowIndicator}) 1079 * @param overflowIndicator the element used to indicate that the collection has been shortened 1080 * @return the shortened collection 1081 */ 1082 public static <T> Collection<T> limit(Collection<T> elements, int maxElements, T overflowIndicator) { 1083 if (elements == null) { 1084 return null; 1085 } else { 1086 if (elements.size() > maxElements) { 1087 final Collection<T> r = new ArrayList<>(maxElements); 1088 final Iterator<T> it = elements.iterator(); 1089 while (r.size() < maxElements - 1) { 1090 r.add(it.next()); 1091 } 1092 r.add(overflowIndicator); 1093 return r; 1094 } else { 1095 return elements; 1096 } 1097 } 1098 } 1099 1100 /** 1101 * Fixes URL with illegal characters in the query (and fragment) part by 1102 * percent encoding those characters. 1103 * 1104 * special characters like & and # are not encoded 1105 * 1106 * @param url the URL that should be fixed 1107 * @return the repaired URL 1108 */ 1109 public static String fixURLQuery(String url) { 1110 if (url == null || url.indexOf('?') == -1) 1111 return url; 1112 1113 String query = url.substring(url.indexOf('?') + 1); 1114 1115 StringBuilder sb = new StringBuilder(url.substring(0, url.indexOf('?') + 1)); 1116 1117 for (int i = 0; i < query.length(); i++) { 1118 String c = query.substring(i, i + 1); 1119 if (URL_CHARS.contains(c)) { 1120 sb.append(c); 1121 } else { 1122 sb.append(encodeUrl(c)); 1123 } 1124 } 1125 return sb.toString(); 1126 } 1127 1128 /** 1129 * Translates a string into <code>application/x-www-form-urlencoded</code> 1130 * format. This method uses UTF-8 encoding scheme to obtain the bytes for unsafe 1131 * characters. 1132 * 1133 * @param s <code>String</code> to be translated. 1134 * @return the translated <code>String</code>. 1135 * @see #decodeUrl(String) 1136 * @since 8304 1137 */ 1138 public static String encodeUrl(String s) { 1139 final String enc = StandardCharsets.UTF_8.name(); 1140 try { 1141 return URLEncoder.encode(s, enc); 1142 } catch (UnsupportedEncodingException e) { 1143 throw new IllegalStateException(e); 1144 } 1145 } 1146 1147 /** 1148 * Decodes a <code>application/x-www-form-urlencoded</code> string. 1149 * UTF-8 encoding is used to determine 1150 * what characters are represented by any consecutive sequences of the 1151 * form "<code>%<i>xy</i></code>". 1152 * 1153 * @param s the <code>String</code> to decode 1154 * @return the newly decoded <code>String</code> 1155 * @see #encodeUrl(String) 1156 * @since 8304 1157 */ 1158 public static String decodeUrl(String s) { 1159 final String enc = StandardCharsets.UTF_8.name(); 1160 try { 1161 return URLDecoder.decode(s, enc); 1162 } catch (UnsupportedEncodingException e) { 1163 throw new IllegalStateException(e); 1164 } 1165 } 1166 1167 /** 1168 * Determines if the given URL denotes a file on a local filesystem. 1169 * @param url The URL to test 1170 * @return {@code true} if the url points to a local file 1171 * @since 7356 1172 */ 1173 public static boolean isLocalUrl(String url) { 1174 return url != null && !url.startsWith("http://") && !url.startsWith("https://") && !url.startsWith("resource://"); 1175 } 1176 1177 /** 1178 * Determines if the given URL is valid. 1179 * @param url The URL to test 1180 * @return {@code true} if the url is valid 1181 * @since 10294 1182 */ 1183 public static boolean isValidUrl(String url) { 1184 if (url != null) { 1185 try { 1186 new URL(url); 1187 return true; 1188 } catch (MalformedURLException e) { 1189 Logging.trace(e); 1190 } 1191 } 1192 return false; 1193 } 1194 1195 /** 1196 * Creates a new {@link ThreadFactory} which creates threads with names according to {@code nameFormat}. 1197 * @param nameFormat a {@link String#format(String, Object...)} compatible name format; its first argument is a unique thread index 1198 * @param threadPriority the priority of the created threads, see {@link Thread#setPriority(int)} 1199 * @return a new {@link ThreadFactory} 1200 */ 1201 public static ThreadFactory newThreadFactory(final String nameFormat, final int threadPriority) { 1202 return new ThreadFactory() { 1203 final AtomicLong count = new AtomicLong(0); 1204 @Override 1205 public Thread newThread(final Runnable runnable) { 1206 final Thread thread = new Thread(runnable, String.format(Locale.ENGLISH, nameFormat, count.getAndIncrement())); 1207 thread.setPriority(threadPriority); 1208 return thread; 1209 } 1210 }; 1211 } 1212 1213 /** 1214 * A ForkJoinWorkerThread that will always inherit caller permissions, 1215 * unlike JDK's InnocuousForkJoinWorkerThread, used if a security manager exists. 1216 */ 1217 static final class JosmForkJoinWorkerThread extends ForkJoinWorkerThread { 1218 JosmForkJoinWorkerThread(ForkJoinPool pool) { 1219 super(pool); 1220 } 1221 } 1222 1223 /** 1224 * Returns a {@link ForkJoinPool} with the parallelism given by the preference key. 1225 * @param pref The preference key to determine parallelism 1226 * @param nameFormat see {@link #newThreadFactory(String, int)} 1227 * @param threadPriority see {@link #newThreadFactory(String, int)} 1228 * @return a {@link ForkJoinPool} 1229 */ 1230 public static ForkJoinPool newForkJoinPool(String pref, final String nameFormat, final int threadPriority) { 1231 int noThreads = Config.getPref().getInt(pref, Runtime.getRuntime().availableProcessors()); 1232 return new ForkJoinPool(noThreads, new ForkJoinPool.ForkJoinWorkerThreadFactory() { 1233 final AtomicLong count = new AtomicLong(0); 1234 @Override 1235 public ForkJoinWorkerThread newThread(ForkJoinPool pool) { 1236 // Do not use JDK default thread factory ! 1237 // If JOSM is started with Java Web Start, a security manager is installed and the factory 1238 // creates threads without any permission, forbidding them to load a class instantiating 1239 // another ForkJoinPool such as MultipolygonBuilder (see bug #15722) 1240 final ForkJoinWorkerThread thread = new JosmForkJoinWorkerThread(pool); 1241 thread.setName(String.format(Locale.ENGLISH, nameFormat, count.getAndIncrement())); 1242 thread.setPriority(threadPriority); 1243 return thread; 1244 } 1245 }, null, true); 1246 } 1247 1248 /** 1249 * Returns an executor which executes commands in the calling thread 1250 * @return an executor 1251 */ 1252 public static Executor newDirectExecutor() { 1253 return Runnable::run; 1254 } 1255 1256 /** 1257 * Updates a given system property. 1258 * @param key The property key 1259 * @param value The property value 1260 * @return the previous value of the system property, or {@code null} if it did not have one. 1261 * @since 7894 1262 */ 1263 public static String updateSystemProperty(String key, String value) { 1264 if (value != null) { 1265 String old = System.setProperty(key, value); 1266 if (Logging.isDebugEnabled() && !value.equals(old)) { 1267 if (!key.toLowerCase(Locale.ENGLISH).contains("password")) { 1268 Logging.debug("System property '" + key + "' set to '" + value + "'. Old value was '" + old + '\''); 1269 } else { 1270 Logging.debug("System property '" + key + "' changed."); 1271 } 1272 } 1273 return old; 1274 } 1275 return null; 1276 } 1277 1278 /** 1279 * Returns a new secure DOM builder, supporting XML namespaces. 1280 * @return a new secure DOM builder, supporting XML namespaces 1281 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration. 1282 * @since 10404 1283 */ 1284 public static DocumentBuilder newSafeDOMBuilder() throws ParserConfigurationException { 1285 DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); 1286 builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); 1287 builderFactory.setNamespaceAware(true); 1288 builderFactory.setValidating(false); 1289 return builderFactory.newDocumentBuilder(); 1290 } 1291 1292 /** 1293 * Parse the content given {@link InputStream} as XML. 1294 * This method uses a secure DOM builder, supporting XML namespaces. 1295 * 1296 * @param is The InputStream containing the content to be parsed. 1297 * @return the result DOM document 1298 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration. 1299 * @throws IOException if any IO errors occur. 1300 * @throws SAXException for SAX errors. 1301 * @since 10404 1302 */ 1303 public static Document parseSafeDOM(InputStream is) throws ParserConfigurationException, IOException, SAXException { 1304 long start = System.currentTimeMillis(); 1305 Logging.debug("Starting DOM parsing of {0}", is); 1306 Document result = newSafeDOMBuilder().parse(is); 1307 if (Logging.isDebugEnabled()) { 1308 Logging.debug("DOM parsing done in {0}", getDurationString(System.currentTimeMillis() - start)); 1309 } 1310 return result; 1311 } 1312 1313 /** 1314 * Returns a new secure SAX parser, supporting XML namespaces. 1315 * @return a new secure SAX parser, supporting XML namespaces 1316 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration. 1317 * @throws SAXException for SAX errors. 1318 * @since 8287 1319 */ 1320 public static SAXParser newSafeSAXParser() throws ParserConfigurationException, SAXException { 1321 SAXParserFactory parserFactory = SAXParserFactory.newInstance(); 1322 parserFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); 1323 parserFactory.setNamespaceAware(true); 1324 return parserFactory.newSAXParser(); 1325 } 1326 1327 /** 1328 * Parse the content given {@link org.xml.sax.InputSource} as XML using the specified {@link org.xml.sax.helpers.DefaultHandler}. 1329 * This method uses a secure SAX parser, supporting XML namespaces. 1330 * 1331 * @param is The InputSource containing the content to be parsed. 1332 * @param dh The SAX DefaultHandler to use. 1333 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration. 1334 * @throws SAXException for SAX errors. 1335 * @throws IOException if any IO errors occur. 1336 * @since 8347 1337 */ 1338 public static void parseSafeSAX(InputSource is, DefaultHandler dh) throws ParserConfigurationException, SAXException, IOException { 1339 long start = System.currentTimeMillis(); 1340 Logging.debug("Starting SAX parsing of {0} using {1}", is, dh); 1341 newSafeSAXParser().parse(is, dh); 1342 if (Logging.isDebugEnabled()) { 1343 Logging.debug("SAX parsing done in {0}", getDurationString(System.currentTimeMillis() - start)); 1344 } 1345 } 1346 1347 /** 1348 * Determines if the filename has one of the given extensions, in a robust manner. 1349 * The comparison is case and locale insensitive. 1350 * @param filename The file name 1351 * @param extensions The list of extensions to look for (without dot) 1352 * @return {@code true} if the filename has one of the given extensions 1353 * @since 8404 1354 */ 1355 public static boolean hasExtension(String filename, String... extensions) { 1356 String name = filename.toLowerCase(Locale.ENGLISH).replace("?format=raw", ""); 1357 for (String ext : extensions) { 1358 if (name.endsWith('.' + ext.toLowerCase(Locale.ENGLISH))) 1359 return true; 1360 } 1361 return false; 1362 } 1363 1364 /** 1365 * Determines if the file's name has one of the given extensions, in a robust manner. 1366 * The comparison is case and locale insensitive. 1367 * @param file The file 1368 * @param extensions The list of extensions to look for (without dot) 1369 * @return {@code true} if the file's name has one of the given extensions 1370 * @since 8404 1371 */ 1372 public static boolean hasExtension(File file, String... extensions) { 1373 return hasExtension(file.getName(), extensions); 1374 } 1375 1376 /** 1377 * Reads the input stream and closes the stream at the end of processing (regardless if an exception was thrown) 1378 * 1379 * @param stream input stream 1380 * @return byte array of data in input stream (empty if stream is null) 1381 * @throws IOException if any I/O error occurs 1382 */ 1383 public static byte[] readBytesFromStream(InputStream stream) throws IOException { 1384 if (stream == null) { 1385 return new byte[0]; 1386 } 1387 try { 1388 ByteArrayOutputStream bout = new ByteArrayOutputStream(stream.available()); 1389 byte[] buffer = new byte[2048]; 1390 boolean finished = false; 1391 do { 1392 int read = stream.read(buffer); 1393 if (read >= 0) { 1394 bout.write(buffer, 0, read); 1395 } else { 1396 finished = true; 1397 } 1398 } while (!finished); 1399 if (bout.size() == 0) 1400 return new byte[0]; 1401 return bout.toByteArray(); 1402 } finally { 1403 stream.close(); 1404 } 1405 } 1406 1407 /** 1408 * Returns the initial capacity to pass to the HashMap / HashSet constructor 1409 * when it is initialized with a known number of entries. 1410 * 1411 * When a HashMap is filled with entries, the underlying array is copied over 1412 * to a larger one multiple times. To avoid this process when the number of 1413 * entries is known in advance, the initial capacity of the array can be 1414 * given to the HashMap constructor. This method returns a suitable value 1415 * that avoids rehashing but doesn't waste memory. 1416 * @param nEntries the number of entries expected 1417 * @param loadFactor the load factor 1418 * @return the initial capacity for the HashMap constructor 1419 */ 1420 public static int hashMapInitialCapacity(int nEntries, double loadFactor) { 1421 return (int) Math.ceil(nEntries / loadFactor); 1422 } 1423 1424 /** 1425 * Returns the initial capacity to pass to the HashMap / HashSet constructor 1426 * when it is initialized with a known number of entries. 1427 * 1428 * When a HashMap is filled with entries, the underlying array is copied over 1429 * to a larger one multiple times. To avoid this process when the number of 1430 * entries is known in advance, the initial capacity of the array can be 1431 * given to the HashMap constructor. This method returns a suitable value 1432 * that avoids rehashing but doesn't waste memory. 1433 * 1434 * Assumes default load factor (0.75). 1435 * @param nEntries the number of entries expected 1436 * @return the initial capacity for the HashMap constructor 1437 */ 1438 public static int hashMapInitialCapacity(int nEntries) { 1439 return hashMapInitialCapacity(nEntries, 0.75d); 1440 } 1441 1442 /** 1443 * Utility class to save a string along with its rendering direction 1444 * (left-to-right or right-to-left). 1445 */ 1446 private static class DirectionString { 1447 public final int direction; 1448 public final String str; 1449 1450 DirectionString(int direction, String str) { 1451 this.direction = direction; 1452 this.str = str; 1453 } 1454 } 1455 1456 /** 1457 * Convert a string to a list of {@link GlyphVector}s. The string may contain 1458 * bi-directional text. The result will be in correct visual order. 1459 * Each element of the resulting list corresponds to one section of the 1460 * string with consistent writing direction (left-to-right or right-to-left). 1461 * 1462 * @param string the string to render 1463 * @param font the font 1464 * @param frc a FontRenderContext object 1465 * @return a list of GlyphVectors 1466 */ 1467 public static List<GlyphVector> getGlyphVectorsBidi(String string, Font font, FontRenderContext frc) { 1468 List<GlyphVector> gvs = new ArrayList<>(); 1469 Bidi bidi = new Bidi(string, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT); 1470 byte[] levels = new byte[bidi.getRunCount()]; 1471 DirectionString[] dirStrings = new DirectionString[levels.length]; 1472 for (int i = 0; i < levels.length; ++i) { 1473 levels[i] = (byte) bidi.getRunLevel(i); 1474 String substr = string.substring(bidi.getRunStart(i), bidi.getRunLimit(i)); 1475 int dir = levels[i] % 2 == 0 ? Bidi.DIRECTION_LEFT_TO_RIGHT : Bidi.DIRECTION_RIGHT_TO_LEFT; 1476 dirStrings[i] = new DirectionString(dir, substr); 1477 } 1478 Bidi.reorderVisually(levels, 0, dirStrings, 0, levels.length); 1479 for (int i = 0; i < dirStrings.length; ++i) { 1480 char[] chars = dirStrings[i].str.toCharArray(); 1481 gvs.add(font.layoutGlyphVector(frc, chars, 0, chars.length, dirStrings[i].direction)); 1482 } 1483 return gvs; 1484 } 1485 1486 /** 1487 * Sets {@code AccessibleObject}(s) accessible. 1488 * @param objects objects 1489 * @see AccessibleObject#setAccessible 1490 * @since 10223 1491 */ 1492 public static void setObjectsAccessible(final AccessibleObject... objects) { 1493 if (objects != null && objects.length > 0) { 1494 AccessController.doPrivileged((PrivilegedAction<Object>) () -> { 1495 for (AccessibleObject o : objects) { 1496 o.setAccessible(true); 1497 } 1498 return null; 1499 }); 1500 } 1501 } 1502 1503 /** 1504 * Clamp a value to the given range 1505 * @param val The value 1506 * @param min minimum value 1507 * @param max maximum value 1508 * @return the value 1509 * @throws IllegalArgumentException if {@code min > max} 1510 * @since 10805 1511 */ 1512 public static double clamp(double val, double min, double max) { 1513 if (min > max) { 1514 throw new IllegalArgumentException(MessageFormat.format("Parameter min ({0}) cannot be greater than max ({1})", min, max)); 1515 } else if (val < min) { 1516 return min; 1517 } else if (val > max) { 1518 return max; 1519 } else { 1520 return val; 1521 } 1522 } 1523 1524 /** 1525 * Clamp a integer value to the given range 1526 * @param val The value 1527 * @param min minimum value 1528 * @param max maximum value 1529 * @return the value 1530 * @throws IllegalArgumentException if {@code min > max} 1531 * @since 11055 1532 */ 1533 public static int clamp(int val, int min, int max) { 1534 if (min > max) { 1535 throw new IllegalArgumentException(MessageFormat.format("Parameter min ({0}) cannot be greater than max ({1})", min, max)); 1536 } else if (val < min) { 1537 return min; 1538 } else if (val > max) { 1539 return max; 1540 } else { 1541 return val; 1542 } 1543 } 1544 1545 /** 1546 * Convert angle from radians to degrees. 1547 * 1548 * Replacement for {@link Math#toDegrees(double)} to match the Java 9 1549 * version of that method. (Can be removed when JOSM support for Java 8 ends.) 1550 * Only relevant in relation to ProjectionRegressionTest. 1551 * @param angleRad an angle in radians 1552 * @return the same angle in degrees 1553 * @see <a href="https://josm.openstreetmap.de/ticket/11889">#11889</a> 1554 * @since 12013 1555 */ 1556 public static double toDegrees(double angleRad) { 1557 return angleRad * TO_DEGREES; 1558 } 1559 1560 /** 1561 * Convert angle from degrees to radians. 1562 * 1563 * Replacement for {@link Math#toRadians(double)} to match the Java 9 1564 * version of that method. (Can be removed when JOSM support for Java 8 ends.) 1565 * Only relevant in relation to ProjectionRegressionTest. 1566 * @param angleDeg an angle in degrees 1567 * @return the same angle in radians 1568 * @see <a href="https://josm.openstreetmap.de/ticket/11889">#11889</a> 1569 * @since 12013 1570 */ 1571 public static double toRadians(double angleDeg) { 1572 return angleDeg * TO_RADIANS; 1573 } 1574 1575 /** 1576 * Returns the Java version as an int value. 1577 * @return the Java version as an int value (8, 9, 10, etc.) 1578 * @since 12130 1579 */ 1580 public static int getJavaVersion() { 1581 String version = System.getProperty("java.version"); 1582 if (version.startsWith("1.")) { 1583 version = version.substring(2); 1584 } 1585 // Allow these formats: 1586 // 1.8.0_72-ea 1587 // 9-ea 1588 // 9 1589 // 9.0.1 1590 int dotPos = version.indexOf('.'); 1591 int dashPos = version.indexOf('-'); 1592 return Integer.parseInt(version.substring(0, 1593 dotPos > -1 ? dotPos : dashPos > -1 ? dashPos : version.length())); 1594 } 1595 1596 /** 1597 * Returns the Java update as an int value. 1598 * @return the Java update as an int value (121, 131, etc.) 1599 * @since 12217 1600 */ 1601 public static int getJavaUpdate() { 1602 String version = System.getProperty("java.version"); 1603 if (version.startsWith("1.")) { 1604 version = version.substring(2); 1605 } 1606 // Allow these formats: 1607 // 1.8.0_72-ea 1608 // 9-ea 1609 // 9 1610 // 9.0.1 1611 int undePos = version.indexOf('_'); 1612 int dashPos = version.indexOf('-'); 1613 if (undePos > -1) { 1614 return Integer.parseInt(version.substring(undePos + 1, 1615 dashPos > -1 ? dashPos : version.length())); 1616 } 1617 int firstDotPos = version.indexOf('.'); 1618 int lastDotPos = version.lastIndexOf('.'); 1619 if (firstDotPos == lastDotPos) { 1620 return 0; 1621 } 1622 return firstDotPos > -1 ? Integer.parseInt(version.substring(firstDotPos + 1, 1623 lastDotPos > -1 ? lastDotPos : version.length())) : 0; 1624 } 1625 1626 /** 1627 * Returns the Java build number as an int value. 1628 * @return the Java build number as an int value (0, 1, etc.) 1629 * @since 12217 1630 */ 1631 public static int getJavaBuild() { 1632 String version = System.getProperty("java.runtime.version"); 1633 int bPos = version.indexOf('b'); 1634 int pPos = version.indexOf('+'); 1635 try { 1636 return Integer.parseInt(version.substring(bPos > -1 ? bPos + 1 : pPos + 1, version.length())); 1637 } catch (NumberFormatException e) { 1638 Logging.trace(e); 1639 return 0; 1640 } 1641 } 1642 1643 /** 1644 * Returns the JRE expiration date. 1645 * @return the JRE expiration date, or null 1646 * @since 12219 1647 */ 1648 public static Date getJavaExpirationDate() { 1649 try { 1650 Object value = null; 1651 Class<?> c = Class.forName("com.sun.deploy.config.BuiltInProperties"); 1652 try { 1653 value = c.getDeclaredField("JRE_EXPIRATION_DATE").get(null); 1654 } catch (NoSuchFieldException e) { 1655 // Field is gone with Java 9, there's a method instead 1656 Logging.trace(e); 1657 value = c.getDeclaredMethod("getProperty", String.class).invoke(null, "JRE_EXPIRATION_DATE"); 1658 } 1659 if (value instanceof String) { 1660 return DateFormat.getDateInstance(3, Locale.US).parse((String) value); 1661 } 1662 } catch (IllegalArgumentException | ReflectiveOperationException | SecurityException | ParseException e) { 1663 Logging.debug(e); 1664 } 1665 return null; 1666 } 1667 1668 /** 1669 * Returns the latest version of Java, from Oracle website. 1670 * @return the latest version of Java, from Oracle website 1671 * @since 12219 1672 */ 1673 public static String getJavaLatestVersion() { 1674 try { 1675 return HttpClient.create( 1676 new URL(Config.getPref().get( 1677 "java.baseline.version.url", 1678 "http://javadl-esd-secure.oracle.com/update/baseline.version"))) 1679 .connect().fetchContent().split("\n")[0]; 1680 } catch (IOException e) { 1681 Logging.error(e); 1682 } 1683 return null; 1684 } 1685 1686 /** 1687 * Get a function that converts an object to a singleton stream of a certain 1688 * class (or null if the object cannot be cast to that class). 1689 * 1690 * Can be useful in relation with streams, but be aware of the performance 1691 * implications of creating a stream for each element. 1692 * @param <T> type of the objects to convert 1693 * @param <U> type of the elements in the resulting stream 1694 * @param klass the class U 1695 * @return function converting an object to a singleton stream or null 1696 * @since 12594 1697 */ 1698 public static <T, U> Function<T, Stream<U>> castToStream(Class<U> klass) { 1699 return x -> klass.isInstance(x) ? Stream.of(klass.cast(x)) : null; 1700 } 1701 1702 /** 1703 * Helper method to replace the "<code>instanceof</code>-check and cast" pattern. 1704 * Checks if an object is instance of class T and performs an action if that 1705 * is the case. 1706 * Syntactic sugar to avoid typing the class name two times, when one time 1707 * would suffice. 1708 * @param <T> the type for the instanceof check and cast 1709 * @param o the object to check and cast 1710 * @param klass the class T 1711 * @param consumer action to take when o is and instance of T 1712 * @since 12604 1713 */ 1714 @SuppressWarnings("unchecked") 1715 public static <T> void instanceOfThen(Object o, Class<T> klass, Consumer<? super T> consumer) { 1716 if (klass.isInstance(o)) { 1717 consumer.accept((T) o); 1718 } 1719 } 1720 1721 /** 1722 * Helper method to replace the "<code>instanceof</code>-check and cast" pattern. 1723 * 1724 * @param <T> the type for the instanceof check and cast 1725 * @param o the object to check and cast 1726 * @param klass the class T 1727 * @return {@link Optional} containing the result of the cast, if it is possible, an empty 1728 * Optional otherwise 1729 */ 1730 @SuppressWarnings("unchecked") 1731 public static <T> Optional<T> instanceOfAndCast(Object o, Class<T> klass) { 1732 if (klass.isInstance(o)) 1733 return Optional.of((T) o); 1734 return Optional.empty(); 1735 } 1736 1737 /** 1738 * Returns JRE JavaScript Engine (Nashorn by default), if any. 1739 * Catches and logs SecurityException and return null in case of error. 1740 * @return JavaScript Engine, or null. 1741 * @since 13301 1742 */ 1743 public static ScriptEngine getJavaScriptEngine() { 1744 try { 1745 return new ScriptEngineManager(null).getEngineByName("JavaScript"); 1746 } catch (SecurityException e) { 1747 Logging.error(e); 1748 return null; 1749 } 1750 } 1751 1752 /** 1753 * Convenient method to open an URL stream, using JOSM HTTP client if neeeded. 1754 * @param url URL for reading from 1755 * @return an input stream for reading from the URL 1756 * @throws IOException if any I/O error occurs 1757 * @since 13356 1758 */ 1759 public static InputStream openStream(URL url) throws IOException { 1760 switch (url.getProtocol()) { 1761 case "http": 1762 case "https": 1763 return HttpClient.create(url).connect().getContent(); 1764 case "jar": 1765 try { 1766 return url.openStream(); 1767 } catch (FileNotFoundException e) { 1768 // Workaround to https://bugs.openjdk.java.net/browse/JDK-4523159 1769 String urlPath = url.getPath(); 1770 if (urlPath.startsWith("file:/") && urlPath.split("!").length > 2) { 1771 try { 1772 // Locate jar file 1773 int index = urlPath.lastIndexOf("!/"); 1774 Path jarFile = Paths.get(urlPath.substring("file:/".length(), index)); 1775 Path filename = jarFile.getFileName(); 1776 FileTime jarTime = Files.readAttributes(jarFile, BasicFileAttributes.class).lastModifiedTime(); 1777 // Copy it to temp directory (hopefully free of exclamation mark) if needed (missing or older jar) 1778 Path jarCopy = Paths.get(System.getProperty("java.io.tmpdir")).resolve(filename); 1779 if (!jarCopy.toFile().exists() || 1780 Files.readAttributes(jarCopy, BasicFileAttributes.class).lastModifiedTime().compareTo(jarTime) < 0) { 1781 Files.copy(jarFile, jarCopy, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); 1782 } 1783 // Open the stream using the copy 1784 return new URL(url.getProtocol() + ':' + jarCopy.toUri().toURL().toExternalForm() + urlPath.substring(index)) 1785 .openStream(); 1786 } catch (RuntimeException | IOException ex) { 1787 Logging.warn(ex); 1788 } 1789 } 1790 throw e; 1791 } 1792 case "file": 1793 default: 1794 return url.openStream(); 1795 } 1796 } 1797}