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

Last change on this file since 13451 was 13450, checked in by Don-vip, 6 years ago

fix #15992 - load native certificates from macOS system root trust store, see https://support.apple.com/en-us/HT208127

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