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

Last change on this file since 9473 was 9473, checked in by simon04, 8 years ago

fix #12343 - Display at most 20 primitives for some confirmation dialogs (e.g., deletion of relations)

  • Property svn:eol-style set to native
File size: 60.6 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import static org.openstreetmap.josm.tools.I18n.marktr;
5import static org.openstreetmap.josm.tools.I18n.tr;
6import static org.openstreetmap.josm.tools.I18n.trn;
7
8import java.awt.Color;
9import java.awt.Font;
10import java.awt.Toolkit;
11import java.awt.datatransfer.Clipboard;
12import java.awt.datatransfer.ClipboardOwner;
13import java.awt.datatransfer.DataFlavor;
14import java.awt.datatransfer.StringSelection;
15import java.awt.datatransfer.Transferable;
16import java.awt.datatransfer.UnsupportedFlavorException;
17import java.awt.font.FontRenderContext;
18import java.awt.font.GlyphVector;
19import java.io.BufferedReader;
20import java.io.ByteArrayOutputStream;
21import java.io.Closeable;
22import java.io.File;
23import java.io.IOException;
24import java.io.InputStream;
25import java.io.InputStreamReader;
26import java.io.UnsupportedEncodingException;
27import java.net.HttpURLConnection;
28import java.net.MalformedURLException;
29import java.net.URL;
30import java.net.URLConnection;
31import java.net.URLDecoder;
32import java.net.URLEncoder;
33import java.nio.charset.StandardCharsets;
34import java.nio.file.Files;
35import java.nio.file.Path;
36import java.nio.file.StandardCopyOption;
37import java.security.MessageDigest;
38import java.security.NoSuchAlgorithmException;
39import java.text.Bidi;
40import java.text.MessageFormat;
41import java.util.AbstractCollection;
42import java.util.AbstractList;
43import java.util.ArrayList;
44import java.util.Arrays;
45import java.util.Collection;
46import java.util.Collections;
47import java.util.Iterator;
48import java.util.List;
49import java.util.Locale;
50import java.util.Objects;
51import java.util.concurrent.Executor;
52import java.util.concurrent.ForkJoinPool;
53import java.util.concurrent.ForkJoinWorkerThread;
54import java.util.concurrent.ThreadFactory;
55import java.util.concurrent.atomic.AtomicLong;
56import java.util.regex.Matcher;
57import java.util.regex.Pattern;
58import java.util.zip.GZIPInputStream;
59import java.util.zip.ZipEntry;
60import java.util.zip.ZipFile;
61import java.util.zip.ZipInputStream;
62
63import javax.xml.XMLConstants;
64import javax.xml.parsers.ParserConfigurationException;
65import javax.xml.parsers.SAXParser;
66import javax.xml.parsers.SAXParserFactory;
67
68import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
69import org.openstreetmap.josm.Main;
70import org.openstreetmap.josm.data.Version;
71import org.xml.sax.InputSource;
72import org.xml.sax.SAXException;
73import org.xml.sax.helpers.DefaultHandler;
74
75/**
76 * Basic utils, that can be useful in different parts of the program.
77 */
78public final class Utils {
79
80 /** Pattern matching white spaces */
81 public static final Pattern WHITE_SPACES_PATTERN = Pattern.compile("\\s+");
82
83 private Utils() {
84 // Hide default constructor for utils classes
85 }
86
87 private static final int MILLIS_OF_SECOND = 1000;
88 private static final int MILLIS_OF_MINUTE = 60000;
89 private static final int MILLIS_OF_HOUR = 3600000;
90 private static final int MILLIS_OF_DAY = 86400000;
91
92 public static final String URL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=%";
93
94 private static final char[] DEFAULT_STRIP = {'\u200B', '\uFEFF'};
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 * and must contain a single parameter <code>{0}</code> for the file path
463 * @return {@code true} if and only if the file is successfully deleted; {@code false} otherwise
464 * @since 9296
465 */
466 public static boolean deleteFile(File file) {
467 return deleteFile(file, marktr("Unable to delete file {0}"));
468 }
469
470 /**
471 * Deletes a file and log a configurable warning if the deletion fails.
472 * @param file file to delete
473 * @param warnMsg warning message. It will be translated with {@code tr()}
474 * and must contain a single parameter <code>{0}</code> for the file path
475 * @return {@code true} if and only if the file is successfully deleted; {@code false} otherwise
476 * @since 9296
477 */
478 public static boolean deleteFile(File file, String warnMsg) {
479 boolean result = file.delete();
480 if (!result) {
481 Main.warn(tr(warnMsg, file.getPath()));
482 }
483 return result;
484 }
485
486 /**
487 * <p>Utility method for closing a {@link java.io.Closeable} object.</p>
488 *
489 * @param c the closeable object. May be null.
490 */
491 public static void close(Closeable c) {
492 if (c == null) return;
493 try {
494 c.close();
495 } catch (IOException e) {
496 Main.warn(e);
497 }
498 }
499
500 /**
501 * <p>Utility method for closing a {@link java.util.zip.ZipFile}.</p>
502 *
503 * @param zip the zip file. May be null.
504 */
505 public static void close(ZipFile zip) {
506 if (zip == null) return;
507 try {
508 zip.close();
509 } catch (IOException e) {
510 Main.warn(e);
511 }
512 }
513
514 /**
515 * Converts the given file to its URL.
516 * @param f The file to get URL from
517 * @return The URL of the given file, or {@code null} if not possible.
518 * @since 6615
519 */
520 public static URL fileToURL(File f) {
521 if (f != null) {
522 try {
523 return f.toURI().toURL();
524 } catch (MalformedURLException ex) {
525 Main.error("Unable to convert filename " + f.getAbsolutePath() + " to URL");
526 }
527 }
528 return null;
529 }
530
531 private static final double EPSILON = 1e-11;
532
533 /**
534 * Determines if the two given double values are equal (their delta being smaller than a fixed epsilon)
535 * @param a The first double value to compare
536 * @param b The second double value to compare
537 * @return {@code true} if {@code abs(a - b) <= 1e-11}, {@code false} otherwise
538 */
539 public static boolean equalsEpsilon(double a, double b) {
540 return Math.abs(a - b) <= EPSILON;
541 }
542
543 /**
544 * Determines if two collections are equal.
545 * @param a first collection
546 * @param b second collection
547 * @return {@code true} if collections are equal, {@code false} otherwise
548 * @since 9217
549 */
550 public static boolean equalCollection(Collection<?> a, Collection<?> b) {
551 if (a == null) return b == null;
552 if (b == null) return false;
553 if (a.size() != b.size()) return false;
554 Iterator<?> itA = a.iterator();
555 Iterator<?> itB = b.iterator();
556 while (itA.hasNext()) {
557 if (!Objects.equals(itA.next(), itB.next()))
558 return false;
559 }
560 return true;
561 }
562
563 /**
564 * Copies the string {@code s} to system clipboard.
565 * @param s string to be copied to clipboard.
566 * @return true if succeeded, false otherwise.
567 */
568 public static boolean copyToClipboard(String s) {
569 try {
570 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(s), new ClipboardOwner() {
571 @Override
572 public void lostOwnership(Clipboard clpbrd, Transferable t) {
573 // Do nothing
574 }
575 });
576 return true;
577 } catch (IllegalStateException ex) {
578 Main.error(ex);
579 return false;
580 }
581 }
582
583 /**
584 * Extracts clipboard content as {@code Transferable} object.
585 * @param clipboard clipboard from which contents are retrieved
586 * @return clipboard contents if available, {@code null} otherwise.
587 * @since 8429
588 */
589 public static Transferable getTransferableContent(Clipboard clipboard) {
590 Transferable t = null;
591 for (int tries = 0; t == null && tries < 10; tries++) {
592 try {
593 t = clipboard.getContents(null);
594 } catch (IllegalStateException e) {
595 // Clipboard currently unavailable.
596 // On some platforms, the system clipboard is unavailable while it is accessed by another application.
597 try {
598 Thread.sleep(1);
599 } catch (InterruptedException ex) {
600 Main.warn("InterruptedException in "+Utils.class.getSimpleName()+" while getting clipboard content");
601 }
602 } catch (NullPointerException e) {
603 // JDK-6322854: On Linux/X11, NPE can happen for unknown reasons, on all versions of Java
604 Main.error(e);
605 }
606 }
607 return t;
608 }
609
610 /**
611 * Extracts clipboard content as string.
612 * @return string clipboard contents if available, {@code null} otherwise.
613 */
614 public static String getClipboardContent() {
615 Transferable t = getTransferableContent(Toolkit.getDefaultToolkit().getSystemClipboard());
616 try {
617 if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
618 return (String) t.getTransferData(DataFlavor.stringFlavor);
619 }
620 } catch (UnsupportedFlavorException | IOException ex) {
621 Main.error(ex);
622 return null;
623 }
624 return null;
625 }
626
627 /**
628 * Calculate MD5 hash of a string and output in hexadecimal format.
629 * @param data arbitrary String
630 * @return MD5 hash of data, string of length 32 with characters in range [0-9a-f]
631 */
632 public static String md5Hex(String data) {
633 MessageDigest md = null;
634 try {
635 md = MessageDigest.getInstance("MD5");
636 } catch (NoSuchAlgorithmException e) {
637 throw new RuntimeException(e);
638 }
639 byte[] byteData = data.getBytes(StandardCharsets.UTF_8);
640 byte[] byteDigest = md.digest(byteData);
641 return toHexString(byteDigest);
642 }
643
644 private static final char[] HEX_ARRAY = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
645
646 /**
647 * Converts a byte array to a string of hexadecimal characters.
648 * Preserves leading zeros, so the size of the output string is always twice
649 * the number of input bytes.
650 * @param bytes the byte array
651 * @return hexadecimal representation
652 */
653 public static String toHexString(byte[] bytes) {
654
655 if (bytes == null) {
656 return "";
657 }
658
659 final int len = bytes.length;
660 if (len == 0) {
661 return "";
662 }
663
664 char[] hexChars = new char[len * 2];
665 for (int i = 0, j = 0; i < len; i++) {
666 final int v = bytes[i];
667 hexChars[j++] = HEX_ARRAY[(v & 0xf0) >> 4];
668 hexChars[j++] = HEX_ARRAY[v & 0xf];
669 }
670 return new String(hexChars);
671 }
672
673 /**
674 * Topological sort.
675 * @param <T> type of items
676 *
677 * @param dependencies contains mappings (key -&gt; value). In the final list of sorted objects, the key will come
678 * after the value. (In other words, the key depends on the value(s).)
679 * There must not be cyclic dependencies.
680 * @return the list of sorted objects
681 */
682 public static <T> List<T> topologicalSort(final MultiMap<T, T> dependencies) {
683 MultiMap<T, T> deps = new MultiMap<>();
684 for (T key : dependencies.keySet()) {
685 deps.putVoid(key);
686 for (T val : dependencies.get(key)) {
687 deps.putVoid(val);
688 deps.put(key, val);
689 }
690 }
691
692 int size = deps.size();
693 List<T> sorted = new ArrayList<>();
694 for (int i = 0; i < size; ++i) {
695 T parentless = null;
696 for (T key : deps.keySet()) {
697 if (deps.get(key).isEmpty()) {
698 parentless = key;
699 break;
700 }
701 }
702 if (parentless == null) throw new RuntimeException();
703 sorted.add(parentless);
704 deps.remove(parentless);
705 for (T key : deps.keySet()) {
706 deps.remove(key, parentless);
707 }
708 }
709 if (sorted.size() != size) throw new RuntimeException();
710 return sorted;
711 }
712
713 /**
714 * Replaces some HTML reserved characters (&lt;, &gt; and &amp;) by their equivalent entity (&amp;lt;, &amp;gt; and &amp;amp;);
715 * @param s The unescaped string
716 * @return The escaped string
717 */
718 public static String escapeReservedCharactersHTML(String s) {
719 return s == null ? "" : s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;");
720 }
721
722 /**
723 * Represents a function that can be applied to objects of {@code A} and
724 * returns objects of {@code B}.
725 * @param <A> class of input objects
726 * @param <B> class of transformed objects
727 */
728 public interface Function<A, B> {
729
730 /**
731 * Applies the function on {@code x}.
732 * @param x an object of
733 * @return the transformed object
734 */
735 B apply(A x);
736 }
737
738 /**
739 * Transforms the collection {@code c} into an unmodifiable collection and
740 * applies the {@link org.openstreetmap.josm.tools.Utils.Function} {@code f} on each element upon access.
741 * @param <A> class of input collection
742 * @param <B> class of transformed collection
743 * @param c a collection
744 * @param f a function that transforms objects of {@code A} to objects of {@code B}
745 * @return the transformed unmodifiable collection
746 */
747 public static <A, B> Collection<B> transform(final Collection<? extends A> c, final Function<A, B> f) {
748 return new AbstractCollection<B>() {
749
750 @Override
751 public int size() {
752 return c.size();
753 }
754
755 @Override
756 public Iterator<B> iterator() {
757 return new Iterator<B>() {
758
759 private Iterator<? extends A> it = c.iterator();
760
761 @Override
762 public boolean hasNext() {
763 return it.hasNext();
764 }
765
766 @Override
767 public B next() {
768 return f.apply(it.next());
769 }
770
771 @Override
772 public void remove() {
773 throw new UnsupportedOperationException();
774 }
775 };
776 }
777 };
778 }
779
780 /**
781 * Transforms the list {@code l} into an unmodifiable list and
782 * applies the {@link org.openstreetmap.josm.tools.Utils.Function} {@code f} on each element upon access.
783 * @param <A> class of input collection
784 * @param <B> class of transformed collection
785 * @param l a collection
786 * @param f a function that transforms objects of {@code A} to objects of {@code B}
787 * @return the transformed unmodifiable list
788 */
789 public static <A, B> List<B> transform(final List<? extends A> l, final Function<A, B> f) {
790 return new AbstractList<B>() {
791
792 @Override
793 public int size() {
794 return l.size();
795 }
796
797 @Override
798 public B get(int index) {
799 return f.apply(l.get(index));
800 }
801 };
802 }
803
804 private static final Pattern HTTP_PREFFIX_PATTERN = Pattern.compile("https?");
805
806 /**
807 * Opens a HTTP connection to the given URL and sets the User-Agent property to JOSM's one.
808 * @param httpURL The HTTP url to open (must use http:// or https://)
809 * @return An open HTTP connection to the given URL
810 * @throws java.io.IOException if an I/O exception occurs.
811 * @since 5587
812 * @deprecated Use {@link HttpClient} instead
813 */
814 @Deprecated
815 public static HttpURLConnection openHttpConnection(URL httpURL) throws IOException {
816 if (httpURL == null || !HTTP_PREFFIX_PATTERN.matcher(httpURL.getProtocol()).matches()) {
817 throw new IllegalArgumentException("Invalid HTTP url");
818 }
819 if (Main.isDebugEnabled()) {
820 Main.debug("Opening HTTP connection to "+httpURL.toExternalForm());
821 }
822 HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection();
823 connection.setRequestProperty("User-Agent", Version.getInstance().getFullAgentString());
824 connection.setUseCaches(false);
825 return connection;
826 }
827
828 /**
829 * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
830 * @param url The url to open
831 * @return An stream for the given URL
832 * @throws java.io.IOException if an I/O exception occurs.
833 * @since 5867
834 * @deprecated Use {@link HttpClient} instead
835 */
836 @Deprecated
837 public static InputStream openURL(URL url) throws IOException {
838 return HttpClient.create(url).connect().getContent();
839 }
840
841 /**
842 * Opens a connection to the given URL, sets the User-Agent property to JOSM's one, and decompresses stream if necessary.
843 * @param url The url to open
844 * @param decompress whether to wrap steam in a {@link GZIPInputStream} or {@link BZip2CompressorInputStream}
845 * if the {@code Content-Type} header is set accordingly.
846 * @return An stream for the given URL
847 * @throws IOException if an I/O exception occurs.
848 * @since 6421
849 * @deprecated Use {@link HttpClient} instead
850 */
851 @Deprecated
852 public static InputStream openURLAndDecompress(final URL url, final boolean decompress) throws IOException {
853 return HttpClient.create(url).connect().uncompress(decompress).getContent();
854 }
855
856 /**
857 * Returns a Bzip2 input stream wrapping given input stream.
858 * @param in The raw input stream
859 * @return a Bzip2 input stream wrapping given input stream, or {@code null} if {@code in} is {@code null}
860 * @throws IOException if the given input stream does not contain valid BZ2 header
861 * @since 7867
862 */
863 public static BZip2CompressorInputStream getBZip2InputStream(InputStream in) throws IOException {
864 if (in == null) {
865 return null;
866 }
867 return new BZip2CompressorInputStream(in, /* see #9537 */ true);
868 }
869
870 /**
871 * Returns a Gzip input stream wrapping given input stream.
872 * @param in The raw input stream
873 * @return a Gzip input stream wrapping given input stream, or {@code null} if {@code in} is {@code null}
874 * @throws IOException if an I/O error has occurred
875 * @since 7119
876 */
877 public static GZIPInputStream getGZipInputStream(InputStream in) throws IOException {
878 if (in == null) {
879 return null;
880 }
881 return new GZIPInputStream(in);
882 }
883
884 /**
885 * Returns a Zip input stream wrapping given input stream.
886 * @param in The raw input stream
887 * @return a Zip input stream wrapping given input stream, or {@code null} if {@code in} is {@code null}
888 * @throws IOException if an I/O error has occurred
889 * @since 7119
890 */
891 public static ZipInputStream getZipInputStream(InputStream in) throws IOException {
892 if (in == null) {
893 return null;
894 }
895 ZipInputStream zis = new ZipInputStream(in, StandardCharsets.UTF_8);
896 // Positions the stream at the beginning of first entry
897 ZipEntry ze = zis.getNextEntry();
898 if (ze != null && Main.isDebugEnabled()) {
899 Main.debug("Zip entry: "+ze.getName());
900 }
901 return zis;
902 }
903
904 /***
905 * Setups the given URL connection to match JOSM needs by setting its User-Agent and timeout properties.
906 * @param connection The connection to setup
907 * @return {@code connection}, with updated properties
908 * @since 5887
909 * @deprecated Use {@link HttpClient} instead
910 */
911 @Deprecated
912 public static URLConnection setupURLConnection(URLConnection connection) {
913 if (connection != null) {
914 connection.setRequestProperty("User-Agent", Version.getInstance().getFullAgentString());
915 connection.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect", 15)*1000);
916 connection.setReadTimeout(Main.pref.getInteger("socket.timeout.read", 30)*1000);
917 }
918 return connection;
919 }
920
921 /**
922 * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
923 * @param url The url to open
924 * @return An buffered stream reader for the given URL (using UTF-8)
925 * @throws java.io.IOException if an I/O exception occurs.
926 * @since 5868
927 * @deprecated Use {@link HttpClient} instead
928 */
929 @Deprecated
930 public static BufferedReader openURLReader(URL url) throws IOException {
931 return HttpClient.create(url).connect().getContentReader();
932 }
933
934 /**
935 * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
936 * @param url The url to open
937 * @param decompress whether to wrap steam in a {@link GZIPInputStream} or {@link BZip2CompressorInputStream}
938 * if the {@code Content-Type} header is set accordingly.
939 * @return An buffered stream reader for the given URL (using UTF-8)
940 * @throws IOException if an I/O exception occurs.
941 * @since 6421
942 * @deprecated Use {@link HttpClient} instead
943 */
944 @Deprecated
945 public static BufferedReader openURLReaderAndDecompress(final URL url, final boolean decompress) throws IOException {
946 return HttpClient.create(url).connect().uncompress(decompress).getContentReader();
947 }
948
949 /**
950 * Opens a HTTP connection to the given URL, sets the User-Agent property to JOSM's one and optionnaly disables Keep-Alive.
951 * @param httpURL The HTTP url to open (must use http:// or https://)
952 * @param keepAlive whether not to set header {@code Connection=close}
953 * @return An open HTTP connection to the given URL
954 * @throws java.io.IOException if an I/O exception occurs.
955 * @since 5587
956 * @deprecated Use {@link HttpClient} instead
957 */
958 @Deprecated
959 public static HttpURLConnection openHttpConnection(URL httpURL, boolean keepAlive) throws IOException {
960 HttpURLConnection connection = openHttpConnection(httpURL);
961 if (!keepAlive) {
962 connection.setRequestProperty("Connection", "close");
963 }
964 if (Main.isDebugEnabled()) {
965 try {
966 Main.debug("REQUEST: "+ connection.getRequestProperties());
967 } catch (IllegalStateException e) {
968 Main.warn(e);
969 }
970 }
971 return connection;
972 }
973
974 /**
975 * Opens a HTTP connection to given URL, sets the User-Agent property to JOSM's one, optionally disables Keep-Alive, and
976 * optionally - follows redirects. It means, that it's not possible to send custom headers with method
977 *
978 * @param httpURL The HTTP url to open (must use http:// or https://)
979 * @param keepAlive whether not to set header {@code Connection=close}
980 * @param followRedirects wheter or not to follow HTTP(S) redirects
981 * @return An open HTTP connection to the given URL
982 * @throws IOException if an I/O exception occurs
983 * @since 8650
984 * @deprecated Use {@link HttpClient} instead
985 */
986 @Deprecated
987 public static HttpURLConnection openHttpConnection(URL httpURL, boolean keepAlive, boolean followRedirects) throws IOException {
988 HttpURLConnection connection = openHttpConnection(httpURL, keepAlive);
989 if (followRedirects) {
990 for (int i = 0; i < 5; i++) {
991 if (connection.getResponseCode() == 302) {
992 connection = openHttpConnection(new URL(connection.getHeaderField("Location")), keepAlive);
993 } else {
994 break;
995 }
996 }
997 }
998 return connection;
999 }
1000
1001 /**
1002 * An alternative to {@link String#trim()} to effectively remove all leading
1003 * and trailing white characters, including Unicode ones.
1004 * @param str The string to strip
1005 * @return <code>str</code>, without leading and trailing characters, according to
1006 * {@link Character#isWhitespace(char)} and {@link Character#isSpaceChar(char)}.
1007 * @see <a href="http://closingbraces.net/2008/11/11/javastringtrim/">Java’s String.trim has a strange idea of whitespace</a>
1008 * @see <a href="https://bugs.openjdk.java.net/browse/JDK-4080617">JDK bug 4080617</a>
1009 * @see <a href="https://bugs.openjdk.java.net/browse/JDK-7190385">JDK bug 7190385</a>
1010 * @since 5772
1011 */
1012 public static String strip(final String str) {
1013 if (str == null || str.isEmpty()) {
1014 return str;
1015 }
1016 return strip(str, DEFAULT_STRIP);
1017 }
1018
1019 /**
1020 * An alternative to {@link String#trim()} to effectively remove all leading
1021 * and trailing white characters, including Unicode ones.
1022 * @param str The string to strip
1023 * @param skipChars additional characters to skip
1024 * @return <code>str</code>, without leading and trailing characters, according to
1025 * {@link Character#isWhitespace(char)}, {@link Character#isSpaceChar(char)} and skipChars.
1026 * @since 8435
1027 */
1028 public static String strip(final String str, final String skipChars) {
1029 if (str == null || str.isEmpty()) {
1030 return str;
1031 }
1032 return strip(str, stripChars(skipChars));
1033 }
1034
1035 private static String strip(final String str, final char[] skipChars) {
1036
1037 int start = 0;
1038 int end = str.length();
1039 boolean leadingSkipChar = true;
1040 while (leadingSkipChar && start < end) {
1041 char c = str.charAt(start);
1042 leadingSkipChar = Character.isWhitespace(c) || Character.isSpaceChar(c) || stripChar(skipChars, c);
1043 if (leadingSkipChar) {
1044 start++;
1045 }
1046 }
1047 boolean trailingSkipChar = true;
1048 while (trailingSkipChar && end > start + 1) {
1049 char c = str.charAt(end - 1);
1050 trailingSkipChar = Character.isWhitespace(c) || Character.isSpaceChar(c) || stripChar(skipChars, c);
1051 if (trailingSkipChar) {
1052 end--;
1053 }
1054 }
1055
1056 return str.substring(start, end);
1057 }
1058
1059 private static char[] stripChars(final String skipChars) {
1060 if (skipChars == null || skipChars.isEmpty()) {
1061 return DEFAULT_STRIP;
1062 }
1063
1064 char[] chars = new char[DEFAULT_STRIP.length + skipChars.length()];
1065 System.arraycopy(DEFAULT_STRIP, 0, chars, 0, DEFAULT_STRIP.length);
1066 skipChars.getChars(0, skipChars.length(), chars, DEFAULT_STRIP.length);
1067
1068 return chars;
1069 }
1070
1071 private static boolean stripChar(final char[] strip, char c) {
1072 for (char s : strip) {
1073 if (c == s) {
1074 return true;
1075 }
1076 }
1077 return false;
1078 }
1079
1080 /**
1081 * Runs an external command and returns the standard output.
1082 *
1083 * The program is expected to execute fast.
1084 *
1085 * @param command the command with arguments
1086 * @return the output
1087 * @throws IOException when there was an error, e.g. command does not exist
1088 */
1089 public static String execOutput(List<String> command) throws IOException {
1090 if (Main.isDebugEnabled()) {
1091 Main.debug(join(" ", command));
1092 }
1093 Process p = new ProcessBuilder(command).start();
1094 try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
1095 StringBuilder all = null;
1096 String line;
1097 while ((line = input.readLine()) != null) {
1098 if (all == null) {
1099 all = new StringBuilder(line);
1100 } else {
1101 all.append('\n');
1102 all.append(line);
1103 }
1104 }
1105 return all != null ? all.toString() : null;
1106 }
1107 }
1108
1109 /**
1110 * Returns the JOSM temp directory.
1111 * @return The JOSM temp directory ({@code <java.io.tmpdir>/JOSM}), or {@code null} if {@code java.io.tmpdir} is not defined
1112 * @since 6245
1113 */
1114 public static File getJosmTempDir() {
1115 String tmpDir = System.getProperty("java.io.tmpdir");
1116 if (tmpDir == null) {
1117 return null;
1118 }
1119 File josmTmpDir = new File(tmpDir, "JOSM");
1120 if (!josmTmpDir.exists() && !josmTmpDir.mkdirs()) {
1121 Main.warn("Unable to create temp directory " + josmTmpDir);
1122 }
1123 return josmTmpDir;
1124 }
1125
1126 /**
1127 * Returns a simple human readable (hours, minutes, seconds) string for a given duration in milliseconds.
1128 * @param elapsedTime The duration in milliseconds
1129 * @return A human readable string for the given duration
1130 * @throws IllegalArgumentException if elapsedTime is &lt; 0
1131 * @since 6354
1132 */
1133 public static String getDurationString(long elapsedTime) {
1134 if (elapsedTime < 0) {
1135 throw new IllegalArgumentException("elapsedTime must be >= 0");
1136 }
1137 // Is it less than 1 second ?
1138 if (elapsedTime < MILLIS_OF_SECOND) {
1139 return String.format("%d %s", elapsedTime, tr("ms"));
1140 }
1141 // Is it less than 1 minute ?
1142 if (elapsedTime < MILLIS_OF_MINUTE) {
1143 return String.format("%.1f %s", elapsedTime / (double) MILLIS_OF_SECOND, tr("s"));
1144 }
1145 // Is it less than 1 hour ?
1146 if (elapsedTime < MILLIS_OF_HOUR) {
1147 final long min = elapsedTime / MILLIS_OF_MINUTE;
1148 return String.format("%d %s %d %s", min, tr("min"), (elapsedTime - min * MILLIS_OF_MINUTE) / MILLIS_OF_SECOND, tr("s"));
1149 }
1150 // Is it less than 1 day ?
1151 if (elapsedTime < MILLIS_OF_DAY) {
1152 final long hour = elapsedTime / MILLIS_OF_HOUR;
1153 return String.format("%d %s %d %s", hour, tr("h"), (elapsedTime - hour * MILLIS_OF_HOUR) / MILLIS_OF_MINUTE, tr("min"));
1154 }
1155 long days = elapsedTime / MILLIS_OF_DAY;
1156 return String.format("%d %s %d %s", days, trn("day", "days", days), (elapsedTime - days * MILLIS_OF_DAY) / MILLIS_OF_HOUR, tr("h"));
1157 }
1158
1159 /**
1160 * Returns a human readable representation (B, kB, MB, ...) for the given number of byes.
1161 * @param bytes the number of bytes
1162 * @param locale the locale used for formatting
1163 * @return a human readable representation
1164 * @since 9274
1165 */
1166 public static String getSizeString(long bytes, Locale locale) {
1167 if (bytes < 0) {
1168 throw new IllegalArgumentException("bytes must be >= 0");
1169 }
1170 final String[] units = {"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
1171 int unitIndex = 0;
1172 double value = bytes;
1173 while (value >= 1024 && unitIndex < units.length) {
1174 value /= 1024;
1175 unitIndex++;
1176 }
1177 if (value > 100 || unitIndex == 0) {
1178 return String.format(locale, "%.0f %s", value, units[unitIndex]);
1179 } else if (value > 10) {
1180 return String.format(locale, "%.1f %s", value, units[unitIndex]);
1181 } else {
1182 return String.format(locale, "%.2f %s", value, units[unitIndex]);
1183 }
1184 }
1185
1186 /**
1187 * Returns a human readable representation of a list of positions.
1188 * <p>
1189 * For instance, {@code [1,5,2,6,7} yields "1-2,5-7
1190 * @param positionList a list of positions
1191 * @return a human readable representation
1192 */
1193 public static String getPositionListString(List<Integer> positionList) {
1194 Collections.sort(positionList);
1195 final StringBuilder sb = new StringBuilder(32);
1196 sb.append(positionList.get(0));
1197 int cnt = 0;
1198 int last = positionList.get(0);
1199 for (int i = 1; i < positionList.size(); ++i) {
1200 int cur = positionList.get(i);
1201 if (cur == last + 1) {
1202 ++cnt;
1203 } else if (cnt == 0) {
1204 sb.append(',').append(cur);
1205 } else {
1206 sb.append('-').append(last);
1207 sb.append(',').append(cur);
1208 cnt = 0;
1209 }
1210 last = cur;
1211 }
1212 if (cnt >= 1) {
1213 sb.append('-').append(last);
1214 }
1215 return sb.toString();
1216 }
1217
1218 /**
1219 * Returns a list of capture groups if {@link Matcher#matches()}, or {@code null}.
1220 * The first element (index 0) is the complete match.
1221 * Further elements correspond to the parts in parentheses of the regular expression.
1222 * @param m the matcher
1223 * @return a list of capture groups if {@link Matcher#matches()}, or {@code null}.
1224 */
1225 public static List<String> getMatches(final Matcher m) {
1226 if (m.matches()) {
1227 List<String> result = new ArrayList<>(m.groupCount() + 1);
1228 for (int i = 0; i <= m.groupCount(); i++) {
1229 result.add(m.group(i));
1230 }
1231 return result;
1232 } else {
1233 return null;
1234 }
1235 }
1236
1237 /**
1238 * Cast an object savely.
1239 * @param <T> the target type
1240 * @param o the object to cast
1241 * @param klass the target class (same as T)
1242 * @return null if <code>o</code> is null or the type <code>o</code> is not
1243 * a subclass of <code>klass</code>. The casted value otherwise.
1244 */
1245 @SuppressWarnings("unchecked")
1246 public static <T> T cast(Object o, Class<T> klass) {
1247 if (klass.isInstance(o)) {
1248 return (T) o;
1249 }
1250 return null;
1251 }
1252
1253 /**
1254 * Returns the root cause of a throwable object.
1255 * @param t The object to get root cause for
1256 * @return the root cause of {@code t}
1257 * @since 6639
1258 */
1259 public static Throwable getRootCause(Throwable t) {
1260 Throwable result = t;
1261 if (result != null) {
1262 Throwable cause = result.getCause();
1263 while (cause != null && !cause.equals(result)) {
1264 result = cause;
1265 cause = result.getCause();
1266 }
1267 }
1268 return result;
1269 }
1270
1271 /**
1272 * Adds the given item at the end of a new copy of given array.
1273 * @param <T> type of items
1274 * @param array The source array
1275 * @param item The item to add
1276 * @return An extended copy of {@code array} containing {@code item} as additional last element
1277 * @since 6717
1278 */
1279 public static <T> T[] addInArrayCopy(T[] array, T item) {
1280 T[] biggerCopy = Arrays.copyOf(array, array.length + 1);
1281 biggerCopy[array.length] = item;
1282 return biggerCopy;
1283 }
1284
1285 /**
1286 * If the string {@code s} is longer than {@code maxLength}, the string is cut and "..." is appended.
1287 * @param s String to shorten
1288 * @param maxLength maximum number of characters to keep (not including the "...")
1289 * @return the shortened string
1290 */
1291 public static String shortenString(String s, int maxLength) {
1292 if (s != null && s.length() > maxLength) {
1293 return s.substring(0, maxLength - 3) + "...";
1294 } else {
1295 return s;
1296 }
1297 }
1298
1299 /**
1300 * If the string {@code s} is longer than {@code maxLines} lines, the string is cut and a "..." line is appended.
1301 * @param s String to shorten
1302 * @param maxLines maximum number of lines to keep (including including the "..." line)
1303 * @return the shortened string
1304 */
1305 public static String restrictStringLines(String s, int maxLines) {
1306 if (s == null) {
1307 return null;
1308 } else {
1309 return join("\n", limit(Arrays.asList(s.split("\\n")), maxLines, "..."));
1310 }
1311 }
1312
1313 /**
1314 * If the collection {@code elements} is larger than {@code maxElements} elements,
1315 * the collection is shortened and the {@code overflowIndicator} is appended.
1316 * @param elements collection to shorten
1317 * @param maxElements maximum number of elements to keep (including including the {@code overflowIndicator})
1318 * @param overflowIndicator the element used to indicate that the collection has been shortened
1319 * @return the shortened collection
1320 */
1321 public static <T> Collection<T> limit(Collection<T> elements, int maxElements, T overflowIndicator) {
1322 if (elements == null) {
1323 return null;
1324 } else {
1325 if (elements.size() > maxElements) {
1326 final Collection<T> r = new ArrayList<>(maxElements);
1327 final Iterator<T> it = elements.iterator();
1328 while (r.size() < maxElements - 1) {
1329 r.add(it.next());
1330 }
1331 r.add(overflowIndicator);
1332 return r;
1333 } else {
1334 return elements;
1335 }
1336 }
1337 }
1338
1339 /**
1340 * Fixes URL with illegal characters in the query (and fragment) part by
1341 * percent encoding those characters.
1342 *
1343 * special characters like &amp; and # are not encoded
1344 *
1345 * @param url the URL that should be fixed
1346 * @return the repaired URL
1347 */
1348 public static String fixURLQuery(String url) {
1349 if (url.indexOf('?') == -1)
1350 return url;
1351
1352 String query = url.substring(url.indexOf('?') + 1);
1353
1354 StringBuilder sb = new StringBuilder(url.substring(0, url.indexOf('?') + 1));
1355
1356 for (int i = 0; i < query.length(); i++) {
1357 String c = query.substring(i, i + 1);
1358 if (URL_CHARS.contains(c)) {
1359 sb.append(c);
1360 } else {
1361 sb.append(encodeUrl(c));
1362 }
1363 }
1364 return sb.toString();
1365 }
1366
1367 /**
1368 * Translates a string into <code>application/x-www-form-urlencoded</code>
1369 * format. This method uses UTF-8 encoding scheme to obtain the bytes for unsafe
1370 * characters.
1371 *
1372 * @param s <code>String</code> to be translated.
1373 * @return the translated <code>String</code>.
1374 * @see #decodeUrl(String)
1375 * @since 8304
1376 */
1377 public static String encodeUrl(String s) {
1378 final String enc = StandardCharsets.UTF_8.name();
1379 try {
1380 return URLEncoder.encode(s, enc);
1381 } catch (UnsupportedEncodingException e) {
1382 throw new IllegalStateException(e);
1383 }
1384 }
1385
1386 /**
1387 * Decodes a <code>application/x-www-form-urlencoded</code> string.
1388 * UTF-8 encoding is used to determine
1389 * what characters are represented by any consecutive sequences of the
1390 * form "<code>%<i>xy</i></code>".
1391 *
1392 * @param s the <code>String</code> to decode
1393 * @return the newly decoded <code>String</code>
1394 * @see #encodeUrl(String)
1395 * @since 8304
1396 */
1397 public static String decodeUrl(String s) {
1398 final String enc = StandardCharsets.UTF_8.name();
1399 try {
1400 return URLDecoder.decode(s, enc);
1401 } catch (UnsupportedEncodingException e) {
1402 throw new IllegalStateException(e);
1403 }
1404 }
1405
1406 /**
1407 * Determines if the given URL denotes a file on a local filesystem.
1408 * @param url The URL to test
1409 * @return {@code true} if the url points to a local file
1410 * @since 7356
1411 */
1412 public static boolean isLocalUrl(String url) {
1413 if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("resource://"))
1414 return false;
1415 return true;
1416 }
1417
1418 /**
1419 * Creates a new {@link ThreadFactory} which creates threads with names according to {@code nameFormat}.
1420 * @param nameFormat a {@link String#format(String, Object...)} compatible name format; its first argument is a unique thread index
1421 * @param threadPriority the priority of the created threads, see {@link Thread#setPriority(int)}
1422 * @return a new {@link ThreadFactory}
1423 */
1424 public static ThreadFactory newThreadFactory(final String nameFormat, final int threadPriority) {
1425 return new ThreadFactory() {
1426 final AtomicLong count = new AtomicLong(0);
1427 @Override
1428 public Thread newThread(final Runnable runnable) {
1429 final Thread thread = new Thread(runnable, String.format(Locale.ENGLISH, nameFormat, count.getAndIncrement()));
1430 thread.setPriority(threadPriority);
1431 return thread;
1432 }
1433 };
1434 }
1435
1436 /**
1437 * Returns a {@link ForkJoinPool} with the parallelism given by the preference key.
1438 * @param pref The preference key to determine parallelism
1439 * @param nameFormat see {@link #newThreadFactory(String, int)}
1440 * @param threadPriority see {@link #newThreadFactory(String, int)}
1441 * @return a {@link ForkJoinPool}
1442 */
1443 public static ForkJoinPool newForkJoinPool(String pref, final String nameFormat, final int threadPriority) {
1444 int noThreads = Main.pref.getInteger(pref, Runtime.getRuntime().availableProcessors());
1445 return new ForkJoinPool(noThreads, new ForkJoinPool.ForkJoinWorkerThreadFactory() {
1446 final AtomicLong count = new AtomicLong(0);
1447 @Override
1448 public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
1449 final ForkJoinWorkerThread thread = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
1450 thread.setName(String.format(Locale.ENGLISH, nameFormat, count.getAndIncrement()));
1451 thread.setPriority(threadPriority);
1452 return thread;
1453 }
1454 }, null, true);
1455 }
1456
1457 /**
1458 * Returns an executor which executes commands in the calling thread
1459 * @return an executor
1460 */
1461 public static Executor newDirectExecutor() {
1462 return new Executor() {
1463 @Override
1464 public void execute(Runnable command) {
1465 command.run();
1466 }
1467 };
1468 }
1469
1470 /**
1471 * Updates a given system property.
1472 * @param key The property key
1473 * @param value The property value
1474 * @return the previous value of the system property, or {@code null} if it did not have one.
1475 * @since 7894
1476 */
1477 public static String updateSystemProperty(String key, String value) {
1478 if (value != null) {
1479 String old = System.setProperty(key, value);
1480 if (!key.toLowerCase(Locale.ENGLISH).contains("password")) {
1481 Main.debug("System property '" + key + "' set to '" + value + "'. Old value was '" + old + '\'');
1482 } else {
1483 Main.debug("System property '" + key + "' changed.");
1484 }
1485 return old;
1486 }
1487 return null;
1488 }
1489
1490 /**
1491 * Returns a new secure SAX parser, supporting XML namespaces.
1492 * @return a new secure SAX parser, supporting XML namespaces
1493 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1494 * @throws SAXException for SAX errors.
1495 * @since 8287
1496 */
1497 public static SAXParser newSafeSAXParser() throws ParserConfigurationException, SAXException {
1498 SAXParserFactory parserFactory = SAXParserFactory.newInstance();
1499 parserFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
1500 parserFactory.setNamespaceAware(true);
1501 return parserFactory.newSAXParser();
1502 }
1503
1504 /**
1505 * Parse the content given {@link org.xml.sax.InputSource} as XML using the specified {@link org.xml.sax.helpers.DefaultHandler}.
1506 * This method uses a secure SAX parser, supporting XML namespaces.
1507 *
1508 * @param is The InputSource containing the content to be parsed.
1509 * @param dh The SAX DefaultHandler to use.
1510 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1511 * @throws SAXException for SAX errors.
1512 * @throws IOException if any IO errors occur.
1513 * @since 8347
1514 */
1515 public static void parseSafeSAX(InputSource is, DefaultHandler dh) throws ParserConfigurationException, SAXException, IOException {
1516 long start = System.currentTimeMillis();
1517 if (Main.isDebugEnabled()) {
1518 Main.debug("Starting SAX parsing of " + is + " using " + dh);
1519 }
1520 newSafeSAXParser().parse(is, dh);
1521 if (Main.isDebugEnabled()) {
1522 Main.debug("SAX parsing done in " + getDurationString(System.currentTimeMillis() - start));
1523 }
1524 }
1525
1526 /**
1527 * Determines if the filename has one of the given extensions, in a robust manner.
1528 * The comparison is case and locale insensitive.
1529 * @param filename The file name
1530 * @param extensions The list of extensions to look for (without dot)
1531 * @return {@code true} if the filename has one of the given extensions
1532 * @since 8404
1533 */
1534 public static boolean hasExtension(String filename, String... extensions) {
1535 String name = filename.toLowerCase(Locale.ENGLISH).replace("?format=raw", "");
1536 for (String ext : extensions) {
1537 if (name.endsWith('.' + ext.toLowerCase(Locale.ENGLISH)))
1538 return true;
1539 }
1540 return false;
1541 }
1542
1543 /**
1544 * Determines if the file's name has one of the given extensions, in a robust manner.
1545 * The comparison is case and locale insensitive.
1546 * @param file The file
1547 * @param extensions The list of extensions to look for (without dot)
1548 * @return {@code true} if the file's name has one of the given extensions
1549 * @since 8404
1550 */
1551 public static boolean hasExtension(File file, String... extensions) {
1552 return hasExtension(file.getName(), extensions);
1553 }
1554
1555 /**
1556 * Reads the input stream and closes the stream at the end of processing (regardless if an exception was thrown)
1557 *
1558 * @param stream input stream
1559 * @return byte array of data in input stream
1560 * @throws IOException if any I/O error occurs
1561 */
1562 public static byte[] readBytesFromStream(InputStream stream) throws IOException {
1563 try {
1564 ByteArrayOutputStream bout = new ByteArrayOutputStream(stream.available());
1565 byte[] buffer = new byte[2048];
1566 boolean finished = false;
1567 do {
1568 int read = stream.read(buffer);
1569 if (read >= 0) {
1570 bout.write(buffer, 0, read);
1571 } else {
1572 finished = true;
1573 }
1574 } while (!finished);
1575 if (bout.size() == 0)
1576 return null;
1577 return bout.toByteArray();
1578 } finally {
1579 stream.close();
1580 }
1581 }
1582
1583 /**
1584 * Returns the initial capacity to pass to the HashMap / HashSet constructor
1585 * when it is initialized with a known number of entries.
1586 *
1587 * When a HashMap is filled with entries, the underlying array is copied over
1588 * to a larger one multiple times. To avoid this process when the number of
1589 * entries is known in advance, the initial capacity of the array can be
1590 * given to the HashMap constructor. This method returns a suitable value
1591 * that avoids rehashing but doesn't waste memory.
1592 * @param nEntries the number of entries expected
1593 * @param loadFactor the load factor
1594 * @return the initial capacity for the HashMap constructor
1595 */
1596 public static int hashMapInitialCapacity(int nEntries, float loadFactor) {
1597 return (int) Math.ceil(nEntries / loadFactor);
1598 }
1599
1600 /**
1601 * Returns the initial capacity to pass to the HashMap / HashSet constructor
1602 * when it is initialized with a known number of entries.
1603 *
1604 * When a HashMap is filled with entries, the underlying array is copied over
1605 * to a larger one multiple times. To avoid this process when the number of
1606 * entries is known in advance, the initial capacity of the array can be
1607 * given to the HashMap constructor. This method returns a suitable value
1608 * that avoids rehashing but doesn't waste memory.
1609 *
1610 * Assumes default load factor (0.75).
1611 * @param nEntries the number of entries expected
1612 * @return the initial capacity for the HashMap constructor
1613 */
1614 public static int hashMapInitialCapacity(int nEntries) {
1615 return hashMapInitialCapacity(nEntries, 0.75f);
1616 }
1617
1618 /**
1619 * Utility class to save a string along with its rendering direction
1620 * (left-to-right or right-to-left).
1621 */
1622 private static class DirectionString {
1623 public final int direction;
1624 public final String str;
1625
1626 DirectionString(int direction, String str) {
1627 this.direction = direction;
1628 this.str = str;
1629 }
1630 }
1631
1632 /**
1633 * Convert a string to a list of {@link GlyphVector}s. The string may contain
1634 * bi-directional text. The result will be in correct visual order.
1635 * Each element of the resulting list corresponds to one section of the
1636 * string with consistent writing direction (left-to-right or right-to-left).
1637 *
1638 * @param string the string to render
1639 * @param font the font
1640 * @param frc a FontRenderContext object
1641 * @return a list of GlyphVectors
1642 */
1643 public static List<GlyphVector> getGlyphVectorsBidi(String string, Font font, FontRenderContext frc) {
1644 List<GlyphVector> gvs = new ArrayList<>();
1645 Bidi bidi = new Bidi(string, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
1646 byte[] levels = new byte[bidi.getRunCount()];
1647 DirectionString[] dirStrings = new DirectionString[levels.length];
1648 for (int i = 0; i < levels.length; ++i) {
1649 levels[i] = (byte) bidi.getRunLevel(i);
1650 String substr = string.substring(bidi.getRunStart(i), bidi.getRunLimit(i));
1651 int dir = levels[i] % 2 == 0 ? Bidi.DIRECTION_LEFT_TO_RIGHT : Bidi.DIRECTION_RIGHT_TO_LEFT;
1652 dirStrings[i] = new DirectionString(dir, substr);
1653 }
1654 Bidi.reorderVisually(levels, 0, dirStrings, 0, levels.length);
1655 for (int i = 0; i < dirStrings.length; ++i) {
1656 char[] chars = dirStrings[i].str.toCharArray();
1657 gvs.add(font.layoutGlyphVector(frc, chars, 0, chars.length, dirStrings[i].direction));
1658 }
1659 return gvs;
1660 }
1661
1662}
Note: See TracBrowser for help on using the repository browser.