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

Last change on this file since 10741 was 10721, checked in by simon04, 8 years ago

Remove too specific Utils functions

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