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

Last change on this file since 8416 was 8404, checked in by Don-vip, 9 years ago

When doing a String.toLowerCase()/toUpperCase() call, use a Locale. This avoids problems with certain locales, i.e. Lithuanian or Turkish. See PMD UseLocaleWithCaseConversions rule and String.toLowerCase() javadoc.

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