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

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

checkstyle, code cleanup

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