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

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

javadoc update

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