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

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

fix #15210 - Fix support of IBM JVM

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