source: josm/trunk/src/org/openstreetmap/josm/tools/Utils.java@ 15716

Last change on this file since 15716 was 15716, checked in by simon04, 4 years ago

Java 8: use String.join

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