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

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

see #14794 - checkstyle

  • Property svn:eol-style set to native
File size: 62.6 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.ZipFile;
61import java.util.zip.ZipInputStream;
62
63import javax.xml.XMLConstants;
64import javax.xml.parsers.DocumentBuilder;
65import javax.xml.parsers.DocumentBuilderFactory;
66import javax.xml.parsers.ParserConfigurationException;
67import javax.xml.parsers.SAXParser;
68import javax.xml.parsers.SAXParserFactory;
69
70import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
71import org.openstreetmap.josm.Main;
72import org.openstreetmap.josm.io.Compression;
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 * @deprecated use {@link Compression#getBZip2InputStream(java.io.InputStream)}
730 */
731 @Deprecated
732 public static BZip2CompressorInputStream getBZip2InputStream(InputStream in) throws IOException {
733 return Compression.getBZip2InputStream(in);
734 }
735
736 /**
737 * Returns a Gzip input stream wrapping given input stream.
738 * @param in The raw input stream
739 * @return a Gzip input stream wrapping given input stream, or {@code null} if {@code in} is {@code null}
740 * @throws IOException if an I/O error has occurred
741 * @since 7119
742 * @deprecated use {@link Compression#getGZipInputStream(java.io.InputStream)}
743 */
744 @Deprecated
745 public static GZIPInputStream getGZipInputStream(InputStream in) throws IOException {
746 return Compression.getGZipInputStream(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 * @deprecated use {@link Compression#getZipInputStream(java.io.InputStream)}
756 */
757 @Deprecated
758 public static ZipInputStream getZipInputStream(InputStream in) throws IOException {
759 return Compression.getZipInputStream(in);
760 }
761
762 /**
763 * Determines if the given String would be empty if stripped.
764 * This is an efficient alternative to {@code strip(s).isEmpty()} that avoids to create useless String object.
765 * @param str The string to test
766 * @return {@code true} if the stripped version of {@code s} would be empty.
767 * @since 11435
768 */
769 public static boolean isStripEmpty(String str) {
770 if (str != null) {
771 for (int i = 0; i < str.length(); i++) {
772 if (!isStrippedChar(str.charAt(i), DEFAULT_STRIP)) {
773 return false;
774 }
775 }
776 }
777 return true;
778 }
779
780 /**
781 * An alternative to {@link String#trim()} to effectively remove all leading
782 * and trailing white characters, including Unicode ones.
783 * @param str The string to strip
784 * @return <code>str</code>, without leading and trailing characters, according to
785 * {@link Character#isWhitespace(char)} and {@link Character#isSpaceChar(char)}.
786 * @see <a href="http://closingbraces.net/2008/11/11/javastringtrim/">Java String.trim has a strange idea of whitespace</a>
787 * @see <a href="https://bugs.openjdk.java.net/browse/JDK-4080617">JDK bug 4080617</a>
788 * @see <a href="https://bugs.openjdk.java.net/browse/JDK-7190385">JDK bug 7190385</a>
789 * @since 5772
790 */
791 public static String strip(final String str) {
792 if (str == null || str.isEmpty()) {
793 return str;
794 }
795 return strip(str, DEFAULT_STRIP);
796 }
797
798 /**
799 * An alternative to {@link String#trim()} to effectively remove all leading
800 * and trailing white characters, including Unicode ones.
801 * @param str The string to strip
802 * @param skipChars additional characters to skip
803 * @return <code>str</code>, without leading and trailing characters, according to
804 * {@link Character#isWhitespace(char)}, {@link Character#isSpaceChar(char)} and skipChars.
805 * @since 8435
806 */
807 public static String strip(final String str, final String skipChars) {
808 if (str == null || str.isEmpty()) {
809 return str;
810 }
811 return strip(str, stripChars(skipChars));
812 }
813
814 private static String strip(final String str, final char... skipChars) {
815
816 int start = 0;
817 int end = str.length();
818 boolean leadingSkipChar = true;
819 while (leadingSkipChar && start < end) {
820 leadingSkipChar = isStrippedChar(str.charAt(start), skipChars);
821 if (leadingSkipChar) {
822 start++;
823 }
824 }
825 boolean trailingSkipChar = true;
826 while (trailingSkipChar && end > start + 1) {
827 trailingSkipChar = isStrippedChar(str.charAt(end - 1), skipChars);
828 if (trailingSkipChar) {
829 end--;
830 }
831 }
832
833 return str.substring(start, end);
834 }
835
836 private static boolean isStrippedChar(char c, final char... skipChars) {
837 return Character.isWhitespace(c) || Character.isSpaceChar(c) || stripChar(skipChars, c);
838 }
839
840 private static char[] stripChars(final String skipChars) {
841 if (skipChars == null || skipChars.isEmpty()) {
842 return DEFAULT_STRIP;
843 }
844
845 char[] chars = new char[DEFAULT_STRIP.length + skipChars.length()];
846 System.arraycopy(DEFAULT_STRIP, 0, chars, 0, DEFAULT_STRIP.length);
847 skipChars.getChars(0, skipChars.length(), chars, DEFAULT_STRIP.length);
848
849 return chars;
850 }
851
852 private static boolean stripChar(final char[] strip, char c) {
853 for (char s : strip) {
854 if (c == s) {
855 return true;
856 }
857 }
858 return false;
859 }
860
861 /**
862 * Runs an external command and returns the standard output.
863 *
864 * The program is expected to execute fast.
865 *
866 * @param command the command with arguments
867 * @return the output
868 * @throws IOException when there was an error, e.g. command does not exist
869 */
870 public static String execOutput(List<String> command) throws IOException {
871 if (Logging.isDebugEnabled()) {
872 Logging.debug(join(" ", command));
873 }
874 Process p = new ProcessBuilder(command).start();
875 try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
876 StringBuilder all = null;
877 String line;
878 while ((line = input.readLine()) != null) {
879 if (all == null) {
880 all = new StringBuilder(line);
881 } else {
882 all.append('\n');
883 all.append(line);
884 }
885 }
886 return all != null ? all.toString() : null;
887 }
888 }
889
890 /**
891 * Returns the JOSM temp directory.
892 * @return The JOSM temp directory ({@code <java.io.tmpdir>/JOSM}), or {@code null} if {@code java.io.tmpdir} is not defined
893 * @since 6245
894 */
895 public static File getJosmTempDir() {
896 String tmpDir = System.getProperty("java.io.tmpdir");
897 if (tmpDir == null) {
898 return null;
899 }
900 File josmTmpDir = new File(tmpDir, "JOSM");
901 if (!josmTmpDir.exists() && !josmTmpDir.mkdirs()) {
902 Logging.warn("Unable to create temp directory " + josmTmpDir);
903 }
904 return josmTmpDir;
905 }
906
907 /**
908 * Returns a simple human readable (hours, minutes, seconds) string for a given duration in milliseconds.
909 * @param elapsedTime The duration in milliseconds
910 * @return A human readable string for the given duration
911 * @throws IllegalArgumentException if elapsedTime is &lt; 0
912 * @since 6354
913 */
914 public static String getDurationString(long elapsedTime) {
915 if (elapsedTime < 0) {
916 throw new IllegalArgumentException("elapsedTime must be >= 0");
917 }
918 // Is it less than 1 second ?
919 if (elapsedTime < MILLIS_OF_SECOND) {
920 return String.format("%d %s", elapsedTime, tr("ms"));
921 }
922 // Is it less than 1 minute ?
923 if (elapsedTime < MILLIS_OF_MINUTE) {
924 return String.format("%.1f %s", elapsedTime / (double) MILLIS_OF_SECOND, tr("s"));
925 }
926 // Is it less than 1 hour ?
927 if (elapsedTime < MILLIS_OF_HOUR) {
928 final long min = elapsedTime / MILLIS_OF_MINUTE;
929 return String.format("%d %s %d %s", min, tr("min"), (elapsedTime - min * MILLIS_OF_MINUTE) / MILLIS_OF_SECOND, tr("s"));
930 }
931 // Is it less than 1 day ?
932 if (elapsedTime < MILLIS_OF_DAY) {
933 final long hour = elapsedTime / MILLIS_OF_HOUR;
934 return String.format("%d %s %d %s", hour, tr("h"), (elapsedTime - hour * MILLIS_OF_HOUR) / MILLIS_OF_MINUTE, tr("min"));
935 }
936 long days = elapsedTime / MILLIS_OF_DAY;
937 return String.format("%d %s %d %s", days, trn("day", "days", days), (elapsedTime - days * MILLIS_OF_DAY) / MILLIS_OF_HOUR, tr("h"));
938 }
939
940 /**
941 * Returns a human readable representation (B, kB, MB, ...) for the given number of byes.
942 * @param bytes the number of bytes
943 * @param locale the locale used for formatting
944 * @return a human readable representation
945 * @since 9274
946 */
947 public static String getSizeString(long bytes, Locale locale) {
948 if (bytes < 0) {
949 throw new IllegalArgumentException("bytes must be >= 0");
950 }
951 int unitIndex = 0;
952 double value = bytes;
953 while (value >= 1024 && unitIndex < SIZE_UNITS.length) {
954 value /= 1024;
955 unitIndex++;
956 }
957 if (value > 100 || unitIndex == 0) {
958 return String.format(locale, "%.0f %s", value, SIZE_UNITS[unitIndex]);
959 } else if (value > 10) {
960 return String.format(locale, "%.1f %s", value, SIZE_UNITS[unitIndex]);
961 } else {
962 return String.format(locale, "%.2f %s", value, SIZE_UNITS[unitIndex]);
963 }
964 }
965
966 /**
967 * Returns a human readable representation of a list of positions.
968 * <p>
969 * For instance, {@code [1,5,2,6,7} yields "1-2,5-7
970 * @param positionList a list of positions
971 * @return a human readable representation
972 */
973 public static String getPositionListString(List<Integer> positionList) {
974 Collections.sort(positionList);
975 final StringBuilder sb = new StringBuilder(32);
976 sb.append(positionList.get(0));
977 int cnt = 0;
978 int last = positionList.get(0);
979 for (int i = 1; i < positionList.size(); ++i) {
980 int cur = positionList.get(i);
981 if (cur == last + 1) {
982 ++cnt;
983 } else if (cnt == 0) {
984 sb.append(',').append(cur);
985 } else {
986 sb.append('-').append(last);
987 sb.append(',').append(cur);
988 cnt = 0;
989 }
990 last = cur;
991 }
992 if (cnt >= 1) {
993 sb.append('-').append(last);
994 }
995 return sb.toString();
996 }
997
998 /**
999 * Returns a list of capture groups if {@link Matcher#matches()}, or {@code null}.
1000 * The first element (index 0) is the complete match.
1001 * Further elements correspond to the parts in parentheses of the regular expression.
1002 * @param m the matcher
1003 * @return a list of capture groups if {@link Matcher#matches()}, or {@code null}.
1004 */
1005 public static List<String> getMatches(final Matcher m) {
1006 if (m.matches()) {
1007 List<String> result = new ArrayList<>(m.groupCount() + 1);
1008 for (int i = 0; i <= m.groupCount(); i++) {
1009 result.add(m.group(i));
1010 }
1011 return result;
1012 } else {
1013 return null;
1014 }
1015 }
1016
1017 /**
1018 * Cast an object savely.
1019 * @param <T> the target type
1020 * @param o the object to cast
1021 * @param klass the target class (same as T)
1022 * @return null if <code>o</code> is null or the type <code>o</code> is not
1023 * a subclass of <code>klass</code>. The casted value otherwise.
1024 */
1025 @SuppressWarnings("unchecked")
1026 public static <T> T cast(Object o, Class<T> klass) {
1027 if (klass.isInstance(o)) {
1028 return (T) o;
1029 }
1030 return null;
1031 }
1032
1033 /**
1034 * Returns the root cause of a throwable object.
1035 * @param t The object to get root cause for
1036 * @return the root cause of {@code t}
1037 * @since 6639
1038 */
1039 public static Throwable getRootCause(Throwable t) {
1040 Throwable result = t;
1041 if (result != null) {
1042 Throwable cause = result.getCause();
1043 while (cause != null && !cause.equals(result)) {
1044 result = cause;
1045 cause = result.getCause();
1046 }
1047 }
1048 return result;
1049 }
1050
1051 /**
1052 * Adds the given item at the end of a new copy of given array.
1053 * @param <T> type of items
1054 * @param array The source array
1055 * @param item The item to add
1056 * @return An extended copy of {@code array} containing {@code item} as additional last element
1057 * @since 6717
1058 */
1059 public static <T> T[] addInArrayCopy(T[] array, T item) {
1060 T[] biggerCopy = Arrays.copyOf(array, array.length + 1);
1061 biggerCopy[array.length] = item;
1062 return biggerCopy;
1063 }
1064
1065 /**
1066 * If the string {@code s} is longer than {@code maxLength}, the string is cut and "..." is appended.
1067 * @param s String to shorten
1068 * @param maxLength maximum number of characters to keep (not including the "...")
1069 * @return the shortened string
1070 */
1071 public static String shortenString(String s, int maxLength) {
1072 if (s != null && s.length() > maxLength) {
1073 return s.substring(0, maxLength - 3) + "...";
1074 } else {
1075 return s;
1076 }
1077 }
1078
1079 /**
1080 * If the string {@code s} is longer than {@code maxLines} lines, the string is cut and a "..." line is appended.
1081 * @param s String to shorten
1082 * @param maxLines maximum number of lines to keep (including including the "..." line)
1083 * @return the shortened string
1084 */
1085 public static String restrictStringLines(String s, int maxLines) {
1086 if (s == null) {
1087 return null;
1088 } else {
1089 return join("\n", limit(Arrays.asList(s.split("\\n")), maxLines, "..."));
1090 }
1091 }
1092
1093 /**
1094 * If the collection {@code elements} is larger than {@code maxElements} elements,
1095 * the collection is shortened and the {@code overflowIndicator} is appended.
1096 * @param <T> type of elements
1097 * @param elements collection to shorten
1098 * @param maxElements maximum number of elements to keep (including including the {@code overflowIndicator})
1099 * @param overflowIndicator the element used to indicate that the collection has been shortened
1100 * @return the shortened collection
1101 */
1102 public static <T> Collection<T> limit(Collection<T> elements, int maxElements, T overflowIndicator) {
1103 if (elements == null) {
1104 return null;
1105 } else {
1106 if (elements.size() > maxElements) {
1107 final Collection<T> r = new ArrayList<>(maxElements);
1108 final Iterator<T> it = elements.iterator();
1109 while (r.size() < maxElements - 1) {
1110 r.add(it.next());
1111 }
1112 r.add(overflowIndicator);
1113 return r;
1114 } else {
1115 return elements;
1116 }
1117 }
1118 }
1119
1120 /**
1121 * Fixes URL with illegal characters in the query (and fragment) part by
1122 * percent encoding those characters.
1123 *
1124 * special characters like &amp; and # are not encoded
1125 *
1126 * @param url the URL that should be fixed
1127 * @return the repaired URL
1128 */
1129 public static String fixURLQuery(String url) {
1130 if (url == null || url.indexOf('?') == -1)
1131 return url;
1132
1133 String query = url.substring(url.indexOf('?') + 1);
1134
1135 StringBuilder sb = new StringBuilder(url.substring(0, url.indexOf('?') + 1));
1136
1137 for (int i = 0; i < query.length(); i++) {
1138 String c = query.substring(i, i + 1);
1139 if (URL_CHARS.contains(c)) {
1140 sb.append(c);
1141 } else {
1142 sb.append(encodeUrl(c));
1143 }
1144 }
1145 return sb.toString();
1146 }
1147
1148 /**
1149 * Translates a string into <code>application/x-www-form-urlencoded</code>
1150 * format. This method uses UTF-8 encoding scheme to obtain the bytes for unsafe
1151 * characters.
1152 *
1153 * @param s <code>String</code> to be translated.
1154 * @return the translated <code>String</code>.
1155 * @see #decodeUrl(String)
1156 * @since 8304
1157 */
1158 public static String encodeUrl(String s) {
1159 final String enc = StandardCharsets.UTF_8.name();
1160 try {
1161 return URLEncoder.encode(s, enc);
1162 } catch (UnsupportedEncodingException e) {
1163 throw new IllegalStateException(e);
1164 }
1165 }
1166
1167 /**
1168 * Decodes a <code>application/x-www-form-urlencoded</code> string.
1169 * UTF-8 encoding is used to determine
1170 * what characters are represented by any consecutive sequences of the
1171 * form "<code>%<i>xy</i></code>".
1172 *
1173 * @param s the <code>String</code> to decode
1174 * @return the newly decoded <code>String</code>
1175 * @see #encodeUrl(String)
1176 * @since 8304
1177 */
1178 public static String decodeUrl(String s) {
1179 final String enc = StandardCharsets.UTF_8.name();
1180 try {
1181 return URLDecoder.decode(s, enc);
1182 } catch (UnsupportedEncodingException e) {
1183 throw new IllegalStateException(e);
1184 }
1185 }
1186
1187 /**
1188 * Determines if the given URL denotes a file on a local filesystem.
1189 * @param url The URL to test
1190 * @return {@code true} if the url points to a local file
1191 * @since 7356
1192 */
1193 public static boolean isLocalUrl(String url) {
1194 return url != null && !url.startsWith("http://") && !url.startsWith("https://") && !url.startsWith("resource://");
1195 }
1196
1197 /**
1198 * Determines if the given URL is valid.
1199 * @param url The URL to test
1200 * @return {@code true} if the url is valid
1201 * @since 10294
1202 */
1203 public static boolean isValidUrl(String url) {
1204 if (url != null) {
1205 try {
1206 new URL(url);
1207 return true;
1208 } catch (MalformedURLException e) {
1209 Logging.trace(e);
1210 }
1211 }
1212 return false;
1213 }
1214
1215 /**
1216 * Creates a new {@link ThreadFactory} which creates threads with names according to {@code nameFormat}.
1217 * @param nameFormat a {@link String#format(String, Object...)} compatible name format; its first argument is a unique thread index
1218 * @param threadPriority the priority of the created threads, see {@link Thread#setPriority(int)}
1219 * @return a new {@link ThreadFactory}
1220 */
1221 public static ThreadFactory newThreadFactory(final String nameFormat, final int threadPriority) {
1222 return new ThreadFactory() {
1223 final AtomicLong count = new AtomicLong(0);
1224 @Override
1225 public Thread newThread(final Runnable runnable) {
1226 final Thread thread = new Thread(runnable, String.format(Locale.ENGLISH, nameFormat, count.getAndIncrement()));
1227 thread.setPriority(threadPriority);
1228 return thread;
1229 }
1230 };
1231 }
1232
1233 /**
1234 * Returns a {@link ForkJoinPool} with the parallelism given by the preference key.
1235 * @param pref The preference key to determine parallelism
1236 * @param nameFormat see {@link #newThreadFactory(String, int)}
1237 * @param threadPriority see {@link #newThreadFactory(String, int)}
1238 * @return a {@link ForkJoinPool}
1239 */
1240 public static ForkJoinPool newForkJoinPool(String pref, final String nameFormat, final int threadPriority) {
1241 int noThreads = Main.pref.getInteger(pref, Runtime.getRuntime().availableProcessors());
1242 return new ForkJoinPool(noThreads, new ForkJoinPool.ForkJoinWorkerThreadFactory() {
1243 final AtomicLong count = new AtomicLong(0);
1244 @Override
1245 public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
1246 final ForkJoinWorkerThread thread = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
1247 thread.setName(String.format(Locale.ENGLISH, nameFormat, count.getAndIncrement()));
1248 thread.setPriority(threadPriority);
1249 return thread;
1250 }
1251 }, null, true);
1252 }
1253
1254 /**
1255 * Returns an executor which executes commands in the calling thread
1256 * @return an executor
1257 */
1258 public static Executor newDirectExecutor() {
1259 return Runnable::run;
1260 }
1261
1262 /**
1263 * Updates a given system property.
1264 * @param key The property key
1265 * @param value The property value
1266 * @return the previous value of the system property, or {@code null} if it did not have one.
1267 * @since 7894
1268 */
1269 public static String updateSystemProperty(String key, String value) {
1270 if (value != null) {
1271 String old = System.setProperty(key, value);
1272 if (Logging.isDebugEnabled() && !value.equals(old)) {
1273 if (!key.toLowerCase(Locale.ENGLISH).contains("password")) {
1274 Logging.debug("System property '" + key + "' set to '" + value + "'. Old value was '" + old + '\'');
1275 } else {
1276 Logging.debug("System property '" + key + "' changed.");
1277 }
1278 }
1279 return old;
1280 }
1281 return null;
1282 }
1283
1284 /**
1285 * Returns a new secure DOM builder, supporting XML namespaces.
1286 * @return a new secure DOM builder, supporting XML namespaces
1287 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1288 * @since 10404
1289 */
1290 public static DocumentBuilder newSafeDOMBuilder() throws ParserConfigurationException {
1291 DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
1292 builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
1293 builderFactory.setNamespaceAware(true);
1294 builderFactory.setValidating(false);
1295 return builderFactory.newDocumentBuilder();
1296 }
1297
1298 /**
1299 * Parse the content given {@link InputStream} as XML.
1300 * This method uses a secure DOM builder, supporting XML namespaces.
1301 *
1302 * @param is The InputStream containing the content to be parsed.
1303 * @return the result DOM document
1304 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1305 * @throws IOException if any IO errors occur.
1306 * @throws SAXException for SAX errors.
1307 * @since 10404
1308 */
1309 public static Document parseSafeDOM(InputStream is) throws ParserConfigurationException, IOException, SAXException {
1310 long start = System.currentTimeMillis();
1311 Logging.debug("Starting DOM parsing of {0}", is);
1312 Document result = newSafeDOMBuilder().parse(is);
1313 if (Logging.isDebugEnabled()) {
1314 Logging.debug("DOM parsing done in {0}", getDurationString(System.currentTimeMillis() - start));
1315 }
1316 return result;
1317 }
1318
1319 /**
1320 * Returns a new secure SAX parser, supporting XML namespaces.
1321 * @return a new secure SAX parser, supporting XML namespaces
1322 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1323 * @throws SAXException for SAX errors.
1324 * @since 8287
1325 */
1326 public static SAXParser newSafeSAXParser() throws ParserConfigurationException, SAXException {
1327 SAXParserFactory parserFactory = SAXParserFactory.newInstance();
1328 parserFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
1329 parserFactory.setNamespaceAware(true);
1330 return parserFactory.newSAXParser();
1331 }
1332
1333 /**
1334 * Parse the content given {@link org.xml.sax.InputSource} as XML using the specified {@link org.xml.sax.helpers.DefaultHandler}.
1335 * This method uses a secure SAX parser, supporting XML namespaces.
1336 *
1337 * @param is The InputSource containing the content to be parsed.
1338 * @param dh The SAX DefaultHandler to use.
1339 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1340 * @throws SAXException for SAX errors.
1341 * @throws IOException if any IO errors occur.
1342 * @since 8347
1343 */
1344 public static void parseSafeSAX(InputSource is, DefaultHandler dh) throws ParserConfigurationException, SAXException, IOException {
1345 long start = System.currentTimeMillis();
1346 Logging.debug("Starting SAX parsing of {0} using {1}", is, dh);
1347 newSafeSAXParser().parse(is, dh);
1348 if (Logging.isDebugEnabled()) {
1349 Logging.debug("SAX parsing done in {0}", getDurationString(System.currentTimeMillis() - start));
1350 }
1351 }
1352
1353 /**
1354 * Determines if the filename has one of the given extensions, in a robust manner.
1355 * The comparison is case and locale insensitive.
1356 * @param filename The file name
1357 * @param extensions The list of extensions to look for (without dot)
1358 * @return {@code true} if the filename has one of the given extensions
1359 * @since 8404
1360 */
1361 public static boolean hasExtension(String filename, String... extensions) {
1362 String name = filename.toLowerCase(Locale.ENGLISH).replace("?format=raw", "");
1363 for (String ext : extensions) {
1364 if (name.endsWith('.' + ext.toLowerCase(Locale.ENGLISH)))
1365 return true;
1366 }
1367 return false;
1368 }
1369
1370 /**
1371 * Determines if the file's name has one of the given extensions, in a robust manner.
1372 * The comparison is case and locale insensitive.
1373 * @param file The file
1374 * @param extensions The list of extensions to look for (without dot)
1375 * @return {@code true} if the file's name has one of the given extensions
1376 * @since 8404
1377 */
1378 public static boolean hasExtension(File file, String... extensions) {
1379 return hasExtension(file.getName(), extensions);
1380 }
1381
1382 /**
1383 * Reads the input stream and closes the stream at the end of processing (regardless if an exception was thrown)
1384 *
1385 * @param stream input stream
1386 * @return byte array of data in input stream (empty if stream is null)
1387 * @throws IOException if any I/O error occurs
1388 */
1389 public static byte[] readBytesFromStream(InputStream stream) throws IOException {
1390 if (stream == null) {
1391 return new byte[0];
1392 }
1393 try {
1394 ByteArrayOutputStream bout = new ByteArrayOutputStream(stream.available());
1395 byte[] buffer = new byte[2048];
1396 boolean finished = false;
1397 do {
1398 int read = stream.read(buffer);
1399 if (read >= 0) {
1400 bout.write(buffer, 0, read);
1401 } else {
1402 finished = true;
1403 }
1404 } while (!finished);
1405 if (bout.size() == 0)
1406 return new byte[0];
1407 return bout.toByteArray();
1408 } finally {
1409 stream.close();
1410 }
1411 }
1412
1413 /**
1414 * Returns the initial capacity to pass to the HashMap / HashSet constructor
1415 * when it is initialized with a known number of entries.
1416 *
1417 * When a HashMap is filled with entries, the underlying array is copied over
1418 * to a larger one multiple times. To avoid this process when the number of
1419 * entries is known in advance, the initial capacity of the array can be
1420 * given to the HashMap constructor. This method returns a suitable value
1421 * that avoids rehashing but doesn't waste memory.
1422 * @param nEntries the number of entries expected
1423 * @param loadFactor the load factor
1424 * @return the initial capacity for the HashMap constructor
1425 */
1426 public static int hashMapInitialCapacity(int nEntries, double loadFactor) {
1427 return (int) Math.ceil(nEntries / loadFactor);
1428 }
1429
1430 /**
1431 * Returns the initial capacity to pass to the HashMap / HashSet constructor
1432 * when it is initialized with a known number of entries.
1433 *
1434 * When a HashMap is filled with entries, the underlying array is copied over
1435 * to a larger one multiple times. To avoid this process when the number of
1436 * entries is known in advance, the initial capacity of the array can be
1437 * given to the HashMap constructor. This method returns a suitable value
1438 * that avoids rehashing but doesn't waste memory.
1439 *
1440 * Assumes default load factor (0.75).
1441 * @param nEntries the number of entries expected
1442 * @return the initial capacity for the HashMap constructor
1443 */
1444 public static int hashMapInitialCapacity(int nEntries) {
1445 return hashMapInitialCapacity(nEntries, 0.75d);
1446 }
1447
1448 /**
1449 * Utility class to save a string along with its rendering direction
1450 * (left-to-right or right-to-left).
1451 */
1452 private static class DirectionString {
1453 public final int direction;
1454 public final String str;
1455
1456 DirectionString(int direction, String str) {
1457 this.direction = direction;
1458 this.str = str;
1459 }
1460 }
1461
1462 /**
1463 * Convert a string to a list of {@link GlyphVector}s. The string may contain
1464 * bi-directional text. The result will be in correct visual order.
1465 * Each element of the resulting list corresponds to one section of the
1466 * string with consistent writing direction (left-to-right or right-to-left).
1467 *
1468 * @param string the string to render
1469 * @param font the font
1470 * @param frc a FontRenderContext object
1471 * @return a list of GlyphVectors
1472 */
1473 public static List<GlyphVector> getGlyphVectorsBidi(String string, Font font, FontRenderContext frc) {
1474 List<GlyphVector> gvs = new ArrayList<>();
1475 Bidi bidi = new Bidi(string, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
1476 byte[] levels = new byte[bidi.getRunCount()];
1477 DirectionString[] dirStrings = new DirectionString[levels.length];
1478 for (int i = 0; i < levels.length; ++i) {
1479 levels[i] = (byte) bidi.getRunLevel(i);
1480 String substr = string.substring(bidi.getRunStart(i), bidi.getRunLimit(i));
1481 int dir = levels[i] % 2 == 0 ? Bidi.DIRECTION_LEFT_TO_RIGHT : Bidi.DIRECTION_RIGHT_TO_LEFT;
1482 dirStrings[i] = new DirectionString(dir, substr);
1483 }
1484 Bidi.reorderVisually(levels, 0, dirStrings, 0, levels.length);
1485 for (int i = 0; i < dirStrings.length; ++i) {
1486 char[] chars = dirStrings[i].str.toCharArray();
1487 gvs.add(font.layoutGlyphVector(frc, chars, 0, chars.length, dirStrings[i].direction));
1488 }
1489 return gvs;
1490 }
1491
1492 /**
1493 * Sets {@code AccessibleObject}(s) accessible.
1494 * @param objects objects
1495 * @see AccessibleObject#setAccessible
1496 * @since 10223
1497 */
1498 public static void setObjectsAccessible(final AccessibleObject... objects) {
1499 if (objects != null && objects.length > 0) {
1500 AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
1501 for (AccessibleObject o : objects) {
1502 o.setAccessible(true);
1503 }
1504 return null;
1505 });
1506 }
1507 }
1508
1509 /**
1510 * Clamp a value to the given range
1511 * @param val The value
1512 * @param min minimum value
1513 * @param max maximum value
1514 * @return the value
1515 * @throws IllegalArgumentException if {@code min > max}
1516 * @since 10805
1517 */
1518 public static double clamp(double val, double min, double max) {
1519 if (min > max) {
1520 throw new IllegalArgumentException(MessageFormat.format("Parameter min ({0}) cannot be greater than max ({1})", min, max));
1521 } else if (val < min) {
1522 return min;
1523 } else if (val > max) {
1524 return max;
1525 } else {
1526 return val;
1527 }
1528 }
1529
1530 /**
1531 * Clamp a integer value to the given range
1532 * @param val The value
1533 * @param min minimum value
1534 * @param max maximum value
1535 * @return the value
1536 * @throws IllegalArgumentException if {@code min > max}
1537 * @since 11055
1538 */
1539 public static int clamp(int val, int min, int max) {
1540 if (min > max) {
1541 throw new IllegalArgumentException(MessageFormat.format("Parameter min ({0}) cannot be greater than max ({1})", min, max));
1542 } else if (val < min) {
1543 return min;
1544 } else if (val > max) {
1545 return max;
1546 } else {
1547 return val;
1548 }
1549 }
1550
1551 /**
1552 * Convert angle from radians to degrees.
1553 *
1554 * Replacement for {@link Math#toDegrees(double)} to match the Java 9
1555 * version of that method. (Can be removed when JOSM support for Java 8 ends.)
1556 * Only relevant in relation to ProjectionRegressionTest.
1557 * @param angleRad an angle in radians
1558 * @return the same angle in degrees
1559 * @see <a href="https://josm.openstreetmap.de/ticket/11889">#11889</a>
1560 * @since 12013
1561 */
1562 public static double toDegrees(double angleRad) {
1563 return angleRad * TO_DEGREES;
1564 }
1565
1566 /**
1567 * Convert angle from degrees to radians.
1568 *
1569 * Replacement for {@link Math#toRadians(double)} to match the Java 9
1570 * version of that method. (Can be removed when JOSM support for Java 8 ends.)
1571 * Only relevant in relation to ProjectionRegressionTest.
1572 * @param angleDeg an angle in degrees
1573 * @return the same angle in radians
1574 * @see <a href="https://josm.openstreetmap.de/ticket/11889">#11889</a>
1575 * @since 12013
1576 */
1577 public static double toRadians(double angleDeg) {
1578 return angleDeg * TO_RADIANS;
1579 }
1580
1581 /**
1582 * Returns the Java version as an int value.
1583 * @return the Java version as an int value (8, 9, etc.)
1584 * @since 12130
1585 */
1586 public static int getJavaVersion() {
1587 String version = System.getProperty("java.version");
1588 if (version.startsWith("1.")) {
1589 version = version.substring(2);
1590 }
1591 // Allow these formats:
1592 // 1.8.0_72-ea
1593 // 9-ea
1594 // 9
1595 // 9.0.1
1596 int dotPos = version.indexOf('.');
1597 int dashPos = version.indexOf('-');
1598 return Integer.parseInt(version.substring(0,
1599 dotPos > -1 ? dotPos : dashPos > -1 ? dashPos : 1));
1600 }
1601
1602 /**
1603 * Returns the Java update as an int value.
1604 * @return the Java update as an int value (121, 131, etc.)
1605 * @since 12217
1606 */
1607 public static int getJavaUpdate() {
1608 String version = System.getProperty("java.version");
1609 if (version.startsWith("1.")) {
1610 version = version.substring(2);
1611 }
1612 // Allow these formats:
1613 // 1.8.0_72-ea
1614 // 9-ea
1615 // 9
1616 // 9.0.1
1617 int undePos = version.indexOf('_');
1618 int dashPos = version.indexOf('-');
1619 if (undePos > -1) {
1620 return Integer.parseInt(version.substring(undePos + 1,
1621 dashPos > -1 ? dashPos : version.length()));
1622 }
1623 int firstDotPos = version.indexOf('.');
1624 int lastDotPos = version.lastIndexOf('.');
1625 if (firstDotPos == lastDotPos) {
1626 return 0;
1627 }
1628 return firstDotPos > -1 ? Integer.parseInt(version.substring(firstDotPos + 1,
1629 lastDotPos > -1 ? lastDotPos : version.length())) : 0;
1630 }
1631
1632 /**
1633 * Returns the Java build number as an int value.
1634 * @return the Java build number as an int value (0, 1, etc.)
1635 * @since 12217
1636 */
1637 public static int getJavaBuild() {
1638 String version = System.getProperty("java.runtime.version");
1639 int bPos = version.indexOf('b');
1640 int pPos = version.indexOf('+');
1641 try {
1642 return Integer.parseInt(version.substring(bPos > -1 ? bPos + 1 : pPos + 1, version.length()));
1643 } catch (NumberFormatException e) {
1644 Logging.trace(e);
1645 return 0;
1646 }
1647 }
1648
1649 /**
1650 * Returns the JRE expiration date.
1651 * @return the JRE expiration date, or null
1652 * @since 12219
1653 */
1654 public static Date getJavaExpirationDate() {
1655 try {
1656 Object value = null;
1657 Class<?> c = Class.forName("com.sun.deploy.config.BuiltInProperties");
1658 try {
1659 value = c.getDeclaredField("JRE_EXPIRATION_DATE").get(null);
1660 } catch (NoSuchFieldException e) {
1661 // Field is gone with Java 9, there's a method instead
1662 Logging.trace(e);
1663 value = c.getDeclaredMethod("getProperty", String.class).invoke(null, "JRE_EXPIRATION_DATE");
1664 }
1665 if (value instanceof String) {
1666 return DateFormat.getDateInstance(3, Locale.US).parse((String) value);
1667 }
1668 } catch (IllegalArgumentException | ReflectiveOperationException | SecurityException | ParseException e) {
1669 Logging.debug(e);
1670 }
1671 return null;
1672 }
1673
1674 /**
1675 * Returns the latest version of Java, from Oracle website.
1676 * @return the latest version of Java, from Oracle website
1677 * @since 12219
1678 */
1679 public static String getJavaLatestVersion() {
1680 try {
1681 return HttpClient.create(
1682 new URL(Main.pref.get("java.baseline.version.url", "http://javadl-esd-secure.oracle.com/update/baseline.version")))
1683 .connect().fetchContent().split("\n")[0];
1684 } catch (IOException e) {
1685 Logging.error(e);
1686 }
1687 return null;
1688 }
1689
1690 /**
1691 * Get a function that converts an object to a singleton stream of a certain
1692 * class (or null if the object cannot be cast to that class).
1693 *
1694 * Can be useful in relation with streams, but be aware of the performance
1695 * implications of creating a stream for each element.
1696 * @param <T> type of the objects to convert
1697 * @param <U> type of the elements in the resulting stream
1698 * @param klass the class U
1699 * @return function converting an object to a singleton stream or null
1700 * @since 12594
1701 */
1702 public static <T, U> Function<T, Stream<U>> castToStream(Class<U> klass) {
1703 return x -> klass.isInstance(x) ? Stream.of(klass.cast(x)) : null;
1704 }
1705
1706 /**
1707 * Helper method to replace the "<code>instanceof</code>-check and cast" pattern.
1708 * Checks if an object is instance of class T and performs an action if that
1709 * is the case.
1710 * Syntactic sugar to avoid typing the class name two times, when one time
1711 * would suffice.
1712 * @param <T> the type for the instanceof check and cast
1713 * @param o the object to check and cast
1714 * @param klass the class T
1715 * @param consumer action to take when o is and instance of T
1716 * @since 12604
1717 */
1718 @SuppressWarnings("unchecked")
1719 public static <T> void instanceOfThen(Object o, Class<T> klass, Consumer<? super T> consumer) {
1720 if (klass.isInstance(o)) {
1721 consumer.accept((T) o);
1722 }
1723 }
1724}
Note: See TracBrowser for help on using the repository browser.