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

Last change on this file since 9970 was 9954, checked in by Don-vip, 8 years ago

make MapScaler and SizeButton implement Accessible interface, add unit tests, fix checkstyle violation

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