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

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

see #16047 - catch correct exception

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