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

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

javadoc update

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