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

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

Utils: UTF-8 cannot be unsupported

Removes "may produce NPE" warnings in IDEs.

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