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

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

see #15310 - remove most of deprecated APIs

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