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

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

sonar - squid:S1126 - Return of boolean expressions should not be wrapped into an "if-then-else" statement

  • Property svn:eol-style set to native
File size: 56.3 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import static org.openstreetmap.josm.tools.I18n.marktr;
5import static org.openstreetmap.josm.tools.I18n.tr;
6import static org.openstreetmap.josm.tools.I18n.trn;
7
8import java.awt.Color;
9import java.awt.Font;
10import java.awt.font.FontRenderContext;
11import java.awt.font.GlyphVector;
12import java.io.BufferedReader;
13import java.io.ByteArrayOutputStream;
14import java.io.Closeable;
15import java.io.File;
16import java.io.IOException;
17import java.io.InputStream;
18import java.io.InputStreamReader;
19import java.io.UnsupportedEncodingException;
20import java.lang.reflect.AccessibleObject;
21import java.net.MalformedURLException;
22import java.net.URL;
23import java.net.URLDecoder;
24import java.net.URLEncoder;
25import java.nio.charset.StandardCharsets;
26import java.nio.file.Files;
27import java.nio.file.Path;
28import java.nio.file.StandardCopyOption;
29import java.security.AccessController;
30import java.security.MessageDigest;
31import java.security.NoSuchAlgorithmException;
32import java.security.PrivilegedAction;
33import java.text.Bidi;
34import java.text.MessageFormat;
35import java.util.AbstractCollection;
36import java.util.AbstractList;
37import java.util.ArrayList;
38import java.util.Arrays;
39import java.util.Collection;
40import java.util.Collections;
41import java.util.Iterator;
42import java.util.List;
43import java.util.Locale;
44import java.util.concurrent.Executor;
45import java.util.concurrent.ForkJoinPool;
46import java.util.concurrent.ForkJoinWorkerThread;
47import java.util.concurrent.ThreadFactory;
48import java.util.concurrent.TimeUnit;
49import java.util.concurrent.atomic.AtomicLong;
50import java.util.function.Function;
51import java.util.function.Predicate;
52import java.util.regex.Matcher;
53import java.util.regex.Pattern;
54import java.util.zip.GZIPInputStream;
55import java.util.zip.ZipEntry;
56import java.util.zip.ZipFile;
57import java.util.zip.ZipInputStream;
58
59import javax.xml.XMLConstants;
60import javax.xml.parsers.DocumentBuilder;
61import javax.xml.parsers.DocumentBuilderFactory;
62import javax.xml.parsers.ParserConfigurationException;
63import javax.xml.parsers.SAXParser;
64import javax.xml.parsers.SAXParserFactory;
65
66import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
67import org.openstreetmap.josm.Main;
68import org.w3c.dom.Document;
69import org.xml.sax.InputSource;
70import org.xml.sax.SAXException;
71import org.xml.sax.helpers.DefaultHandler;
72
73/**
74 * Basic utils, that can be useful in different parts of the program.
75 */
76public final class Utils {
77
78 /** Pattern matching white spaces */
79 public static final Pattern WHITE_SPACES_PATTERN = Pattern.compile("\\s+");
80
81 private static final long MILLIS_OF_SECOND = TimeUnit.SECONDS.toMillis(1);
82 private static final long MILLIS_OF_MINUTE = TimeUnit.MINUTES.toMillis(1);
83 private static final long MILLIS_OF_HOUR = TimeUnit.HOURS.toMillis(1);
84 private static final long MILLIS_OF_DAY = TimeUnit.DAYS.toMillis(1);
85
86 /**
87 * A list of all characters allowed in URLs
88 */
89 public static final String URL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=%";
90
91 private static final char[] DEFAULT_STRIP = {'\u200B', '\uFEFF'};
92
93 private static final String[] SIZE_UNITS = {"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
94
95 private Utils() {
96 // Hide default constructor for utils classes
97 }
98
99 /**
100 * Checks if an item that is an instance of clazz exists in the collection
101 * @param <T> The collection type.
102 * @param collection The collection
103 * @param clazz The class to search for.
104 * @return <code>true</code> if that item exists in the collection.
105 */
106 public static <T> boolean exists(Iterable<T> collection, Class<? extends T> clazz) {
107 CheckParameterUtil.ensureParameterNotNull(clazz, "clazz");
108 return StreamUtils.toStream(collection).anyMatch(clazz::isInstance);
109 }
110
111 /**
112 * Finds the first item in the iterable for which the predicate matches.
113 * @param <T> The iterable type.
114 * @param collection The iterable to search in.
115 * @param predicate The predicate to match
116 * @return the item or <code>null</code> if there was not match.
117 */
118 public static <T> T find(Iterable<? extends T> collection, Predicate<? super T> predicate) {
119 for (T item : collection) {
120 if (predicate.test(item)) {
121 return item;
122 }
123 }
124 return null;
125 }
126
127 /**
128 * Finds the first item in the iterable which is of the given type.
129 * @param <T> The iterable type.
130 * @param collection The iterable to search in.
131 * @param clazz The class to search for.
132 * @return the item or <code>null</code> if there was not match.
133 */
134 @SuppressWarnings("unchecked")
135 public static <T> T find(Iterable<? extends Object> collection, Class<? extends T> clazz) {
136 CheckParameterUtil.ensureParameterNotNull(clazz, "clazz");
137 return (T) find(collection, clazz::isInstance);
138 }
139
140 /**
141 * Returns the first element from {@code items} which is non-null, or null if all elements are null.
142 * @param <T> type of items
143 * @param items the items to look for
144 * @return first non-null item if there is one
145 */
146 @SafeVarargs
147 public static <T> T firstNonNull(T... items) {
148 for (T i : items) {
149 if (i != null) {
150 return i;
151 }
152 }
153 return null;
154 }
155
156 /**
157 * Filter a collection by (sub)class.
158 * This is an efficient read-only implementation.
159 * @param <S> Super type of items
160 * @param <T> type of items
161 * @param collection the collection
162 * @param clazz the (sub)class
163 * @return a read-only filtered collection
164 */
165 public static <S, T extends S> SubclassFilteredCollection<S, T> filteredCollection(Collection<S> collection, final Class<T> clazz) {
166 CheckParameterUtil.ensureParameterNotNull(clazz, "clazz");
167 return new SubclassFilteredCollection<>(collection, clazz::isInstance);
168 }
169
170 /**
171 * Find the index of the first item that matches the predicate.
172 * @param <T> The iterable type
173 * @param collection The iterable to iterate over.
174 * @param predicate The predicate to search for.
175 * @return The index of the first item or -1 if none was found.
176 */
177 public static <T> int indexOf(Iterable<? extends T> collection, Predicate<? super T> predicate) {
178 int i = 0;
179 for (T item : collection) {
180 if (predicate.test(item))
181 return i;
182 i++;
183 }
184 return -1;
185 }
186
187 /**
188 * Ensures a logical condition is met. Otherwise throws an assertion error.
189 * @param condition the condition to be met
190 * @param message Formatted error message to raise if condition is not met
191 * @param data Message parameters, optional
192 * @throws AssertionError if the condition is not met
193 */
194 public static void ensure(boolean condition, String message, Object...data) {
195 if (!condition)
196 throw new AssertionError(
197 MessageFormat.format(message, data)
198 );
199 }
200
201 /**
202 * Return the modulus in the range [0, n)
203 * @param a dividend
204 * @param n divisor
205 * @return modulo (remainder of the Euclidian division of a by n)
206 */
207 public static int mod(int a, int n) {
208 if (n <= 0)
209 throw new IllegalArgumentException("n must be <= 0 but is "+n);
210 int res = a % n;
211 if (res < 0) {
212 res += n;
213 }
214 return res;
215 }
216
217 /**
218 * Joins a list of strings (or objects that can be converted to string via
219 * Object.toString()) into a single string with fields separated by sep.
220 * @param sep the separator
221 * @param values collection of objects, null is converted to the
222 * empty string
223 * @return null if values is null. The joined string otherwise.
224 */
225 public static String join(String sep, Collection<?> values) {
226 CheckParameterUtil.ensureParameterNotNull(sep, "sep");
227 if (values == null)
228 return null;
229 StringBuilder s = null;
230 for (Object a : values) {
231 if (a == null) {
232 a = "";
233 }
234 if (s != null) {
235 s.append(sep).append(a);
236 } else {
237 s = new StringBuilder(a.toString());
238 }
239 }
240 return s != null ? s.toString() : "";
241 }
242
243 /**
244 * Converts the given iterable collection as an unordered HTML list.
245 * @param values The iterable collection
246 * @return An unordered HTML list
247 */
248 public static String joinAsHtmlUnorderedList(Iterable<?> values) {
249 return StreamUtils.toStream(values).map(Object::toString).collect(StreamUtils.toHtmlList());
250 }
251
252 /**
253 * convert Color to String
254 * (Color.toString() omits alpha value)
255 * @param c the color
256 * @return the String representation, including alpha
257 */
258 public static String toString(Color c) {
259 if (c == null)
260 return "null";
261 if (c.getAlpha() == 255)
262 return String.format("#%06x", c.getRGB() & 0x00ffffff);
263 else
264 return String.format("#%06x(alpha=%d)", c.getRGB() & 0x00ffffff, c.getAlpha());
265 }
266
267 /**
268 * convert float range 0 &lt;= x &lt;= 1 to integer range 0..255
269 * when dealing with colors and color alpha value
270 * @param val float value between 0 and 1
271 * @return null if val is null, the corresponding int if val is in the
272 * range 0...1. If val is outside that range, return 255
273 */
274 public static Integer colorFloat2int(Float val) {
275 if (val == null)
276 return null;
277 if (val < 0 || val > 1)
278 return 255;
279 return (int) (255f * val + 0.5f);
280 }
281
282 /**
283 * convert integer range 0..255 to float range 0 &lt;= x &lt;= 1
284 * when dealing with colors and color alpha value
285 * @param val integer value
286 * @return corresponding float value in range 0 &lt;= x &lt;= 1
287 */
288 public static Float colorInt2float(Integer val) {
289 if (val == null)
290 return null;
291 if (val < 0 || val > 255)
292 return 1f;
293 return ((float) val) / 255f;
294 }
295
296 /**
297 * Multiply the alpha value of the given color with the factor. The alpha value is clamped to 0..255
298 * @param color The color
299 * @param alphaFactor The factor to multiply alpha with.
300 * @return The new color.
301 * @since 11692
302 */
303 public static Color alphaMultiply(Color color, float alphaFactor) {
304 int alpha = Utils.colorFloat2int(Utils.colorInt2float(color.getAlpha()) * alphaFactor);
305 alpha = clamp(alpha, 0, 255);
306 return new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha);
307 }
308
309 /**
310 * Returns the complementary color of {@code clr}.
311 * @param clr the color to complement
312 * @return the complementary color of {@code clr}
313 */
314 public static Color complement(Color clr) {
315 return new Color(255 - clr.getRed(), 255 - clr.getGreen(), 255 - clr.getBlue(), clr.getAlpha());
316 }
317
318 /**
319 * Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe.
320 * @param <T> type of items
321 * @param array The array to copy
322 * @return A copy of the original array, or {@code null} if {@code array} is null
323 * @since 6221
324 */
325 public static <T> T[] copyArray(T[] array) {
326 if (array != null) {
327 return Arrays.copyOf(array, array.length);
328 }
329 return array;
330 }
331
332 /**
333 * Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe.
334 * @param array The array to copy
335 * @return A copy of the original array, or {@code null} if {@code array} is null
336 * @since 6222
337 */
338 public static char[] copyArray(char ... array) {
339 if (array != null) {
340 return Arrays.copyOf(array, array.length);
341 }
342 return array;
343 }
344
345 /**
346 * Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe.
347 * @param array The array to copy
348 * @return A copy of the original array, or {@code null} if {@code array} is null
349 * @since 7436
350 */
351 public static int[] copyArray(int... array) {
352 if (array != null) {
353 return Arrays.copyOf(array, array.length);
354 }
355 return array;
356 }
357
358 /**
359 * Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe.
360 * @param array The array to copy
361 * @return A copy of the original array, or {@code null} if {@code array} is null
362 * @since 11879
363 */
364 public static byte[] copyArray(byte... array) {
365 if (array != null) {
366 return Arrays.copyOf(array, array.length);
367 }
368 return array;
369 }
370
371 /**
372 * Simple file copy function that will overwrite the target file.
373 * @param in The source file
374 * @param out The destination file
375 * @return the path to the target file
376 * @throws IOException if any I/O error occurs
377 * @throws IllegalArgumentException if {@code in} or {@code out} is {@code null}
378 * @since 7003
379 */
380 public static Path copyFile(File in, File out) throws IOException {
381 CheckParameterUtil.ensureParameterNotNull(in, "in");
382 CheckParameterUtil.ensureParameterNotNull(out, "out");
383 return Files.copy(in.toPath(), out.toPath(), StandardCopyOption.REPLACE_EXISTING);
384 }
385
386 /**
387 * Recursive directory copy function
388 * @param in The source directory
389 * @param out The destination directory
390 * @throws IOException if any I/O error ooccurs
391 * @throws IllegalArgumentException if {@code in} or {@code out} is {@code null}
392 * @since 7835
393 */
394 public static void copyDirectory(File in, File out) throws IOException {
395 CheckParameterUtil.ensureParameterNotNull(in, "in");
396 CheckParameterUtil.ensureParameterNotNull(out, "out");
397 if (!out.exists() && !out.mkdirs()) {
398 Main.warn("Unable to create directory "+out.getPath());
399 }
400 File[] files = in.listFiles();
401 if (files != null) {
402 for (File f : files) {
403 File target = new File(out, f.getName());
404 if (f.isDirectory()) {
405 copyDirectory(f, target);
406 } else {
407 copyFile(f, target);
408 }
409 }
410 }
411 }
412
413 /**
414 * Deletes a directory recursively.
415 * @param path The directory to delete
416 * @return <code>true</code> if and only if the file or directory is
417 * successfully deleted; <code>false</code> otherwise
418 */
419 public static boolean deleteDirectory(File path) {
420 if (path.exists()) {
421 File[] files = path.listFiles();
422 if (files != null) {
423 for (File file : files) {
424 if (file.isDirectory()) {
425 deleteDirectory(file);
426 } else {
427 deleteFile(file);
428 }
429 }
430 }
431 }
432 return path.delete();
433 }
434
435 /**
436 * Deletes a file and log a default warning if the file exists but the deletion fails.
437 * @param file file to delete
438 * @return {@code true} if and only if the file does not exist or is successfully deleted; {@code false} otherwise
439 * @since 10569
440 */
441 public static boolean deleteFileIfExists(File file) {
442 if (file.exists()) {
443 return deleteFile(file);
444 } else {
445 return true;
446 }
447 }
448
449 /**
450 * Deletes a file and log a default warning if the deletion fails.
451 * @param file file to delete
452 * @return {@code true} if and only if the file is successfully deleted; {@code false} otherwise
453 * @since 9296
454 */
455 public static boolean deleteFile(File file) {
456 return deleteFile(file, marktr("Unable to delete file {0}"));
457 }
458
459 /**
460 * Deletes a file and log a configurable warning if the deletion fails.
461 * @param file file to delete
462 * @param warnMsg warning message. It will be translated with {@code tr()}
463 * and must contain a single parameter <code>{0}</code> for the file path
464 * @return {@code true} if and only if the file is successfully deleted; {@code false} otherwise
465 * @since 9296
466 */
467 public static boolean deleteFile(File file, String warnMsg) {
468 boolean result = file.delete();
469 if (!result) {
470 Main.warn(tr(warnMsg, file.getPath()));
471 }
472 return result;
473 }
474
475 /**
476 * Creates a directory and log a default warning if the creation fails.
477 * @param dir directory to create
478 * @return {@code true} if and only if the directory is successfully created; {@code false} otherwise
479 * @since 9645
480 */
481 public static boolean mkDirs(File dir) {
482 return mkDirs(dir, marktr("Unable to create directory {0}"));
483 }
484
485 /**
486 * Creates a directory and log a configurable warning if the creation fails.
487 * @param dir directory to create
488 * @param warnMsg warning message. It will be translated with {@code tr()}
489 * and must contain a single parameter <code>{0}</code> for the directory path
490 * @return {@code true} if and only if the directory is successfully created; {@code false} otherwise
491 * @since 9645
492 */
493 public static boolean mkDirs(File dir, String warnMsg) {
494 boolean result = dir.mkdirs();
495 if (!result) {
496 Main.warn(tr(warnMsg, dir.getPath()));
497 }
498 return result;
499 }
500
501 /**
502 * <p>Utility method for closing a {@link java.io.Closeable} object.</p>
503 *
504 * @param c the closeable object. May be null.
505 */
506 public static void close(Closeable c) {
507 if (c == null) return;
508 try {
509 c.close();
510 } catch (IOException e) {
511 Main.warn(e);
512 }
513 }
514
515 /**
516 * <p>Utility method for closing a {@link java.util.zip.ZipFile}.</p>
517 *
518 * @param zip the zip file. May be null.
519 */
520 public static void close(ZipFile zip) {
521 close((Closeable) zip);
522 }
523
524 /**
525 * Converts the given file to its URL.
526 * @param f The file to get URL from
527 * @return The URL of the given file, or {@code null} if not possible.
528 * @since 6615
529 */
530 public static URL fileToURL(File f) {
531 if (f != null) {
532 try {
533 return f.toURI().toURL();
534 } catch (MalformedURLException ex) {
535 Main.error("Unable to convert filename " + f.getAbsolutePath() + " to URL");
536 }
537 }
538 return null;
539 }
540
541 private static final double EPSILON = 1e-11;
542
543 /**
544 * Determines if the two given double values are equal (their delta being smaller than a fixed epsilon)
545 * @param a The first double value to compare
546 * @param b The second double value to compare
547 * @return {@code true} if {@code abs(a - b) <= 1e-11}, {@code false} otherwise
548 */
549 public static boolean equalsEpsilon(double a, double b) {
550 return Math.abs(a - b) <= EPSILON;
551 }
552
553 /**
554 * Calculate MD5 hash of a string and output in hexadecimal format.
555 * @param data arbitrary String
556 * @return MD5 hash of data, string of length 32 with characters in range [0-9a-f]
557 */
558 public static String md5Hex(String data) {
559 MessageDigest md = null;
560 try {
561 md = MessageDigest.getInstance("MD5");
562 } catch (NoSuchAlgorithmException e) {
563 throw new JosmRuntimeException(e);
564 }
565 byte[] byteData = data.getBytes(StandardCharsets.UTF_8);
566 byte[] byteDigest = md.digest(byteData);
567 return toHexString(byteDigest);
568 }
569
570 private static final char[] HEX_ARRAY = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
571
572 /**
573 * Converts a byte array to a string of hexadecimal characters.
574 * Preserves leading zeros, so the size of the output string is always twice
575 * the number of input bytes.
576 * @param bytes the byte array
577 * @return hexadecimal representation
578 */
579 public static String toHexString(byte[] bytes) {
580
581 if (bytes == null) {
582 return "";
583 }
584
585 final int len = bytes.length;
586 if (len == 0) {
587 return "";
588 }
589
590 char[] hexChars = new char[len * 2];
591 for (int i = 0, j = 0; i < len; i++) {
592 final int v = bytes[i];
593 hexChars[j++] = HEX_ARRAY[(v & 0xf0) >> 4];
594 hexChars[j++] = HEX_ARRAY[v & 0xf];
595 }
596 return new String(hexChars);
597 }
598
599 /**
600 * Topological sort.
601 * @param <T> type of items
602 *
603 * @param dependencies contains mappings (key -&gt; value). In the final list of sorted objects, the key will come
604 * after the value. (In other words, the key depends on the value(s).)
605 * There must not be cyclic dependencies.
606 * @return the list of sorted objects
607 */
608 public static <T> List<T> topologicalSort(final MultiMap<T, T> dependencies) {
609 MultiMap<T, T> deps = new MultiMap<>();
610 for (T key : dependencies.keySet()) {
611 deps.putVoid(key);
612 for (T val : dependencies.get(key)) {
613 deps.putVoid(val);
614 deps.put(key, val);
615 }
616 }
617
618 int size = deps.size();
619 List<T> sorted = new ArrayList<>();
620 for (int i = 0; i < size; ++i) {
621 T parentless = null;
622 for (T key : deps.keySet()) {
623 if (deps.get(key).isEmpty()) {
624 parentless = key;
625 break;
626 }
627 }
628 if (parentless == null) throw new JosmRuntimeException("parentless");
629 sorted.add(parentless);
630 deps.remove(parentless);
631 for (T key : deps.keySet()) {
632 deps.remove(key, parentless);
633 }
634 }
635 if (sorted.size() != size) throw new JosmRuntimeException("Wrong size");
636 return sorted;
637 }
638
639 /**
640 * Replaces some HTML reserved characters (&lt;, &gt; and &amp;) by their equivalent entity (&amp;lt;, &amp;gt; and &amp;amp;);
641 * @param s The unescaped string
642 * @return The escaped string
643 */
644 public static String escapeReservedCharactersHTML(String s) {
645 return s == null ? "" : s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;");
646 }
647
648 /**
649 * Transforms the collection {@code c} into an unmodifiable collection and
650 * applies the {@link Function} {@code f} on each element upon access.
651 * @param <A> class of input collection
652 * @param <B> class of transformed collection
653 * @param c a collection
654 * @param f a function that transforms objects of {@code A} to objects of {@code B}
655 * @return the transformed unmodifiable collection
656 */
657 public static <A, B> Collection<B> transform(final Collection<? extends A> c, final Function<A, B> f) {
658 return new AbstractCollection<B>() {
659
660 @Override
661 public int size() {
662 return c.size();
663 }
664
665 @Override
666 public Iterator<B> iterator() {
667 return new Iterator<B>() {
668
669 private Iterator<? extends A> it = c.iterator();
670
671 @Override
672 public boolean hasNext() {
673 return it.hasNext();
674 }
675
676 @Override
677 public B next() {
678 return f.apply(it.next());
679 }
680
681 @Override
682 public void remove() {
683 throw new UnsupportedOperationException();
684 }
685 };
686 }
687 };
688 }
689
690 /**
691 * Transforms the list {@code l} into an unmodifiable list and
692 * applies the {@link Function} {@code f} on each element upon access.
693 * @param <A> class of input collection
694 * @param <B> class of transformed collection
695 * @param l a collection
696 * @param f a function that transforms objects of {@code A} to objects of {@code B}
697 * @return the transformed unmodifiable list
698 */
699 public static <A, B> List<B> transform(final List<? extends A> l, final Function<A, B> f) {
700 return new AbstractList<B>() {
701
702 @Override
703 public int size() {
704 return l.size();
705 }
706
707 @Override
708 public B get(int index) {
709 return f.apply(l.get(index));
710 }
711 };
712 }
713
714 /**
715 * Returns a Bzip2 input stream wrapping given input stream.
716 * @param in The raw input stream
717 * @return a Bzip2 input stream wrapping given input stream, or {@code null} if {@code in} is {@code null}
718 * @throws IOException if the given input stream does not contain valid BZ2 header
719 * @since 7867
720 */
721 public static BZip2CompressorInputStream getBZip2InputStream(InputStream in) throws IOException {
722 if (in == null) {
723 return null;
724 }
725 return new BZip2CompressorInputStream(in, /* see #9537 */ true);
726 }
727
728 /**
729 * Returns a Gzip input stream wrapping given input stream.
730 * @param in The raw input stream
731 * @return a Gzip input stream wrapping given input stream, or {@code null} if {@code in} is {@code null}
732 * @throws IOException if an I/O error has occurred
733 * @since 7119
734 */
735 public static GZIPInputStream getGZipInputStream(InputStream in) throws IOException {
736 if (in == null) {
737 return null;
738 }
739 return new GZIPInputStream(in);
740 }
741
742 /**
743 * Returns a Zip input stream wrapping given input stream.
744 * @param in The raw input stream
745 * @return a Zip input stream wrapping given input stream, or {@code null} if {@code in} is {@code null}
746 * @throws IOException if an I/O error has occurred
747 * @since 7119
748 */
749 public static ZipInputStream getZipInputStream(InputStream in) throws IOException {
750 if (in == null) {
751 return null;
752 }
753 ZipInputStream zis = new ZipInputStream(in, StandardCharsets.UTF_8);
754 // Positions the stream at the beginning of first entry
755 ZipEntry ze = zis.getNextEntry();
756 if (ze != null && Main.isDebugEnabled()) {
757 Main.debug("Zip entry: "+ze.getName());
758 }
759 return zis;
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 (Main.isDebugEnabled()) {
872 Main.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 Main.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 Main.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 (Main.isDebugEnabled()) {
1273 if (!key.toLowerCase(Locale.ENGLISH).contains("password")) {
1274 Main.debug("System property '" + key + "' set to '" + value + "'. Old value was '" + old + '\'');
1275 } else {
1276 Main.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 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1289 * @since 10404
1290 */
1291 public static DocumentBuilder newSafeDOMBuilder() throws ParserConfigurationException {
1292 DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
1293 builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
1294 builderFactory.setNamespaceAware(true);
1295 builderFactory.setValidating(false);
1296 return builderFactory.newDocumentBuilder();
1297 }
1298
1299 /**
1300 * Parse the content given {@link InputStream} as XML.
1301 * This method uses a secure DOM builder, supporting XML namespaces.
1302 *
1303 * @param is The InputStream containing the content to be parsed.
1304 * @return the result DOM document
1305 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1306 * @throws IOException if any IO errors occur.
1307 * @throws SAXException for SAX errors.
1308 * @since 10404
1309 */
1310 public static Document parseSafeDOM(InputStream is) throws ParserConfigurationException, IOException, SAXException {
1311 long start = System.currentTimeMillis();
1312 if (Main.isDebugEnabled()) {
1313 Main.debug("Starting DOM parsing of " + is);
1314 }
1315 Document result = newSafeDOMBuilder().parse(is);
1316 if (Main.isDebugEnabled()) {
1317 Main.debug("DOM parsing done in " + getDurationString(System.currentTimeMillis() - start));
1318 }
1319 return result;
1320 }
1321
1322 /**
1323 * Returns a new secure SAX parser, supporting XML namespaces.
1324 * @return a new secure SAX parser, supporting XML namespaces
1325 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1326 * @throws SAXException for SAX errors.
1327 * @since 8287
1328 */
1329 public static SAXParser newSafeSAXParser() throws ParserConfigurationException, SAXException {
1330 SAXParserFactory parserFactory = SAXParserFactory.newInstance();
1331 parserFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
1332 parserFactory.setNamespaceAware(true);
1333 return parserFactory.newSAXParser();
1334 }
1335
1336 /**
1337 * Parse the content given {@link org.xml.sax.InputSource} as XML using the specified {@link org.xml.sax.helpers.DefaultHandler}.
1338 * This method uses a secure SAX parser, supporting XML namespaces.
1339 *
1340 * @param is The InputSource containing the content to be parsed.
1341 * @param dh The SAX DefaultHandler to use.
1342 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1343 * @throws SAXException for SAX errors.
1344 * @throws IOException if any IO errors occur.
1345 * @since 8347
1346 */
1347 public static void parseSafeSAX(InputSource is, DefaultHandler dh) throws ParserConfigurationException, SAXException, IOException {
1348 long start = System.currentTimeMillis();
1349 if (Main.isDebugEnabled()) {
1350 Main.debug("Starting SAX parsing of " + is + " using " + dh);
1351 }
1352 newSafeSAXParser().parse(is, dh);
1353 if (Main.isDebugEnabled()) {
1354 Main.debug("SAX parsing done in " + getDurationString(System.currentTimeMillis() - start));
1355 }
1356 }
1357
1358 /**
1359 * Determines if the filename has one of the given extensions, in a robust manner.
1360 * The comparison is case and locale insensitive.
1361 * @param filename The file name
1362 * @param extensions The list of extensions to look for (without dot)
1363 * @return {@code true} if the filename has one of the given extensions
1364 * @since 8404
1365 */
1366 public static boolean hasExtension(String filename, String... extensions) {
1367 String name = filename.toLowerCase(Locale.ENGLISH).replace("?format=raw", "");
1368 for (String ext : extensions) {
1369 if (name.endsWith('.' + ext.toLowerCase(Locale.ENGLISH)))
1370 return true;
1371 }
1372 return false;
1373 }
1374
1375 /**
1376 * Determines if the file's name has one of the given extensions, in a robust manner.
1377 * The comparison is case and locale insensitive.
1378 * @param file The file
1379 * @param extensions The list of extensions to look for (without dot)
1380 * @return {@code true} if the file's name has one of the given extensions
1381 * @since 8404
1382 */
1383 public static boolean hasExtension(File file, String... extensions) {
1384 return hasExtension(file.getName(), extensions);
1385 }
1386
1387 /**
1388 * Reads the input stream and closes the stream at the end of processing (regardless if an exception was thrown)
1389 *
1390 * @param stream input stream
1391 * @return byte array of data in input stream (empty if stream is null)
1392 * @throws IOException if any I/O error occurs
1393 */
1394 public static byte[] readBytesFromStream(InputStream stream) throws IOException {
1395 if (stream == null) {
1396 return new byte[0];
1397 }
1398 try {
1399 ByteArrayOutputStream bout = new ByteArrayOutputStream(stream.available());
1400 byte[] buffer = new byte[2048];
1401 boolean finished = false;
1402 do {
1403 int read = stream.read(buffer);
1404 if (read >= 0) {
1405 bout.write(buffer, 0, read);
1406 } else {
1407 finished = true;
1408 }
1409 } while (!finished);
1410 if (bout.size() == 0)
1411 return new byte[0];
1412 return bout.toByteArray();
1413 } finally {
1414 stream.close();
1415 }
1416 }
1417
1418 /**
1419 * Returns the initial capacity to pass to the HashMap / HashSet constructor
1420 * when it is initialized with a known number of entries.
1421 *
1422 * When a HashMap is filled with entries, the underlying array is copied over
1423 * to a larger one multiple times. To avoid this process when the number of
1424 * entries is known in advance, the initial capacity of the array can be
1425 * given to the HashMap constructor. This method returns a suitable value
1426 * that avoids rehashing but doesn't waste memory.
1427 * @param nEntries the number of entries expected
1428 * @param loadFactor the load factor
1429 * @return the initial capacity for the HashMap constructor
1430 */
1431 public static int hashMapInitialCapacity(int nEntries, double loadFactor) {
1432 return (int) Math.ceil(nEntries / loadFactor);
1433 }
1434
1435 /**
1436 * Returns the initial capacity to pass to the HashMap / HashSet constructor
1437 * when it is initialized with a known number of entries.
1438 *
1439 * When a HashMap is filled with entries, the underlying array is copied over
1440 * to a larger one multiple times. To avoid this process when the number of
1441 * entries is known in advance, the initial capacity of the array can be
1442 * given to the HashMap constructor. This method returns a suitable value
1443 * that avoids rehashing but doesn't waste memory.
1444 *
1445 * Assumes default load factor (0.75).
1446 * @param nEntries the number of entries expected
1447 * @return the initial capacity for the HashMap constructor
1448 */
1449 public static int hashMapInitialCapacity(int nEntries) {
1450 return hashMapInitialCapacity(nEntries, 0.75d);
1451 }
1452
1453 /**
1454 * Utility class to save a string along with its rendering direction
1455 * (left-to-right or right-to-left).
1456 */
1457 private static class DirectionString {
1458 public final int direction;
1459 public final String str;
1460
1461 DirectionString(int direction, String str) {
1462 this.direction = direction;
1463 this.str = str;
1464 }
1465 }
1466
1467 /**
1468 * Convert a string to a list of {@link GlyphVector}s. The string may contain
1469 * bi-directional text. The result will be in correct visual order.
1470 * Each element of the resulting list corresponds to one section of the
1471 * string with consistent writing direction (left-to-right or right-to-left).
1472 *
1473 * @param string the string to render
1474 * @param font the font
1475 * @param frc a FontRenderContext object
1476 * @return a list of GlyphVectors
1477 */
1478 public static List<GlyphVector> getGlyphVectorsBidi(String string, Font font, FontRenderContext frc) {
1479 List<GlyphVector> gvs = new ArrayList<>();
1480 Bidi bidi = new Bidi(string, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
1481 byte[] levels = new byte[bidi.getRunCount()];
1482 DirectionString[] dirStrings = new DirectionString[levels.length];
1483 for (int i = 0; i < levels.length; ++i) {
1484 levels[i] = (byte) bidi.getRunLevel(i);
1485 String substr = string.substring(bidi.getRunStart(i), bidi.getRunLimit(i));
1486 int dir = levels[i] % 2 == 0 ? Bidi.DIRECTION_LEFT_TO_RIGHT : Bidi.DIRECTION_RIGHT_TO_LEFT;
1487 dirStrings[i] = new DirectionString(dir, substr);
1488 }
1489 Bidi.reorderVisually(levels, 0, dirStrings, 0, levels.length);
1490 for (int i = 0; i < dirStrings.length; ++i) {
1491 char[] chars = dirStrings[i].str.toCharArray();
1492 gvs.add(font.layoutGlyphVector(frc, chars, 0, chars.length, dirStrings[i].direction));
1493 }
1494 return gvs;
1495 }
1496
1497 /**
1498 * Sets {@code AccessibleObject}(s) accessible.
1499 * @param objects objects
1500 * @see AccessibleObject#setAccessible
1501 * @since 10223
1502 */
1503 public static void setObjectsAccessible(final AccessibleObject ... objects) {
1504 if (objects != null && objects.length > 0) {
1505 AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
1506 for (AccessibleObject o : objects) {
1507 o.setAccessible(true);
1508 }
1509 return null;
1510 });
1511 }
1512 }
1513
1514 /**
1515 * Clamp a value to the given range
1516 * @param val The value
1517 * @param min minimum value
1518 * @param max maximum value
1519 * @return the value
1520 * @throws IllegalArgumentException if {@code min > max}
1521 * @since 10805
1522 */
1523 public static double clamp(double val, double min, double max) {
1524 if (min > max) {
1525 throw new IllegalArgumentException(MessageFormat.format("Parameter min ({0}) cannot be greater than max ({1})", min, max));
1526 } else if (val < min) {
1527 return min;
1528 } else if (val > max) {
1529 return max;
1530 } else {
1531 return val;
1532 }
1533 }
1534
1535 /**
1536 * Clamp a integer value to the given range
1537 * @param val The value
1538 * @param min minimum value
1539 * @param max maximum value
1540 * @return the value
1541 * @throws IllegalArgumentException if {@code min > max}
1542 * @since 11055
1543 */
1544 public static int clamp(int val, int min, int max) {
1545 if (min > max) {
1546 throw new IllegalArgumentException(MessageFormat.format("Parameter min ({0}) cannot be greater than max ({1})", min, max));
1547 } else if (val < min) {
1548 return min;
1549 } else if (val > max) {
1550 return max;
1551 } else {
1552 return val;
1553 }
1554 }
1555}
Note: See TracBrowser for help on using the repository browser.