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

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

fix findbugs issue RV_RETURN_VALUE_IGNORED_BAD_PRACTICE for java.io.File.mkdirs

  • Property svn:eol-style set to native
File size: 61.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 * @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 Transferable t = getTransferableContent(Toolkit.getDefaultToolkit().getSystemClipboard());
641 try {
642 if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
643 return (String) t.getTransferData(DataFlavor.stringFlavor);
644 }
645 } catch (UnsupportedFlavorException | IOException 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 private static final Pattern HTTP_PREFFIX_PATTERN = Pattern.compile("https?");
830
831 /**
832 * Opens a HTTP connection to the given URL and sets the User-Agent property to JOSM's one.
833 * @param httpURL The HTTP url to open (must use http:// or https://)
834 * @return An open HTTP connection to the given URL
835 * @throws java.io.IOException if an I/O exception occurs.
836 * @since 5587
837 * @deprecated Use {@link HttpClient} instead
838 */
839 @Deprecated
840 public static HttpURLConnection openHttpConnection(URL httpURL) throws IOException {
841 if (httpURL == null || !HTTP_PREFFIX_PATTERN.matcher(httpURL.getProtocol()).matches()) {
842 throw new IllegalArgumentException("Invalid HTTP url");
843 }
844 if (Main.isDebugEnabled()) {
845 Main.debug("Opening HTTP connection to "+httpURL.toExternalForm());
846 }
847 HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection();
848 connection.setRequestProperty("User-Agent", Version.getInstance().getFullAgentString());
849 connection.setUseCaches(false);
850 return connection;
851 }
852
853 /**
854 * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
855 * @param url The url to open
856 * @return An stream for the given URL
857 * @throws java.io.IOException if an I/O exception occurs.
858 * @since 5867
859 * @deprecated Use {@link HttpClient} instead
860 */
861 @Deprecated
862 public static InputStream openURL(URL url) throws IOException {
863 return HttpClient.create(url).connect().getContent();
864 }
865
866 /**
867 * Opens a connection to the given URL, sets the User-Agent property to JOSM's one, and decompresses stream if necessary.
868 * @param url The url to open
869 * @param decompress whether to wrap steam in a {@link GZIPInputStream} or {@link BZip2CompressorInputStream}
870 * if the {@code Content-Type} header is set accordingly.
871 * @return An stream for the given URL
872 * @throws IOException if an I/O exception occurs.
873 * @since 6421
874 * @deprecated Use {@link HttpClient} instead
875 */
876 @Deprecated
877 public static InputStream openURLAndDecompress(final URL url, final boolean decompress) throws IOException {
878 return HttpClient.create(url).connect().uncompress(decompress).getContent();
879 }
880
881 /**
882 * Returns a Bzip2 input stream wrapping given input stream.
883 * @param in The raw input stream
884 * @return a Bzip2 input stream wrapping given input stream, or {@code null} if {@code in} is {@code null}
885 * @throws IOException if the given input stream does not contain valid BZ2 header
886 * @since 7867
887 */
888 public static BZip2CompressorInputStream getBZip2InputStream(InputStream in) throws IOException {
889 if (in == null) {
890 return null;
891 }
892 return new BZip2CompressorInputStream(in, /* see #9537 */ true);
893 }
894
895 /**
896 * Returns a Gzip input stream wrapping given input stream.
897 * @param in The raw input stream
898 * @return a Gzip input stream wrapping given input stream, or {@code null} if {@code in} is {@code null}
899 * @throws IOException if an I/O error has occurred
900 * @since 7119
901 */
902 public static GZIPInputStream getGZipInputStream(InputStream in) throws IOException {
903 if (in == null) {
904 return null;
905 }
906 return new GZIPInputStream(in);
907 }
908
909 /**
910 * Returns a Zip input stream wrapping given input stream.
911 * @param in The raw input stream
912 * @return a Zip input stream wrapping given input stream, or {@code null} if {@code in} is {@code null}
913 * @throws IOException if an I/O error has occurred
914 * @since 7119
915 */
916 public static ZipInputStream getZipInputStream(InputStream in) throws IOException {
917 if (in == null) {
918 return null;
919 }
920 ZipInputStream zis = new ZipInputStream(in, StandardCharsets.UTF_8);
921 // Positions the stream at the beginning of first entry
922 ZipEntry ze = zis.getNextEntry();
923 if (ze != null && Main.isDebugEnabled()) {
924 Main.debug("Zip entry: "+ze.getName());
925 }
926 return zis;
927 }
928
929 /***
930 * Setups the given URL connection to match JOSM needs by setting its User-Agent and timeout properties.
931 * @param connection The connection to setup
932 * @return {@code connection}, with updated properties
933 * @since 5887
934 * @deprecated Use {@link HttpClient} instead
935 */
936 @Deprecated
937 public static URLConnection setupURLConnection(URLConnection connection) {
938 if (connection != null) {
939 connection.setRequestProperty("User-Agent", Version.getInstance().getFullAgentString());
940 connection.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect", 15)*1000);
941 connection.setReadTimeout(Main.pref.getInteger("socket.timeout.read", 30)*1000);
942 }
943 return connection;
944 }
945
946 /**
947 * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
948 * @param url The url to open
949 * @return An buffered stream reader for the given URL (using UTF-8)
950 * @throws java.io.IOException if an I/O exception occurs.
951 * @since 5868
952 * @deprecated Use {@link HttpClient} instead
953 */
954 @Deprecated
955 public static BufferedReader openURLReader(URL url) throws IOException {
956 return HttpClient.create(url).connect().getContentReader();
957 }
958
959 /**
960 * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
961 * @param url The url to open
962 * @param decompress whether to wrap steam in a {@link GZIPInputStream} or {@link BZip2CompressorInputStream}
963 * if the {@code Content-Type} header is set accordingly.
964 * @return An buffered stream reader for the given URL (using UTF-8)
965 * @throws IOException if an I/O exception occurs.
966 * @since 6421
967 * @deprecated Use {@link HttpClient} instead
968 */
969 @Deprecated
970 public static BufferedReader openURLReaderAndDecompress(final URL url, final boolean decompress) throws IOException {
971 return HttpClient.create(url).connect().uncompress(decompress).getContentReader();
972 }
973
974 /**
975 * Opens a HTTP connection to the given URL, sets the User-Agent property to JOSM's one and optionnaly disables Keep-Alive.
976 * @param httpURL The HTTP url to open (must use http:// or https://)
977 * @param keepAlive whether not to set header {@code Connection=close}
978 * @return An open HTTP connection to the given URL
979 * @throws java.io.IOException if an I/O exception occurs.
980 * @since 5587
981 * @deprecated Use {@link HttpClient} instead
982 */
983 @Deprecated
984 public static HttpURLConnection openHttpConnection(URL httpURL, boolean keepAlive) throws IOException {
985 HttpURLConnection connection = openHttpConnection(httpURL);
986 if (!keepAlive) {
987 connection.setRequestProperty("Connection", "close");
988 }
989 if (Main.isDebugEnabled()) {
990 try {
991 Main.debug("REQUEST: "+ connection.getRequestProperties());
992 } catch (IllegalStateException e) {
993 Main.warn(e);
994 }
995 }
996 return connection;
997 }
998
999 /**
1000 * Opens a HTTP connection to given URL, sets the User-Agent property to JOSM's one, optionally disables Keep-Alive, and
1001 * optionally - follows redirects. It means, that it's not possible to send custom headers with method
1002 *
1003 * @param httpURL The HTTP url to open (must use http:// or https://)
1004 * @param keepAlive whether not to set header {@code Connection=close}
1005 * @param followRedirects wheter or not to follow HTTP(S) redirects
1006 * @return An open HTTP connection to the given URL
1007 * @throws IOException if an I/O exception occurs
1008 * @since 8650
1009 * @deprecated Use {@link HttpClient} instead
1010 */
1011 @Deprecated
1012 public static HttpURLConnection openHttpConnection(URL httpURL, boolean keepAlive, boolean followRedirects) throws IOException {
1013 HttpURLConnection connection = openHttpConnection(httpURL, keepAlive);
1014 if (followRedirects) {
1015 for (int i = 0; i < 5; i++) {
1016 if (connection.getResponseCode() == 302) {
1017 connection = openHttpConnection(new URL(connection.getHeaderField("Location")), keepAlive);
1018 } else {
1019 break;
1020 }
1021 }
1022 }
1023 return connection;
1024 }
1025
1026 /**
1027 * An alternative to {@link String#trim()} to effectively remove all leading
1028 * and trailing white characters, including Unicode ones.
1029 * @param str The string to strip
1030 * @return <code>str</code>, without leading and trailing characters, according to
1031 * {@link Character#isWhitespace(char)} and {@link Character#isSpaceChar(char)}.
1032 * @see <a href="http://closingbraces.net/2008/11/11/javastringtrim/">Java’s String.trim has a strange idea of whitespace</a>
1033 * @see <a href="https://bugs.openjdk.java.net/browse/JDK-4080617">JDK bug 4080617</a>
1034 * @see <a href="https://bugs.openjdk.java.net/browse/JDK-7190385">JDK bug 7190385</a>
1035 * @since 5772
1036 */
1037 public static String strip(final String str) {
1038 if (str == null || str.isEmpty()) {
1039 return str;
1040 }
1041 return strip(str, DEFAULT_STRIP);
1042 }
1043
1044 /**
1045 * An alternative to {@link String#trim()} to effectively remove all leading
1046 * and trailing white characters, including Unicode ones.
1047 * @param str The string to strip
1048 * @param skipChars additional characters to skip
1049 * @return <code>str</code>, without leading and trailing characters, according to
1050 * {@link Character#isWhitespace(char)}, {@link Character#isSpaceChar(char)} and skipChars.
1051 * @since 8435
1052 */
1053 public static String strip(final String str, final String skipChars) {
1054 if (str == null || str.isEmpty()) {
1055 return str;
1056 }
1057 return strip(str, stripChars(skipChars));
1058 }
1059
1060 private static String strip(final String str, final char[] skipChars) {
1061
1062 int start = 0;
1063 int end = str.length();
1064 boolean leadingSkipChar = true;
1065 while (leadingSkipChar && start < end) {
1066 char c = str.charAt(start);
1067 leadingSkipChar = Character.isWhitespace(c) || Character.isSpaceChar(c) || stripChar(skipChars, c);
1068 if (leadingSkipChar) {
1069 start++;
1070 }
1071 }
1072 boolean trailingSkipChar = true;
1073 while (trailingSkipChar && end > start + 1) {
1074 char c = str.charAt(end - 1);
1075 trailingSkipChar = Character.isWhitespace(c) || Character.isSpaceChar(c) || stripChar(skipChars, c);
1076 if (trailingSkipChar) {
1077 end--;
1078 }
1079 }
1080
1081 return str.substring(start, end);
1082 }
1083
1084 private static char[] stripChars(final String skipChars) {
1085 if (skipChars == null || skipChars.isEmpty()) {
1086 return DEFAULT_STRIP;
1087 }
1088
1089 char[] chars = new char[DEFAULT_STRIP.length + skipChars.length()];
1090 System.arraycopy(DEFAULT_STRIP, 0, chars, 0, DEFAULT_STRIP.length);
1091 skipChars.getChars(0, skipChars.length(), chars, DEFAULT_STRIP.length);
1092
1093 return chars;
1094 }
1095
1096 private static boolean stripChar(final char[] strip, char c) {
1097 for (char s : strip) {
1098 if (c == s) {
1099 return true;
1100 }
1101 }
1102 return false;
1103 }
1104
1105 /**
1106 * Runs an external command and returns the standard output.
1107 *
1108 * The program is expected to execute fast.
1109 *
1110 * @param command the command with arguments
1111 * @return the output
1112 * @throws IOException when there was an error, e.g. command does not exist
1113 */
1114 public static String execOutput(List<String> command) throws IOException {
1115 if (Main.isDebugEnabled()) {
1116 Main.debug(join(" ", command));
1117 }
1118 Process p = new ProcessBuilder(command).start();
1119 try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
1120 StringBuilder all = null;
1121 String line;
1122 while ((line = input.readLine()) != null) {
1123 if (all == null) {
1124 all = new StringBuilder(line);
1125 } else {
1126 all.append('\n');
1127 all.append(line);
1128 }
1129 }
1130 return all != null ? all.toString() : null;
1131 }
1132 }
1133
1134 /**
1135 * Returns the JOSM temp directory.
1136 * @return The JOSM temp directory ({@code <java.io.tmpdir>/JOSM}), or {@code null} if {@code java.io.tmpdir} is not defined
1137 * @since 6245
1138 */
1139 public static File getJosmTempDir() {
1140 String tmpDir = System.getProperty("java.io.tmpdir");
1141 if (tmpDir == null) {
1142 return null;
1143 }
1144 File josmTmpDir = new File(tmpDir, "JOSM");
1145 if (!josmTmpDir.exists() && !josmTmpDir.mkdirs()) {
1146 Main.warn("Unable to create temp directory " + josmTmpDir);
1147 }
1148 return josmTmpDir;
1149 }
1150
1151 /**
1152 * Returns a simple human readable (hours, minutes, seconds) string for a given duration in milliseconds.
1153 * @param elapsedTime The duration in milliseconds
1154 * @return A human readable string for the given duration
1155 * @throws IllegalArgumentException if elapsedTime is &lt; 0
1156 * @since 6354
1157 */
1158 public static String getDurationString(long elapsedTime) {
1159 if (elapsedTime < 0) {
1160 throw new IllegalArgumentException("elapsedTime must be >= 0");
1161 }
1162 // Is it less than 1 second ?
1163 if (elapsedTime < MILLIS_OF_SECOND) {
1164 return String.format("%d %s", elapsedTime, tr("ms"));
1165 }
1166 // Is it less than 1 minute ?
1167 if (elapsedTime < MILLIS_OF_MINUTE) {
1168 return String.format("%.1f %s", elapsedTime / (double) MILLIS_OF_SECOND, tr("s"));
1169 }
1170 // Is it less than 1 hour ?
1171 if (elapsedTime < MILLIS_OF_HOUR) {
1172 final long min = elapsedTime / MILLIS_OF_MINUTE;
1173 return String.format("%d %s %d %s", min, tr("min"), (elapsedTime - min * MILLIS_OF_MINUTE) / MILLIS_OF_SECOND, tr("s"));
1174 }
1175 // Is it less than 1 day ?
1176 if (elapsedTime < MILLIS_OF_DAY) {
1177 final long hour = elapsedTime / MILLIS_OF_HOUR;
1178 return String.format("%d %s %d %s", hour, tr("h"), (elapsedTime - hour * MILLIS_OF_HOUR) / MILLIS_OF_MINUTE, tr("min"));
1179 }
1180 long days = elapsedTime / MILLIS_OF_DAY;
1181 return String.format("%d %s %d %s", days, trn("day", "days", days), (elapsedTime - days * MILLIS_OF_DAY) / MILLIS_OF_HOUR, tr("h"));
1182 }
1183
1184 /**
1185 * Returns a human readable representation (B, kB, MB, ...) for the given number of byes.
1186 * @param bytes the number of bytes
1187 * @param locale the locale used for formatting
1188 * @return a human readable representation
1189 * @since 9274
1190 */
1191 public static String getSizeString(long bytes, Locale locale) {
1192 if (bytes < 0) {
1193 throw new IllegalArgumentException("bytes must be >= 0");
1194 }
1195 final String[] units = {"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
1196 int unitIndex = 0;
1197 double value = bytes;
1198 while (value >= 1024 && unitIndex < units.length) {
1199 value /= 1024;
1200 unitIndex++;
1201 }
1202 if (value > 100 || unitIndex == 0) {
1203 return String.format(locale, "%.0f %s", value, units[unitIndex]);
1204 } else if (value > 10) {
1205 return String.format(locale, "%.1f %s", value, units[unitIndex]);
1206 } else {
1207 return String.format(locale, "%.2f %s", value, units[unitIndex]);
1208 }
1209 }
1210
1211 /**
1212 * Returns a human readable representation of a list of positions.
1213 * <p>
1214 * For instance, {@code [1,5,2,6,7} yields "1-2,5-7
1215 * @param positionList a list of positions
1216 * @return a human readable representation
1217 */
1218 public static String getPositionListString(List<Integer> positionList) {
1219 Collections.sort(positionList);
1220 final StringBuilder sb = new StringBuilder(32);
1221 sb.append(positionList.get(0));
1222 int cnt = 0;
1223 int last = positionList.get(0);
1224 for (int i = 1; i < positionList.size(); ++i) {
1225 int cur = positionList.get(i);
1226 if (cur == last + 1) {
1227 ++cnt;
1228 } else if (cnt == 0) {
1229 sb.append(',').append(cur);
1230 } else {
1231 sb.append('-').append(last);
1232 sb.append(',').append(cur);
1233 cnt = 0;
1234 }
1235 last = cur;
1236 }
1237 if (cnt >= 1) {
1238 sb.append('-').append(last);
1239 }
1240 return sb.toString();
1241 }
1242
1243 /**
1244 * Returns a list of capture groups if {@link Matcher#matches()}, or {@code null}.
1245 * The first element (index 0) is the complete match.
1246 * Further elements correspond to the parts in parentheses of the regular expression.
1247 * @param m the matcher
1248 * @return a list of capture groups if {@link Matcher#matches()}, or {@code null}.
1249 */
1250 public static List<String> getMatches(final Matcher m) {
1251 if (m.matches()) {
1252 List<String> result = new ArrayList<>(m.groupCount() + 1);
1253 for (int i = 0; i <= m.groupCount(); i++) {
1254 result.add(m.group(i));
1255 }
1256 return result;
1257 } else {
1258 return null;
1259 }
1260 }
1261
1262 /**
1263 * Cast an object savely.
1264 * @param <T> the target type
1265 * @param o the object to cast
1266 * @param klass the target class (same as T)
1267 * @return null if <code>o</code> is null or the type <code>o</code> is not
1268 * a subclass of <code>klass</code>. The casted value otherwise.
1269 */
1270 @SuppressWarnings("unchecked")
1271 public static <T> T cast(Object o, Class<T> klass) {
1272 if (klass.isInstance(o)) {
1273 return (T) o;
1274 }
1275 return null;
1276 }
1277
1278 /**
1279 * Returns the root cause of a throwable object.
1280 * @param t The object to get root cause for
1281 * @return the root cause of {@code t}
1282 * @since 6639
1283 */
1284 public static Throwable getRootCause(Throwable t) {
1285 Throwable result = t;
1286 if (result != null) {
1287 Throwable cause = result.getCause();
1288 while (cause != null && !cause.equals(result)) {
1289 result = cause;
1290 cause = result.getCause();
1291 }
1292 }
1293 return result;
1294 }
1295
1296 /**
1297 * Adds the given item at the end of a new copy of given array.
1298 * @param <T> type of items
1299 * @param array The source array
1300 * @param item The item to add
1301 * @return An extended copy of {@code array} containing {@code item} as additional last element
1302 * @since 6717
1303 */
1304 public static <T> T[] addInArrayCopy(T[] array, T item) {
1305 T[] biggerCopy = Arrays.copyOf(array, array.length + 1);
1306 biggerCopy[array.length] = item;
1307 return biggerCopy;
1308 }
1309
1310 /**
1311 * If the string {@code s} is longer than {@code maxLength}, the string is cut and "..." is appended.
1312 * @param s String to shorten
1313 * @param maxLength maximum number of characters to keep (not including the "...")
1314 * @return the shortened string
1315 */
1316 public static String shortenString(String s, int maxLength) {
1317 if (s != null && s.length() > maxLength) {
1318 return s.substring(0, maxLength - 3) + "...";
1319 } else {
1320 return s;
1321 }
1322 }
1323
1324 /**
1325 * If the string {@code s} is longer than {@code maxLines} lines, the string is cut and a "..." line is appended.
1326 * @param s String to shorten
1327 * @param maxLines maximum number of lines to keep (including including the "..." line)
1328 * @return the shortened string
1329 */
1330 public static String restrictStringLines(String s, int maxLines) {
1331 if (s == null) {
1332 return null;
1333 } else {
1334 return join("\n", limit(Arrays.asList(s.split("\\n")), maxLines, "..."));
1335 }
1336 }
1337
1338 /**
1339 * If the collection {@code elements} is larger than {@code maxElements} elements,
1340 * the collection is shortened and the {@code overflowIndicator} is appended.
1341 * @param <T> type of elements
1342 * @param elements collection to shorten
1343 * @param maxElements maximum number of elements to keep (including including the {@code overflowIndicator})
1344 * @param overflowIndicator the element used to indicate that the collection has been shortened
1345 * @return the shortened collection
1346 */
1347 public static <T> Collection<T> limit(Collection<T> elements, int maxElements, T overflowIndicator) {
1348 if (elements == null) {
1349 return null;
1350 } else {
1351 if (elements.size() > maxElements) {
1352 final Collection<T> r = new ArrayList<>(maxElements);
1353 final Iterator<T> it = elements.iterator();
1354 while (r.size() < maxElements - 1) {
1355 r.add(it.next());
1356 }
1357 r.add(overflowIndicator);
1358 return r;
1359 } else {
1360 return elements;
1361 }
1362 }
1363 }
1364
1365 /**
1366 * Fixes URL with illegal characters in the query (and fragment) part by
1367 * percent encoding those characters.
1368 *
1369 * special characters like &amp; and # are not encoded
1370 *
1371 * @param url the URL that should be fixed
1372 * @return the repaired URL
1373 */
1374 public static String fixURLQuery(String url) {
1375 if (url.indexOf('?') == -1)
1376 return url;
1377
1378 String query = url.substring(url.indexOf('?') + 1);
1379
1380 StringBuilder sb = new StringBuilder(url.substring(0, url.indexOf('?') + 1));
1381
1382 for (int i = 0; i < query.length(); i++) {
1383 String c = query.substring(i, i + 1);
1384 if (URL_CHARS.contains(c)) {
1385 sb.append(c);
1386 } else {
1387 sb.append(encodeUrl(c));
1388 }
1389 }
1390 return sb.toString();
1391 }
1392
1393 /**
1394 * Translates a string into <code>application/x-www-form-urlencoded</code>
1395 * format. This method uses UTF-8 encoding scheme to obtain the bytes for unsafe
1396 * characters.
1397 *
1398 * @param s <code>String</code> to be translated.
1399 * @return the translated <code>String</code>.
1400 * @see #decodeUrl(String)
1401 * @since 8304
1402 */
1403 public static String encodeUrl(String s) {
1404 final String enc = StandardCharsets.UTF_8.name();
1405 try {
1406 return URLEncoder.encode(s, enc);
1407 } catch (UnsupportedEncodingException e) {
1408 throw new IllegalStateException(e);
1409 }
1410 }
1411
1412 /**
1413 * Decodes a <code>application/x-www-form-urlencoded</code> string.
1414 * UTF-8 encoding is used to determine
1415 * what characters are represented by any consecutive sequences of the
1416 * form "<code>%<i>xy</i></code>".
1417 *
1418 * @param s the <code>String</code> to decode
1419 * @return the newly decoded <code>String</code>
1420 * @see #encodeUrl(String)
1421 * @since 8304
1422 */
1423 public static String decodeUrl(String s) {
1424 final String enc = StandardCharsets.UTF_8.name();
1425 try {
1426 return URLDecoder.decode(s, enc);
1427 } catch (UnsupportedEncodingException e) {
1428 throw new IllegalStateException(e);
1429 }
1430 }
1431
1432 /**
1433 * Determines if the given URL denotes a file on a local filesystem.
1434 * @param url The URL to test
1435 * @return {@code true} if the url points to a local file
1436 * @since 7356
1437 */
1438 public static boolean isLocalUrl(String url) {
1439 if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("resource://"))
1440 return false;
1441 return true;
1442 }
1443
1444 /**
1445 * Creates a new {@link ThreadFactory} which creates threads with names according to {@code nameFormat}.
1446 * @param nameFormat a {@link String#format(String, Object...)} compatible name format; its first argument is a unique thread index
1447 * @param threadPriority the priority of the created threads, see {@link Thread#setPriority(int)}
1448 * @return a new {@link ThreadFactory}
1449 */
1450 public static ThreadFactory newThreadFactory(final String nameFormat, final int threadPriority) {
1451 return new ThreadFactory() {
1452 final AtomicLong count = new AtomicLong(0);
1453 @Override
1454 public Thread newThread(final Runnable runnable) {
1455 final Thread thread = new Thread(runnable, String.format(Locale.ENGLISH, nameFormat, count.getAndIncrement()));
1456 thread.setPriority(threadPriority);
1457 return thread;
1458 }
1459 };
1460 }
1461
1462 /**
1463 * Returns a {@link ForkJoinPool} with the parallelism given by the preference key.
1464 * @param pref The preference key to determine parallelism
1465 * @param nameFormat see {@link #newThreadFactory(String, int)}
1466 * @param threadPriority see {@link #newThreadFactory(String, int)}
1467 * @return a {@link ForkJoinPool}
1468 */
1469 public static ForkJoinPool newForkJoinPool(String pref, final String nameFormat, final int threadPriority) {
1470 int noThreads = Main.pref.getInteger(pref, Runtime.getRuntime().availableProcessors());
1471 return new ForkJoinPool(noThreads, new ForkJoinPool.ForkJoinWorkerThreadFactory() {
1472 final AtomicLong count = new AtomicLong(0);
1473 @Override
1474 public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
1475 final ForkJoinWorkerThread thread = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
1476 thread.setName(String.format(Locale.ENGLISH, nameFormat, count.getAndIncrement()));
1477 thread.setPriority(threadPriority);
1478 return thread;
1479 }
1480 }, null, true);
1481 }
1482
1483 /**
1484 * Returns an executor which executes commands in the calling thread
1485 * @return an executor
1486 */
1487 public static Executor newDirectExecutor() {
1488 return new Executor() {
1489 @Override
1490 public void execute(Runnable command) {
1491 command.run();
1492 }
1493 };
1494 }
1495
1496 /**
1497 * Updates a given system property.
1498 * @param key The property key
1499 * @param value The property value
1500 * @return the previous value of the system property, or {@code null} if it did not have one.
1501 * @since 7894
1502 */
1503 public static String updateSystemProperty(String key, String value) {
1504 if (value != null) {
1505 String old = System.setProperty(key, value);
1506 if (!key.toLowerCase(Locale.ENGLISH).contains("password")) {
1507 Main.debug("System property '" + key + "' set to '" + value + "'. Old value was '" + old + '\'');
1508 } else {
1509 Main.debug("System property '" + key + "' changed.");
1510 }
1511 return old;
1512 }
1513 return null;
1514 }
1515
1516 /**
1517 * Returns a new secure SAX parser, supporting XML namespaces.
1518 * @return a new secure SAX parser, supporting XML namespaces
1519 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1520 * @throws SAXException for SAX errors.
1521 * @since 8287
1522 */
1523 public static SAXParser newSafeSAXParser() throws ParserConfigurationException, SAXException {
1524 SAXParserFactory parserFactory = SAXParserFactory.newInstance();
1525 parserFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
1526 parserFactory.setNamespaceAware(true);
1527 return parserFactory.newSAXParser();
1528 }
1529
1530 /**
1531 * Parse the content given {@link org.xml.sax.InputSource} as XML using the specified {@link org.xml.sax.helpers.DefaultHandler}.
1532 * This method uses a secure SAX parser, supporting XML namespaces.
1533 *
1534 * @param is The InputSource containing the content to be parsed.
1535 * @param dh The SAX DefaultHandler to use.
1536 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1537 * @throws SAXException for SAX errors.
1538 * @throws IOException if any IO errors occur.
1539 * @since 8347
1540 */
1541 public static void parseSafeSAX(InputSource is, DefaultHandler dh) throws ParserConfigurationException, SAXException, IOException {
1542 long start = System.currentTimeMillis();
1543 if (Main.isDebugEnabled()) {
1544 Main.debug("Starting SAX parsing of " + is + " using " + dh);
1545 }
1546 newSafeSAXParser().parse(is, dh);
1547 if (Main.isDebugEnabled()) {
1548 Main.debug("SAX parsing done in " + getDurationString(System.currentTimeMillis() - start));
1549 }
1550 }
1551
1552 /**
1553 * Determines if the filename has one of the given extensions, in a robust manner.
1554 * The comparison is case and locale insensitive.
1555 * @param filename The file name
1556 * @param extensions The list of extensions to look for (without dot)
1557 * @return {@code true} if the filename has one of the given extensions
1558 * @since 8404
1559 */
1560 public static boolean hasExtension(String filename, String... extensions) {
1561 String name = filename.toLowerCase(Locale.ENGLISH).replace("?format=raw", "");
1562 for (String ext : extensions) {
1563 if (name.endsWith('.' + ext.toLowerCase(Locale.ENGLISH)))
1564 return true;
1565 }
1566 return false;
1567 }
1568
1569 /**
1570 * Determines if the file's name has one of the given extensions, in a robust manner.
1571 * The comparison is case and locale insensitive.
1572 * @param file The file
1573 * @param extensions The list of extensions to look for (without dot)
1574 * @return {@code true} if the file's name has one of the given extensions
1575 * @since 8404
1576 */
1577 public static boolean hasExtension(File file, String... extensions) {
1578 return hasExtension(file.getName(), extensions);
1579 }
1580
1581 /**
1582 * Reads the input stream and closes the stream at the end of processing (regardless if an exception was thrown)
1583 *
1584 * @param stream input stream
1585 * @return byte array of data in input stream
1586 * @throws IOException if any I/O error occurs
1587 */
1588 public static byte[] readBytesFromStream(InputStream stream) throws IOException {
1589 try {
1590 ByteArrayOutputStream bout = new ByteArrayOutputStream(stream.available());
1591 byte[] buffer = new byte[2048];
1592 boolean finished = false;
1593 do {
1594 int read = stream.read(buffer);
1595 if (read >= 0) {
1596 bout.write(buffer, 0, read);
1597 } else {
1598 finished = true;
1599 }
1600 } while (!finished);
1601 if (bout.size() == 0)
1602 return null;
1603 return bout.toByteArray();
1604 } finally {
1605 stream.close();
1606 }
1607 }
1608
1609 /**
1610 * Returns the initial capacity to pass to the HashMap / HashSet constructor
1611 * when it is initialized with a known number of entries.
1612 *
1613 * When a HashMap is filled with entries, the underlying array is copied over
1614 * to a larger one multiple times. To avoid this process when the number of
1615 * entries is known in advance, the initial capacity of the array can be
1616 * given to the HashMap constructor. This method returns a suitable value
1617 * that avoids rehashing but doesn't waste memory.
1618 * @param nEntries the number of entries expected
1619 * @param loadFactor the load factor
1620 * @return the initial capacity for the HashMap constructor
1621 */
1622 public static int hashMapInitialCapacity(int nEntries, float loadFactor) {
1623 return (int) Math.ceil(nEntries / loadFactor);
1624 }
1625
1626 /**
1627 * Returns the initial capacity to pass to the HashMap / HashSet constructor
1628 * when it is initialized with a known number of entries.
1629 *
1630 * When a HashMap is filled with entries, the underlying array is copied over
1631 * to a larger one multiple times. To avoid this process when the number of
1632 * entries is known in advance, the initial capacity of the array can be
1633 * given to the HashMap constructor. This method returns a suitable value
1634 * that avoids rehashing but doesn't waste memory.
1635 *
1636 * Assumes default load factor (0.75).
1637 * @param nEntries the number of entries expected
1638 * @return the initial capacity for the HashMap constructor
1639 */
1640 public static int hashMapInitialCapacity(int nEntries) {
1641 return hashMapInitialCapacity(nEntries, 0.75f);
1642 }
1643
1644 /**
1645 * Utility class to save a string along with its rendering direction
1646 * (left-to-right or right-to-left).
1647 */
1648 private static class DirectionString {
1649 public final int direction;
1650 public final String str;
1651
1652 DirectionString(int direction, String str) {
1653 this.direction = direction;
1654 this.str = str;
1655 }
1656 }
1657
1658 /**
1659 * Convert a string to a list of {@link GlyphVector}s. The string may contain
1660 * bi-directional text. The result will be in correct visual order.
1661 * Each element of the resulting list corresponds to one section of the
1662 * string with consistent writing direction (left-to-right or right-to-left).
1663 *
1664 * @param string the string to render
1665 * @param font the font
1666 * @param frc a FontRenderContext object
1667 * @return a list of GlyphVectors
1668 */
1669 public static List<GlyphVector> getGlyphVectorsBidi(String string, Font font, FontRenderContext frc) {
1670 List<GlyphVector> gvs = new ArrayList<>();
1671 Bidi bidi = new Bidi(string, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
1672 byte[] levels = new byte[bidi.getRunCount()];
1673 DirectionString[] dirStrings = new DirectionString[levels.length];
1674 for (int i = 0; i < levels.length; ++i) {
1675 levels[i] = (byte) bidi.getRunLevel(i);
1676 String substr = string.substring(bidi.getRunStart(i), bidi.getRunLimit(i));
1677 int dir = levels[i] % 2 == 0 ? Bidi.DIRECTION_LEFT_TO_RIGHT : Bidi.DIRECTION_RIGHT_TO_LEFT;
1678 dirStrings[i] = new DirectionString(dir, substr);
1679 }
1680 Bidi.reorderVisually(levels, 0, dirStrings, 0, levels.length);
1681 for (int i = 0; i < dirStrings.length; ++i) {
1682 char[] chars = dirStrings[i].str.toCharArray();
1683 gvs.add(font.layoutGlyphVector(frc, chars, 0, chars.length, dirStrings[i].direction));
1684 }
1685 return gvs;
1686 }
1687
1688}
Note: See TracBrowser for help on using the repository browser.