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

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

fix #16316 - catch InvalidPathException

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