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

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

see #11924 - make the JRE expiration date detection system work with Java 9

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