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

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

fix #13889 - Make preset searchs ignore accents

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