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

Last change on this file since 10621 was 10616, checked in by Don-vip, 8 years ago

see #11390 - sonar - squid:S1604 - Java 8: Anonymous inner classes containing only one method should become lambdas

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