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

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

Refactoring: use Fork/Join Tasks for parallel execution

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