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

Last change on this file since 11288 was 11288, checked in by simon04, 7 years ago

see #13376 - Use TimeUnit instead of combinations of 1000/60/60/24

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