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

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

partial revert of r9070 - make build run with Java 9 again

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