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

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

checkstyle - NoWhiteSpaceBefore ...

  • Property svn:eol-style set to native
File size: 55.9 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 * Simple file copy function that will overwrite the target file.
360 * @param in The source file
361 * @param out The destination file
362 * @return the path to the target file
363 * @throws IOException if any I/O error occurs
364 * @throws IllegalArgumentException if {@code in} or {@code out} is {@code null}
365 * @since 7003
366 */
367 public static Path copyFile(File in, File out) throws IOException {
368 CheckParameterUtil.ensureParameterNotNull(in, "in");
369 CheckParameterUtil.ensureParameterNotNull(out, "out");
370 return Files.copy(in.toPath(), out.toPath(), StandardCopyOption.REPLACE_EXISTING);
371 }
372
373 /**
374 * Recursive directory copy function
375 * @param in The source directory
376 * @param out The destination directory
377 * @throws IOException if any I/O error ooccurs
378 * @throws IllegalArgumentException if {@code in} or {@code out} is {@code null}
379 * @since 7835
380 */
381 public static void copyDirectory(File in, File out) throws IOException {
382 CheckParameterUtil.ensureParameterNotNull(in, "in");
383 CheckParameterUtil.ensureParameterNotNull(out, "out");
384 if (!out.exists() && !out.mkdirs()) {
385 Main.warn("Unable to create directory "+out.getPath());
386 }
387 File[] files = in.listFiles();
388 if (files != null) {
389 for (File f : files) {
390 File target = new File(out, f.getName());
391 if (f.isDirectory()) {
392 copyDirectory(f, target);
393 } else {
394 copyFile(f, target);
395 }
396 }
397 }
398 }
399
400 /**
401 * Deletes a directory recursively.
402 * @param path The directory to delete
403 * @return <code>true</code> if and only if the file or directory is
404 * successfully deleted; <code>false</code> otherwise
405 */
406 public static boolean deleteDirectory(File path) {
407 if (path.exists()) {
408 File[] files = path.listFiles();
409 if (files != null) {
410 for (File file : files) {
411 if (file.isDirectory()) {
412 deleteDirectory(file);
413 } else {
414 deleteFile(file);
415 }
416 }
417 }
418 }
419 return path.delete();
420 }
421
422 /**
423 * Deletes a file and log a default warning if the file exists but the deletion fails.
424 * @param file file to delete
425 * @return {@code true} if and only if the file does not exist or is successfully deleted; {@code false} otherwise
426 * @since 10569
427 */
428 public static boolean deleteFileIfExists(File file) {
429 if (file.exists()) {
430 return deleteFile(file);
431 } else {
432 return true;
433 }
434 }
435
436 /**
437 * Deletes a file and log a default warning if the deletion fails.
438 * @param file file to delete
439 * @return {@code true} if and only if the file is successfully deleted; {@code false} otherwise
440 * @since 9296
441 */
442 public static boolean deleteFile(File file) {
443 return deleteFile(file, marktr("Unable to delete file {0}"));
444 }
445
446 /**
447 * Deletes a file and log a configurable warning if the deletion fails.
448 * @param file file to delete
449 * @param warnMsg warning message. It will be translated with {@code tr()}
450 * and must contain a single parameter <code>{0}</code> for the file path
451 * @return {@code true} if and only if the file is successfully deleted; {@code false} otherwise
452 * @since 9296
453 */
454 public static boolean deleteFile(File file, String warnMsg) {
455 boolean result = file.delete();
456 if (!result) {
457 Main.warn(tr(warnMsg, file.getPath()));
458 }
459 return result;
460 }
461
462 /**
463 * Creates a directory and log a default warning if the creation fails.
464 * @param dir directory to create
465 * @return {@code true} if and only if the directory is successfully created; {@code false} otherwise
466 * @since 9645
467 */
468 public static boolean mkDirs(File dir) {
469 return mkDirs(dir, marktr("Unable to create directory {0}"));
470 }
471
472 /**
473 * Creates a directory and log a configurable warning if the creation fails.
474 * @param dir directory to create
475 * @param warnMsg warning message. It will be translated with {@code tr()}
476 * and must contain a single parameter <code>{0}</code> for the directory path
477 * @return {@code true} if and only if the directory is successfully created; {@code false} otherwise
478 * @since 9645
479 */
480 public static boolean mkDirs(File dir, String warnMsg) {
481 boolean result = dir.mkdirs();
482 if (!result) {
483 Main.warn(tr(warnMsg, dir.getPath()));
484 }
485 return result;
486 }
487
488 /**
489 * <p>Utility method for closing a {@link java.io.Closeable} object.</p>
490 *
491 * @param c the closeable object. May be null.
492 */
493 public static void close(Closeable c) {
494 if (c == null) return;
495 try {
496 c.close();
497 } catch (IOException e) {
498 Main.warn(e);
499 }
500 }
501
502 /**
503 * <p>Utility method for closing a {@link java.util.zip.ZipFile}.</p>
504 *
505 * @param zip the zip file. May be null.
506 */
507 public static void close(ZipFile zip) {
508 close((Closeable) zip);
509 }
510
511 /**
512 * Converts the given file to its URL.
513 * @param f The file to get URL from
514 * @return The URL of the given file, or {@code null} if not possible.
515 * @since 6615
516 */
517 public static URL fileToURL(File f) {
518 if (f != null) {
519 try {
520 return f.toURI().toURL();
521 } catch (MalformedURLException ex) {
522 Main.error("Unable to convert filename " + f.getAbsolutePath() + " to URL");
523 }
524 }
525 return null;
526 }
527
528 private static final double EPSILON = 1e-11;
529
530 /**
531 * Determines if the two given double values are equal (their delta being smaller than a fixed epsilon)
532 * @param a The first double value to compare
533 * @param b The second double value to compare
534 * @return {@code true} if {@code abs(a - b) <= 1e-11}, {@code false} otherwise
535 */
536 public static boolean equalsEpsilon(double a, double b) {
537 return Math.abs(a - b) <= EPSILON;
538 }
539
540 /**
541 * Calculate MD5 hash of a string and output in hexadecimal format.
542 * @param data arbitrary String
543 * @return MD5 hash of data, string of length 32 with characters in range [0-9a-f]
544 */
545 public static String md5Hex(String data) {
546 MessageDigest md = null;
547 try {
548 md = MessageDigest.getInstance("MD5");
549 } catch (NoSuchAlgorithmException e) {
550 throw new JosmRuntimeException(e);
551 }
552 byte[] byteData = data.getBytes(StandardCharsets.UTF_8);
553 byte[] byteDigest = md.digest(byteData);
554 return toHexString(byteDigest);
555 }
556
557 private static final char[] HEX_ARRAY = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
558
559 /**
560 * Converts a byte array to a string of hexadecimal characters.
561 * Preserves leading zeros, so the size of the output string is always twice
562 * the number of input bytes.
563 * @param bytes the byte array
564 * @return hexadecimal representation
565 */
566 public static String toHexString(byte[] bytes) {
567
568 if (bytes == null) {
569 return "";
570 }
571
572 final int len = bytes.length;
573 if (len == 0) {
574 return "";
575 }
576
577 char[] hexChars = new char[len * 2];
578 for (int i = 0, j = 0; i < len; i++) {
579 final int v = bytes[i];
580 hexChars[j++] = HEX_ARRAY[(v & 0xf0) >> 4];
581 hexChars[j++] = HEX_ARRAY[v & 0xf];
582 }
583 return new String(hexChars);
584 }
585
586 /**
587 * Topological sort.
588 * @param <T> type of items
589 *
590 * @param dependencies contains mappings (key -&gt; value). In the final list of sorted objects, the key will come
591 * after the value. (In other words, the key depends on the value(s).)
592 * There must not be cyclic dependencies.
593 * @return the list of sorted objects
594 */
595 public static <T> List<T> topologicalSort(final MultiMap<T, T> dependencies) {
596 MultiMap<T, T> deps = new MultiMap<>();
597 for (T key : dependencies.keySet()) {
598 deps.putVoid(key);
599 for (T val : dependencies.get(key)) {
600 deps.putVoid(val);
601 deps.put(key, val);
602 }
603 }
604
605 int size = deps.size();
606 List<T> sorted = new ArrayList<>();
607 for (int i = 0; i < size; ++i) {
608 T parentless = null;
609 for (T key : deps.keySet()) {
610 if (deps.get(key).isEmpty()) {
611 parentless = key;
612 break;
613 }
614 }
615 if (parentless == null) throw new JosmRuntimeException("parentless");
616 sorted.add(parentless);
617 deps.remove(parentless);
618 for (T key : deps.keySet()) {
619 deps.remove(key, parentless);
620 }
621 }
622 if (sorted.size() != size) throw new JosmRuntimeException("Wrong size");
623 return sorted;
624 }
625
626 /**
627 * Replaces some HTML reserved characters (&lt;, &gt; and &amp;) by their equivalent entity (&amp;lt;, &amp;gt; and &amp;amp;);
628 * @param s The unescaped string
629 * @return The escaped string
630 */
631 public static String escapeReservedCharactersHTML(String s) {
632 return s == null ? "" : s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;");
633 }
634
635 /**
636 * Transforms the collection {@code c} into an unmodifiable collection and
637 * applies the {@link Function} {@code f} on each element upon access.
638 * @param <A> class of input collection
639 * @param <B> class of transformed collection
640 * @param c a collection
641 * @param f a function that transforms objects of {@code A} to objects of {@code B}
642 * @return the transformed unmodifiable collection
643 */
644 public static <A, B> Collection<B> transform(final Collection<? extends A> c, final Function<A, B> f) {
645 return new AbstractCollection<B>() {
646
647 @Override
648 public int size() {
649 return c.size();
650 }
651
652 @Override
653 public Iterator<B> iterator() {
654 return new Iterator<B>() {
655
656 private Iterator<? extends A> it = c.iterator();
657
658 @Override
659 public boolean hasNext() {
660 return it.hasNext();
661 }
662
663 @Override
664 public B next() {
665 return f.apply(it.next());
666 }
667
668 @Override
669 public void remove() {
670 throw new UnsupportedOperationException();
671 }
672 };
673 }
674 };
675 }
676
677 /**
678 * Transforms the list {@code l} into an unmodifiable list and
679 * applies the {@link Function} {@code f} on each element upon access.
680 * @param <A> class of input collection
681 * @param <B> class of transformed collection
682 * @param l a collection
683 * @param f a function that transforms objects of {@code A} to objects of {@code B}
684 * @return the transformed unmodifiable list
685 */
686 public static <A, B> List<B> transform(final List<? extends A> l, final Function<A, B> f) {
687 return new AbstractList<B>() {
688
689 @Override
690 public int size() {
691 return l.size();
692 }
693
694 @Override
695 public B get(int index) {
696 return f.apply(l.get(index));
697 }
698 };
699 }
700
701 /**
702 * Returns a Bzip2 input stream wrapping given input stream.
703 * @param in The raw input stream
704 * @return a Bzip2 input stream wrapping given input stream, or {@code null} if {@code in} is {@code null}
705 * @throws IOException if the given input stream does not contain valid BZ2 header
706 * @since 7867
707 */
708 public static BZip2CompressorInputStream getBZip2InputStream(InputStream in) throws IOException {
709 if (in == null) {
710 return null;
711 }
712 return new BZip2CompressorInputStream(in, /* see #9537 */ true);
713 }
714
715 /**
716 * Returns a Gzip input stream wrapping given input stream.
717 * @param in The raw input stream
718 * @return a Gzip input stream wrapping given input stream, or {@code null} if {@code in} is {@code null}
719 * @throws IOException if an I/O error has occurred
720 * @since 7119
721 */
722 public static GZIPInputStream getGZipInputStream(InputStream in) throws IOException {
723 if (in == null) {
724 return null;
725 }
726 return new GZIPInputStream(in);
727 }
728
729 /**
730 * Returns a Zip input stream wrapping given input stream.
731 * @param in The raw input stream
732 * @return a Zip input stream wrapping given input stream, or {@code null} if {@code in} is {@code null}
733 * @throws IOException if an I/O error has occurred
734 * @since 7119
735 */
736 public static ZipInputStream getZipInputStream(InputStream in) throws IOException {
737 if (in == null) {
738 return null;
739 }
740 ZipInputStream zis = new ZipInputStream(in, StandardCharsets.UTF_8);
741 // Positions the stream at the beginning of first entry
742 ZipEntry ze = zis.getNextEntry();
743 if (ze != null && Main.isDebugEnabled()) {
744 Main.debug("Zip entry: "+ze.getName());
745 }
746 return zis;
747 }
748
749 /**
750 * Determines if the given String would be empty if stripped.
751 * This is an efficient alternative to {@code strip(s).isEmpty()} that avoids to create useless String object.
752 * @param str The string to test
753 * @return {@code true} if the stripped version of {@code s} would be empty.
754 * @since 11435
755 */
756 public static boolean isStripEmpty(String str) {
757 if (str != null) {
758 for (int i = 0; i < str.length(); i++) {
759 if (!isStrippedChar(str.charAt(i), DEFAULT_STRIP)) {
760 return false;
761 }
762 }
763 }
764 return true;
765 }
766
767 /**
768 * An alternative to {@link String#trim()} to effectively remove all leading
769 * and trailing white characters, including Unicode ones.
770 * @param str The string to strip
771 * @return <code>str</code>, without leading and trailing characters, according to
772 * {@link Character#isWhitespace(char)} and {@link Character#isSpaceChar(char)}.
773 * @see <a href="http://closingbraces.net/2008/11/11/javastringtrim/">Java String.trim has a strange idea of whitespace</a>
774 * @see <a href="https://bugs.openjdk.java.net/browse/JDK-4080617">JDK bug 4080617</a>
775 * @see <a href="https://bugs.openjdk.java.net/browse/JDK-7190385">JDK bug 7190385</a>
776 * @since 5772
777 */
778 public static String strip(final String str) {
779 if (str == null || str.isEmpty()) {
780 return str;
781 }
782 return strip(str, DEFAULT_STRIP);
783 }
784
785 /**
786 * An alternative to {@link String#trim()} to effectively remove all leading
787 * and trailing white characters, including Unicode ones.
788 * @param str The string to strip
789 * @param skipChars additional characters to skip
790 * @return <code>str</code>, without leading and trailing characters, according to
791 * {@link Character#isWhitespace(char)}, {@link Character#isSpaceChar(char)} and skipChars.
792 * @since 8435
793 */
794 public static String strip(final String str, final String skipChars) {
795 if (str == null || str.isEmpty()) {
796 return str;
797 }
798 return strip(str, stripChars(skipChars));
799 }
800
801 private static String strip(final String str, final char ... skipChars) {
802
803 int start = 0;
804 int end = str.length();
805 boolean leadingSkipChar = true;
806 while (leadingSkipChar && start < end) {
807 leadingSkipChar = isStrippedChar(str.charAt(start), skipChars);
808 if (leadingSkipChar) {
809 start++;
810 }
811 }
812 boolean trailingSkipChar = true;
813 while (trailingSkipChar && end > start + 1) {
814 trailingSkipChar = isStrippedChar(str.charAt(end - 1), skipChars);
815 if (trailingSkipChar) {
816 end--;
817 }
818 }
819
820 return str.substring(start, end);
821 }
822
823 private static boolean isStrippedChar(char c, final char ... skipChars) {
824 return Character.isWhitespace(c) || Character.isSpaceChar(c) || stripChar(skipChars, c);
825 }
826
827 private static char[] stripChars(final String skipChars) {
828 if (skipChars == null || skipChars.isEmpty()) {
829 return DEFAULT_STRIP;
830 }
831
832 char[] chars = new char[DEFAULT_STRIP.length + skipChars.length()];
833 System.arraycopy(DEFAULT_STRIP, 0, chars, 0, DEFAULT_STRIP.length);
834 skipChars.getChars(0, skipChars.length(), chars, DEFAULT_STRIP.length);
835
836 return chars;
837 }
838
839 private static boolean stripChar(final char[] strip, char c) {
840 for (char s : strip) {
841 if (c == s) {
842 return true;
843 }
844 }
845 return false;
846 }
847
848 /**
849 * Runs an external command and returns the standard output.
850 *
851 * The program is expected to execute fast.
852 *
853 * @param command the command with arguments
854 * @return the output
855 * @throws IOException when there was an error, e.g. command does not exist
856 */
857 public static String execOutput(List<String> command) throws IOException {
858 if (Main.isDebugEnabled()) {
859 Main.debug(join(" ", command));
860 }
861 Process p = new ProcessBuilder(command).start();
862 try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
863 StringBuilder all = null;
864 String line;
865 while ((line = input.readLine()) != null) {
866 if (all == null) {
867 all = new StringBuilder(line);
868 } else {
869 all.append('\n');
870 all.append(line);
871 }
872 }
873 return all != null ? all.toString() : null;
874 }
875 }
876
877 /**
878 * Returns the JOSM temp directory.
879 * @return The JOSM temp directory ({@code <java.io.tmpdir>/JOSM}), or {@code null} if {@code java.io.tmpdir} is not defined
880 * @since 6245
881 */
882 public static File getJosmTempDir() {
883 String tmpDir = System.getProperty("java.io.tmpdir");
884 if (tmpDir == null) {
885 return null;
886 }
887 File josmTmpDir = new File(tmpDir, "JOSM");
888 if (!josmTmpDir.exists() && !josmTmpDir.mkdirs()) {
889 Main.warn("Unable to create temp directory " + josmTmpDir);
890 }
891 return josmTmpDir;
892 }
893
894 /**
895 * Returns a simple human readable (hours, minutes, seconds) string for a given duration in milliseconds.
896 * @param elapsedTime The duration in milliseconds
897 * @return A human readable string for the given duration
898 * @throws IllegalArgumentException if elapsedTime is &lt; 0
899 * @since 6354
900 */
901 public static String getDurationString(long elapsedTime) {
902 if (elapsedTime < 0) {
903 throw new IllegalArgumentException("elapsedTime must be >= 0");
904 }
905 // Is it less than 1 second ?
906 if (elapsedTime < MILLIS_OF_SECOND) {
907 return String.format("%d %s", elapsedTime, tr("ms"));
908 }
909 // Is it less than 1 minute ?
910 if (elapsedTime < MILLIS_OF_MINUTE) {
911 return String.format("%.1f %s", elapsedTime / (double) MILLIS_OF_SECOND, tr("s"));
912 }
913 // Is it less than 1 hour ?
914 if (elapsedTime < MILLIS_OF_HOUR) {
915 final long min = elapsedTime / MILLIS_OF_MINUTE;
916 return String.format("%d %s %d %s", min, tr("min"), (elapsedTime - min * MILLIS_OF_MINUTE) / MILLIS_OF_SECOND, tr("s"));
917 }
918 // Is it less than 1 day ?
919 if (elapsedTime < MILLIS_OF_DAY) {
920 final long hour = elapsedTime / MILLIS_OF_HOUR;
921 return String.format("%d %s %d %s", hour, tr("h"), (elapsedTime - hour * MILLIS_OF_HOUR) / MILLIS_OF_MINUTE, tr("min"));
922 }
923 long days = elapsedTime / MILLIS_OF_DAY;
924 return String.format("%d %s %d %s", days, trn("day", "days", days), (elapsedTime - days * MILLIS_OF_DAY) / MILLIS_OF_HOUR, tr("h"));
925 }
926
927 /**
928 * Returns a human readable representation (B, kB, MB, ...) for the given number of byes.
929 * @param bytes the number of bytes
930 * @param locale the locale used for formatting
931 * @return a human readable representation
932 * @since 9274
933 */
934 public static String getSizeString(long bytes, Locale locale) {
935 if (bytes < 0) {
936 throw new IllegalArgumentException("bytes must be >= 0");
937 }
938 int unitIndex = 0;
939 double value = bytes;
940 while (value >= 1024 && unitIndex < SIZE_UNITS.length) {
941 value /= 1024;
942 unitIndex++;
943 }
944 if (value > 100 || unitIndex == 0) {
945 return String.format(locale, "%.0f %s", value, SIZE_UNITS[unitIndex]);
946 } else if (value > 10) {
947 return String.format(locale, "%.1f %s", value, SIZE_UNITS[unitIndex]);
948 } else {
949 return String.format(locale, "%.2f %s", value, SIZE_UNITS[unitIndex]);
950 }
951 }
952
953 /**
954 * Returns a human readable representation of a list of positions.
955 * <p>
956 * For instance, {@code [1,5,2,6,7} yields "1-2,5-7
957 * @param positionList a list of positions
958 * @return a human readable representation
959 */
960 public static String getPositionListString(List<Integer> positionList) {
961 Collections.sort(positionList);
962 final StringBuilder sb = new StringBuilder(32);
963 sb.append(positionList.get(0));
964 int cnt = 0;
965 int last = positionList.get(0);
966 for (int i = 1; i < positionList.size(); ++i) {
967 int cur = positionList.get(i);
968 if (cur == last + 1) {
969 ++cnt;
970 } else if (cnt == 0) {
971 sb.append(',').append(cur);
972 } else {
973 sb.append('-').append(last);
974 sb.append(',').append(cur);
975 cnt = 0;
976 }
977 last = cur;
978 }
979 if (cnt >= 1) {
980 sb.append('-').append(last);
981 }
982 return sb.toString();
983 }
984
985 /**
986 * Returns a list of capture groups if {@link Matcher#matches()}, or {@code null}.
987 * The first element (index 0) is the complete match.
988 * Further elements correspond to the parts in parentheses of the regular expression.
989 * @param m the matcher
990 * @return a list of capture groups if {@link Matcher#matches()}, or {@code null}.
991 */
992 public static List<String> getMatches(final Matcher m) {
993 if (m.matches()) {
994 List<String> result = new ArrayList<>(m.groupCount() + 1);
995 for (int i = 0; i <= m.groupCount(); i++) {
996 result.add(m.group(i));
997 }
998 return result;
999 } else {
1000 return null;
1001 }
1002 }
1003
1004 /**
1005 * Cast an object savely.
1006 * @param <T> the target type
1007 * @param o the object to cast
1008 * @param klass the target class (same as T)
1009 * @return null if <code>o</code> is null or the type <code>o</code> is not
1010 * a subclass of <code>klass</code>. The casted value otherwise.
1011 */
1012 @SuppressWarnings("unchecked")
1013 public static <T> T cast(Object o, Class<T> klass) {
1014 if (klass.isInstance(o)) {
1015 return (T) o;
1016 }
1017 return null;
1018 }
1019
1020 /**
1021 * Returns the root cause of a throwable object.
1022 * @param t The object to get root cause for
1023 * @return the root cause of {@code t}
1024 * @since 6639
1025 */
1026 public static Throwable getRootCause(Throwable t) {
1027 Throwable result = t;
1028 if (result != null) {
1029 Throwable cause = result.getCause();
1030 while (cause != null && !cause.equals(result)) {
1031 result = cause;
1032 cause = result.getCause();
1033 }
1034 }
1035 return result;
1036 }
1037
1038 /**
1039 * Adds the given item at the end of a new copy of given array.
1040 * @param <T> type of items
1041 * @param array The source array
1042 * @param item The item to add
1043 * @return An extended copy of {@code array} containing {@code item} as additional last element
1044 * @since 6717
1045 */
1046 public static <T> T[] addInArrayCopy(T[] array, T item) {
1047 T[] biggerCopy = Arrays.copyOf(array, array.length + 1);
1048 biggerCopy[array.length] = item;
1049 return biggerCopy;
1050 }
1051
1052 /**
1053 * If the string {@code s} is longer than {@code maxLength}, the string is cut and "..." is appended.
1054 * @param s String to shorten
1055 * @param maxLength maximum number of characters to keep (not including the "...")
1056 * @return the shortened string
1057 */
1058 public static String shortenString(String s, int maxLength) {
1059 if (s != null && s.length() > maxLength) {
1060 return s.substring(0, maxLength - 3) + "...";
1061 } else {
1062 return s;
1063 }
1064 }
1065
1066 /**
1067 * If the string {@code s} is longer than {@code maxLines} lines, the string is cut and a "..." line is appended.
1068 * @param s String to shorten
1069 * @param maxLines maximum number of lines to keep (including including the "..." line)
1070 * @return the shortened string
1071 */
1072 public static String restrictStringLines(String s, int maxLines) {
1073 if (s == null) {
1074 return null;
1075 } else {
1076 return join("\n", limit(Arrays.asList(s.split("\\n")), maxLines, "..."));
1077 }
1078 }
1079
1080 /**
1081 * If the collection {@code elements} is larger than {@code maxElements} elements,
1082 * the collection is shortened and the {@code overflowIndicator} is appended.
1083 * @param <T> type of elements
1084 * @param elements collection to shorten
1085 * @param maxElements maximum number of elements to keep (including including the {@code overflowIndicator})
1086 * @param overflowIndicator the element used to indicate that the collection has been shortened
1087 * @return the shortened collection
1088 */
1089 public static <T> Collection<T> limit(Collection<T> elements, int maxElements, T overflowIndicator) {
1090 if (elements == null) {
1091 return null;
1092 } else {
1093 if (elements.size() > maxElements) {
1094 final Collection<T> r = new ArrayList<>(maxElements);
1095 final Iterator<T> it = elements.iterator();
1096 while (r.size() < maxElements - 1) {
1097 r.add(it.next());
1098 }
1099 r.add(overflowIndicator);
1100 return r;
1101 } else {
1102 return elements;
1103 }
1104 }
1105 }
1106
1107 /**
1108 * Fixes URL with illegal characters in the query (and fragment) part by
1109 * percent encoding those characters.
1110 *
1111 * special characters like &amp; and # are not encoded
1112 *
1113 * @param url the URL that should be fixed
1114 * @return the repaired URL
1115 */
1116 public static String fixURLQuery(String url) {
1117 if (url == null || url.indexOf('?') == -1)
1118 return url;
1119
1120 String query = url.substring(url.indexOf('?') + 1);
1121
1122 StringBuilder sb = new StringBuilder(url.substring(0, url.indexOf('?') + 1));
1123
1124 for (int i = 0; i < query.length(); i++) {
1125 String c = query.substring(i, i + 1);
1126 if (URL_CHARS.contains(c)) {
1127 sb.append(c);
1128 } else {
1129 sb.append(encodeUrl(c));
1130 }
1131 }
1132 return sb.toString();
1133 }
1134
1135 /**
1136 * Translates a string into <code>application/x-www-form-urlencoded</code>
1137 * format. This method uses UTF-8 encoding scheme to obtain the bytes for unsafe
1138 * characters.
1139 *
1140 * @param s <code>String</code> to be translated.
1141 * @return the translated <code>String</code>.
1142 * @see #decodeUrl(String)
1143 * @since 8304
1144 */
1145 public static String encodeUrl(String s) {
1146 final String enc = StandardCharsets.UTF_8.name();
1147 try {
1148 return URLEncoder.encode(s, enc);
1149 } catch (UnsupportedEncodingException e) {
1150 throw new IllegalStateException(e);
1151 }
1152 }
1153
1154 /**
1155 * Decodes a <code>application/x-www-form-urlencoded</code> string.
1156 * UTF-8 encoding is used to determine
1157 * what characters are represented by any consecutive sequences of the
1158 * form "<code>%<i>xy</i></code>".
1159 *
1160 * @param s the <code>String</code> to decode
1161 * @return the newly decoded <code>String</code>
1162 * @see #encodeUrl(String)
1163 * @since 8304
1164 */
1165 public static String decodeUrl(String s) {
1166 final String enc = StandardCharsets.UTF_8.name();
1167 try {
1168 return URLDecoder.decode(s, enc);
1169 } catch (UnsupportedEncodingException e) {
1170 throw new IllegalStateException(e);
1171 }
1172 }
1173
1174 /**
1175 * Determines if the given URL denotes a file on a local filesystem.
1176 * @param url The URL to test
1177 * @return {@code true} if the url points to a local file
1178 * @since 7356
1179 */
1180 public static boolean isLocalUrl(String url) {
1181 if (url == null || url.startsWith("http://") || url.startsWith("https://") || url.startsWith("resource://"))
1182 return false;
1183 return true;
1184 }
1185
1186 /**
1187 * Determines if the given URL is valid.
1188 * @param url The URL to test
1189 * @return {@code true} if the url is valid
1190 * @since 10294
1191 */
1192 public static boolean isValidUrl(String url) {
1193 if (url != null) {
1194 try {
1195 new URL(url);
1196 return true;
1197 } catch (MalformedURLException e) {
1198 Main.trace(e);
1199 }
1200 }
1201 return false;
1202 }
1203
1204 /**
1205 * Creates a new {@link ThreadFactory} which creates threads with names according to {@code nameFormat}.
1206 * @param nameFormat a {@link String#format(String, Object...)} compatible name format; its first argument is a unique thread index
1207 * @param threadPriority the priority of the created threads, see {@link Thread#setPriority(int)}
1208 * @return a new {@link ThreadFactory}
1209 */
1210 public static ThreadFactory newThreadFactory(final String nameFormat, final int threadPriority) {
1211 return new ThreadFactory() {
1212 final AtomicLong count = new AtomicLong(0);
1213 @Override
1214 public Thread newThread(final Runnable runnable) {
1215 final Thread thread = new Thread(runnable, String.format(Locale.ENGLISH, nameFormat, count.getAndIncrement()));
1216 thread.setPriority(threadPriority);
1217 return thread;
1218 }
1219 };
1220 }
1221
1222 /**
1223 * Returns a {@link ForkJoinPool} with the parallelism given by the preference key.
1224 * @param pref The preference key to determine parallelism
1225 * @param nameFormat see {@link #newThreadFactory(String, int)}
1226 * @param threadPriority see {@link #newThreadFactory(String, int)}
1227 * @return a {@link ForkJoinPool}
1228 */
1229 public static ForkJoinPool newForkJoinPool(String pref, final String nameFormat, final int threadPriority) {
1230 int noThreads = Main.pref.getInteger(pref, Runtime.getRuntime().availableProcessors());
1231 return new ForkJoinPool(noThreads, new ForkJoinPool.ForkJoinWorkerThreadFactory() {
1232 final AtomicLong count = new AtomicLong(0);
1233 @Override
1234 public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
1235 final ForkJoinWorkerThread thread = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
1236 thread.setName(String.format(Locale.ENGLISH, nameFormat, count.getAndIncrement()));
1237 thread.setPriority(threadPriority);
1238 return thread;
1239 }
1240 }, null, true);
1241 }
1242
1243 /**
1244 * Returns an executor which executes commands in the calling thread
1245 * @return an executor
1246 */
1247 public static Executor newDirectExecutor() {
1248 return Runnable::run;
1249 }
1250
1251 /**
1252 * Updates a given system property.
1253 * @param key The property key
1254 * @param value The property value
1255 * @return the previous value of the system property, or {@code null} if it did not have one.
1256 * @since 7894
1257 */
1258 public static String updateSystemProperty(String key, String value) {
1259 if (value != null) {
1260 String old = System.setProperty(key, value);
1261 if (Main.isDebugEnabled()) {
1262 if (!key.toLowerCase(Locale.ENGLISH).contains("password")) {
1263 Main.debug("System property '" + key + "' set to '" + value + "'. Old value was '" + old + '\'');
1264 } else {
1265 Main.debug("System property '" + key + "' changed.");
1266 }
1267 }
1268 return old;
1269 }
1270 return null;
1271 }
1272
1273 /**
1274 * Returns a new secure DOM builder, supporting XML namespaces.
1275 * @return a new secure DOM builder, supporting XML namespaces
1276 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1277 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1278 * @since 10404
1279 */
1280 public static DocumentBuilder newSafeDOMBuilder() throws ParserConfigurationException {
1281 DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
1282 builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
1283 builderFactory.setNamespaceAware(true);
1284 builderFactory.setValidating(false);
1285 return builderFactory.newDocumentBuilder();
1286 }
1287
1288 /**
1289 * Parse the content given {@link InputStream} as XML.
1290 * This method uses a secure DOM builder, supporting XML namespaces.
1291 *
1292 * @param is The InputStream containing the content to be parsed.
1293 * @return the result DOM document
1294 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1295 * @throws IOException if any IO errors occur.
1296 * @throws SAXException for SAX errors.
1297 * @since 10404
1298 */
1299 public static Document parseSafeDOM(InputStream is) throws ParserConfigurationException, IOException, SAXException {
1300 long start = System.currentTimeMillis();
1301 if (Main.isDebugEnabled()) {
1302 Main.debug("Starting DOM parsing of " + is);
1303 }
1304 Document result = newSafeDOMBuilder().parse(is);
1305 if (Main.isDebugEnabled()) {
1306 Main.debug("DOM parsing done in " + getDurationString(System.currentTimeMillis() - start));
1307 }
1308 return result;
1309 }
1310
1311 /**
1312 * Returns a new secure SAX parser, supporting XML namespaces.
1313 * @return a new secure SAX parser, supporting XML namespaces
1314 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1315 * @throws SAXException for SAX errors.
1316 * @since 8287
1317 */
1318 public static SAXParser newSafeSAXParser() throws ParserConfigurationException, SAXException {
1319 SAXParserFactory parserFactory = SAXParserFactory.newInstance();
1320 parserFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
1321 parserFactory.setNamespaceAware(true);
1322 return parserFactory.newSAXParser();
1323 }
1324
1325 /**
1326 * Parse the content given {@link org.xml.sax.InputSource} as XML using the specified {@link org.xml.sax.helpers.DefaultHandler}.
1327 * This method uses a secure SAX parser, supporting XML namespaces.
1328 *
1329 * @param is The InputSource containing the content to be parsed.
1330 * @param dh The SAX DefaultHandler to use.
1331 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1332 * @throws SAXException for SAX errors.
1333 * @throws IOException if any IO errors occur.
1334 * @since 8347
1335 */
1336 public static void parseSafeSAX(InputSource is, DefaultHandler dh) throws ParserConfigurationException, SAXException, IOException {
1337 long start = System.currentTimeMillis();
1338 if (Main.isDebugEnabled()) {
1339 Main.debug("Starting SAX parsing of " + is + " using " + dh);
1340 }
1341 newSafeSAXParser().parse(is, dh);
1342 if (Main.isDebugEnabled()) {
1343 Main.debug("SAX parsing done in " + getDurationString(System.currentTimeMillis() - start));
1344 }
1345 }
1346
1347 /**
1348 * Determines if the filename has one of the given extensions, in a robust manner.
1349 * The comparison is case and locale insensitive.
1350 * @param filename The file name
1351 * @param extensions The list of extensions to look for (without dot)
1352 * @return {@code true} if the filename has one of the given extensions
1353 * @since 8404
1354 */
1355 public static boolean hasExtension(String filename, String... extensions) {
1356 String name = filename.toLowerCase(Locale.ENGLISH).replace("?format=raw", "");
1357 for (String ext : extensions) {
1358 if (name.endsWith('.' + ext.toLowerCase(Locale.ENGLISH)))
1359 return true;
1360 }
1361 return false;
1362 }
1363
1364 /**
1365 * Determines if the file's name has one of the given extensions, in a robust manner.
1366 * The comparison is case and locale insensitive.
1367 * @param file The file
1368 * @param extensions The list of extensions to look for (without dot)
1369 * @return {@code true} if the file's name has one of the given extensions
1370 * @since 8404
1371 */
1372 public static boolean hasExtension(File file, String... extensions) {
1373 return hasExtension(file.getName(), extensions);
1374 }
1375
1376 /**
1377 * Reads the input stream and closes the stream at the end of processing (regardless if an exception was thrown)
1378 *
1379 * @param stream input stream
1380 * @return byte array of data in input stream (empty if stream is null)
1381 * @throws IOException if any I/O error occurs
1382 */
1383 public static byte[] readBytesFromStream(InputStream stream) throws IOException {
1384 if (stream == null) {
1385 return new byte[0];
1386 }
1387 try {
1388 ByteArrayOutputStream bout = new ByteArrayOutputStream(stream.available());
1389 byte[] buffer = new byte[2048];
1390 boolean finished = false;
1391 do {
1392 int read = stream.read(buffer);
1393 if (read >= 0) {
1394 bout.write(buffer, 0, read);
1395 } else {
1396 finished = true;
1397 }
1398 } while (!finished);
1399 if (bout.size() == 0)
1400 return new byte[0];
1401 return bout.toByteArray();
1402 } finally {
1403 stream.close();
1404 }
1405 }
1406
1407 /**
1408 * Returns the initial capacity to pass to the HashMap / HashSet constructor
1409 * when it is initialized with a known number of entries.
1410 *
1411 * When a HashMap is filled with entries, the underlying array is copied over
1412 * to a larger one multiple times. To avoid this process when the number of
1413 * entries is known in advance, the initial capacity of the array can be
1414 * given to the HashMap constructor. This method returns a suitable value
1415 * that avoids rehashing but doesn't waste memory.
1416 * @param nEntries the number of entries expected
1417 * @param loadFactor the load factor
1418 * @return the initial capacity for the HashMap constructor
1419 */
1420 public static int hashMapInitialCapacity(int nEntries, double loadFactor) {
1421 return (int) Math.ceil(nEntries / loadFactor);
1422 }
1423
1424 /**
1425 * Returns the initial capacity to pass to the HashMap / HashSet constructor
1426 * when it is initialized with a known number of entries.
1427 *
1428 * When a HashMap is filled with entries, the underlying array is copied over
1429 * to a larger one multiple times. To avoid this process when the number of
1430 * entries is known in advance, the initial capacity of the array can be
1431 * given to the HashMap constructor. This method returns a suitable value
1432 * that avoids rehashing but doesn't waste memory.
1433 *
1434 * Assumes default load factor (0.75).
1435 * @param nEntries the number of entries expected
1436 * @return the initial capacity for the HashMap constructor
1437 */
1438 public static int hashMapInitialCapacity(int nEntries) {
1439 return hashMapInitialCapacity(nEntries, 0.75d);
1440 }
1441
1442 /**
1443 * Utility class to save a string along with its rendering direction
1444 * (left-to-right or right-to-left).
1445 */
1446 private static class DirectionString {
1447 public final int direction;
1448 public final String str;
1449
1450 DirectionString(int direction, String str) {
1451 this.direction = direction;
1452 this.str = str;
1453 }
1454 }
1455
1456 /**
1457 * Convert a string to a list of {@link GlyphVector}s. The string may contain
1458 * bi-directional text. The result will be in correct visual order.
1459 * Each element of the resulting list corresponds to one section of the
1460 * string with consistent writing direction (left-to-right or right-to-left).
1461 *
1462 * @param string the string to render
1463 * @param font the font
1464 * @param frc a FontRenderContext object
1465 * @return a list of GlyphVectors
1466 */
1467 public static List<GlyphVector> getGlyphVectorsBidi(String string, Font font, FontRenderContext frc) {
1468 List<GlyphVector> gvs = new ArrayList<>();
1469 Bidi bidi = new Bidi(string, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
1470 byte[] levels = new byte[bidi.getRunCount()];
1471 DirectionString[] dirStrings = new DirectionString[levels.length];
1472 for (int i = 0; i < levels.length; ++i) {
1473 levels[i] = (byte) bidi.getRunLevel(i);
1474 String substr = string.substring(bidi.getRunStart(i), bidi.getRunLimit(i));
1475 int dir = levels[i] % 2 == 0 ? Bidi.DIRECTION_LEFT_TO_RIGHT : Bidi.DIRECTION_RIGHT_TO_LEFT;
1476 dirStrings[i] = new DirectionString(dir, substr);
1477 }
1478 Bidi.reorderVisually(levels, 0, dirStrings, 0, levels.length);
1479 for (int i = 0; i < dirStrings.length; ++i) {
1480 char[] chars = dirStrings[i].str.toCharArray();
1481 gvs.add(font.layoutGlyphVector(frc, chars, 0, chars.length, dirStrings[i].direction));
1482 }
1483 return gvs;
1484 }
1485
1486 /**
1487 * Sets {@code AccessibleObject}(s) accessible.
1488 * @param objects objects
1489 * @see AccessibleObject#setAccessible
1490 * @since 10223
1491 */
1492 public static void setObjectsAccessible(final AccessibleObject ... objects) {
1493 if (objects != null && objects.length > 0) {
1494 AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
1495 for (AccessibleObject o : objects) {
1496 o.setAccessible(true);
1497 }
1498 return null;
1499 });
1500 }
1501 }
1502
1503 /**
1504 * Clamp a value to the given range
1505 * @param val The value
1506 * @param min minimum value
1507 * @param max maximum value
1508 * @return the value
1509 * @throws IllegalArgumentException if {@code min > max}
1510 * @since 10805
1511 */
1512 public static double clamp(double val, double min, double max) {
1513 if (min > max) {
1514 throw new IllegalArgumentException(MessageFormat.format("Parameter min ({0}) cannot be greater than max ({1})", min, max));
1515 } else if (val < min) {
1516 return min;
1517 } else if (val > max) {
1518 return max;
1519 } else {
1520 return val;
1521 }
1522 }
1523
1524 /**
1525 * Clamp a integer value to the given range
1526 * @param val The value
1527 * @param min minimum value
1528 * @param max maximum value
1529 * @return the value
1530 * @throws IllegalArgumentException if {@code min > max}
1531 * @since 11055
1532 */
1533 public static int clamp(int val, int min, int max) {
1534 if (min > max) {
1535 throw new IllegalArgumentException(MessageFormat.format("Parameter min ({0}) cannot be greater than max ({1})", min, max));
1536 } else if (val < min) {
1537 return min;
1538 } else if (val > max) {
1539 return max;
1540 } else {
1541 return val;
1542 }
1543 }
1544}
Note: See TracBrowser for help on using the repository browser.