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

Last change on this file since 12181 was 12130, checked in by Don-vip, 7 years ago

see #11924 - do not try old workaround with java 9 (pollutes console with stacktrace)

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