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

Last change on this file since 13060 was 12987, checked in by bastiK, 7 years ago

see #15410 - change preferences scheme for named colors - makes runtime color name registry obsolete

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