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

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

fix #11485 - robustness to JDK-6322854 when dealing with system selection

  • Property svn:eol-style set to native
File size: 46.0 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 @Override
502 public void lostOwnership(Clipboard clpbrd, Transferable t) {
503 // Do nothing
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 {@code Transferable} object.
515 * @param clipboard clipboard from which contents are retrieved
516 * @return clipboard contents if available, {@code null} otherwise.
517 * @since 8429
518 */
519 public static Transferable getTransferableContent(Clipboard clipboard) {
520 Transferable t = null;
521 for (int tries = 0; t == null && tries < 10; tries++) {
522 try {
523 t = clipboard.getContents(null);
524 } catch (IllegalStateException e) {
525 // Clipboard currently unavailable.
526 // On some platforms, the system clipboard is unavailable while it is accessed by another application.
527 try {
528 Thread.sleep(1);
529 } catch (InterruptedException ex) {
530 Main.warn("InterruptedException in "+Utils.class.getSimpleName()+" while getting clipboard content");
531 }
532 } catch (NullPointerException e) {
533 // JDK-6322854: On Linux/X11, NPE can happen for unknown reasons, on all versions of Java
534 Main.error(e);
535 }
536 }
537 return t;
538 }
539
540 /**
541 * Extracts clipboard content as string.
542 * @return string clipboard contents if available, {@code null} otherwise.
543 */
544 public static String getClipboardContent() {
545 Transferable t = getTransferableContent(Toolkit.getDefaultToolkit().getSystemClipboard());
546 try {
547 if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
548 return (String) t.getTransferData(DataFlavor.stringFlavor);
549 }
550 } catch (UnsupportedFlavorException | IOException ex) {
551 Main.error(ex);
552 return null;
553 }
554 return null;
555 }
556
557 /**
558 * Calculate MD5 hash of a string and output in hexadecimal format.
559 * @param data arbitrary String
560 * @return MD5 hash of data, string of length 32 with characters in range [0-9a-f]
561 */
562 public static String md5Hex(String data) {
563 MessageDigest md = null;
564 try {
565 md = MessageDigest.getInstance("MD5");
566 } catch (NoSuchAlgorithmException e) {
567 throw new RuntimeException(e);
568 }
569 byte[] byteData = data.getBytes(StandardCharsets.UTF_8);
570 byte[] byteDigest = md.digest(byteData);
571 return toHexString(byteDigest);
572 }
573
574 private static final char[] HEX_ARRAY = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
575
576 /**
577 * Converts a byte array to a string of hexadecimal characters.
578 * Preserves leading zeros, so the size of the output string is always twice
579 * the number of input bytes.
580 * @param bytes the byte array
581 * @return hexadecimal representation
582 */
583 public static String toHexString(byte[] bytes) {
584
585 if (bytes == null) {
586 return "";
587 }
588
589 final int len = bytes.length;
590 if (len == 0) {
591 return "";
592 }
593
594 char[] hexChars = new char[len * 2];
595 for (int i = 0, j = 0; i < len; i++) {
596 final int v = bytes[i];
597 hexChars[j++] = HEX_ARRAY[(v & 0xf0) >> 4];
598 hexChars[j++] = HEX_ARRAY[v & 0xf];
599 }
600 return new String(hexChars);
601 }
602
603 /**
604 * Topological sort.
605 *
606 * @param dependencies contains mappings (key -&gt; value). In the final list of sorted objects, the key will come
607 * after the value. (In other words, the key depends on the value(s).)
608 * There must not be cyclic dependencies.
609 * @return the list of sorted objects
610 */
611 public static <T> List<T> topologicalSort(final MultiMap<T,T> dependencies) {
612 MultiMap<T,T> deps = new MultiMap<>();
613 for (T key : dependencies.keySet()) {
614 deps.putVoid(key);
615 for (T val : dependencies.get(key)) {
616 deps.putVoid(val);
617 deps.put(key, val);
618 }
619 }
620
621 int size = deps.size();
622 List<T> sorted = new ArrayList<>();
623 for (int i=0; i<size; ++i) {
624 T parentless = null;
625 for (T key : deps.keySet()) {
626 if (deps.get(key).isEmpty()) {
627 parentless = key;
628 break;
629 }
630 }
631 if (parentless == null) throw new RuntimeException();
632 sorted.add(parentless);
633 deps.remove(parentless);
634 for (T key : deps.keySet()) {
635 deps.remove(key, parentless);
636 }
637 }
638 if (sorted.size() != size) throw new RuntimeException();
639 return sorted;
640 }
641
642 /**
643 * Represents a function that can be applied to objects of {@code A} and
644 * returns objects of {@code B}.
645 * @param <A> class of input objects
646 * @param <B> class of transformed objects
647 */
648 public static interface Function<A, B> {
649
650 /**
651 * Applies the function on {@code x}.
652 * @param x an object of
653 * @return the transformed object
654 */
655 B apply(A x);
656 }
657
658 /**
659 * Transforms the collection {@code c} into an unmodifiable collection and
660 * applies the {@link org.openstreetmap.josm.tools.Utils.Function} {@code f} on each element upon access.
661 * @param <A> class of input collection
662 * @param <B> class of transformed collection
663 * @param c a collection
664 * @param f a function that transforms objects of {@code A} to objects of {@code B}
665 * @return the transformed unmodifiable collection
666 */
667 public static <A, B> Collection<B> transform(final Collection<? extends A> c, final Function<A, B> f) {
668 return new AbstractCollection<B>() {
669
670 @Override
671 public int size() {
672 return c.size();
673 }
674
675 @Override
676 public Iterator<B> iterator() {
677 return new Iterator<B>() {
678
679 private Iterator<? extends A> it = c.iterator();
680
681 @Override
682 public boolean hasNext() {
683 return it.hasNext();
684 }
685
686 @Override
687 public B next() {
688 return f.apply(it.next());
689 }
690
691 @Override
692 public void remove() {
693 throw new UnsupportedOperationException();
694 }
695 };
696 }
697 };
698 }
699
700 /**
701 * Transforms the list {@code l} into an unmodifiable list and
702 * applies the {@link org.openstreetmap.josm.tools.Utils.Function} {@code f} on each element upon access.
703 * @param <A> class of input collection
704 * @param <B> class of transformed collection
705 * @param l a collection
706 * @param f a function that transforms objects of {@code A} to objects of {@code B}
707 * @return the transformed unmodifiable list
708 */
709 public static <A, B> List<B> transform(final List<? extends A> l, final Function<A, B> f) {
710 return new AbstractList<B>() {
711
712 @Override
713 public int size() {
714 return l.size();
715 }
716
717 @Override
718 public B get(int index) {
719 return f.apply(l.get(index));
720 }
721 };
722 }
723
724 private static final Pattern HTTP_PREFFIX_PATTERN = Pattern.compile("https?");
725
726 /**
727 * Opens a HTTP connection to the given URL and sets the User-Agent property to JOSM's one.
728 * @param httpURL The HTTP url to open (must use http:// or https://)
729 * @return An open HTTP connection to the given URL
730 * @throws java.io.IOException if an I/O exception occurs.
731 * @since 5587
732 */
733 public static HttpURLConnection openHttpConnection(URL httpURL) throws IOException {
734 if (httpURL == null || !HTTP_PREFFIX_PATTERN.matcher(httpURL.getProtocol()).matches()) {
735 throw new IllegalArgumentException("Invalid HTTP url");
736 }
737 if (Main.isDebugEnabled()) {
738 Main.debug("Opening HTTP connection to "+httpURL.toExternalForm());
739 }
740 HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection();
741 connection.setRequestProperty("User-Agent", Version.getInstance().getFullAgentString());
742 connection.setUseCaches(false);
743 return connection;
744 }
745
746 /**
747 * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
748 * @param url The url to open
749 * @return An stream for the given URL
750 * @throws java.io.IOException if an I/O exception occurs.
751 * @since 5867
752 */
753 public static InputStream openURL(URL url) throws IOException {
754 return openURLAndDecompress(url, false);
755 }
756
757 /**
758 * Opens a connection to the given URL, sets the User-Agent property to JOSM's one, and decompresses stream if necessary.
759 * @param url The url to open
760 * @param decompress whether to wrap steam in a {@link GZIPInputStream} or {@link BZip2CompressorInputStream}
761 * if the {@code Content-Type} header is set accordingly.
762 * @return An stream for the given URL
763 * @throws IOException if an I/O exception occurs.
764 * @since 6421
765 */
766 public static InputStream openURLAndDecompress(final URL url, final boolean decompress) throws IOException {
767 final URLConnection connection = setupURLConnection(url.openConnection());
768 final InputStream in = connection.getInputStream();
769 if (decompress) {
770 switch (connection.getHeaderField("Content-Type")) {
771 case "application/zip":
772 return getZipInputStream(in);
773 case "application/x-gzip":
774 return getGZipInputStream(in);
775 case "application/x-bzip2":
776 return getBZip2InputStream(in);
777 }
778 }
779 return in;
780 }
781
782 /**
783 * Returns a Bzip2 input stream wrapping given input stream.
784 * @param in The raw input stream
785 * @return a Bzip2 input stream wrapping given input stream, or {@code null} if {@code in} is {@code null}
786 * @throws IOException if the given input stream does not contain valid BZ2 header
787 * @since 7867
788 */
789 public static BZip2CompressorInputStream getBZip2InputStream(InputStream in) throws IOException {
790 if (in == null) {
791 return null;
792 }
793 return new BZip2CompressorInputStream(in, /* see #9537 */ true);
794 }
795
796 /**
797 * Returns a Gzip input stream wrapping given input stream.
798 * @param in The raw input stream
799 * @return a Gzip 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 GZIPInputStream getGZipInputStream(InputStream in) throws IOException {
804 if (in == null) {
805 return null;
806 }
807 return new GZIPInputStream(in);
808 }
809
810 /**
811 * Returns a Zip input stream wrapping given input stream.
812 * @param in The raw input stream
813 * @return a Zip input stream wrapping given input stream, or {@code null} if {@code in} is {@code null}
814 * @throws IOException if an I/O error has occurred
815 * @since 7119
816 */
817 public static ZipInputStream getZipInputStream(InputStream in) throws IOException {
818 if (in == null) {
819 return null;
820 }
821 ZipInputStream zis = new ZipInputStream(in, StandardCharsets.UTF_8);
822 // Positions the stream at the beginning of first entry
823 ZipEntry ze = zis.getNextEntry();
824 if (ze != null && Main.isDebugEnabled()) {
825 Main.debug("Zip entry: "+ze.getName());
826 }
827 return zis;
828 }
829
830 /***
831 * Setups the given URL connection to match JOSM needs by setting its User-Agent and timeout properties.
832 * @param connection The connection to setup
833 * @return {@code connection}, with updated properties
834 * @since 5887
835 */
836 public static URLConnection setupURLConnection(URLConnection connection) {
837 if (connection != null) {
838 connection.setRequestProperty("User-Agent", Version.getInstance().getFullAgentString());
839 connection.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect",15)*1000);
840 connection.setReadTimeout(Main.pref.getInteger("socket.timeout.read",30)*1000);
841 }
842 return connection;
843 }
844
845 /**
846 * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
847 * @param url The url to open
848 * @return An buffered stream reader for the given URL (using UTF-8)
849 * @throws java.io.IOException if an I/O exception occurs.
850 * @since 5868
851 */
852 public static BufferedReader openURLReader(URL url) throws IOException {
853 return openURLReaderAndDecompress(url, false);
854 }
855
856 /**
857 * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
858 * @param url The url to open
859 * @param decompress whether to wrap steam in a {@link GZIPInputStream} or {@link BZip2CompressorInputStream}
860 * if the {@code Content-Type} header is set accordingly.
861 * @return An buffered stream reader for the given URL (using UTF-8)
862 * @throws IOException if an I/O exception occurs.
863 * @since 6421
864 */
865 public static BufferedReader openURLReaderAndDecompress(final URL url, final boolean decompress) throws IOException {
866 return new BufferedReader(new InputStreamReader(openURLAndDecompress(url, decompress), StandardCharsets.UTF_8));
867 }
868
869 /**
870 * Opens a HTTP connection to the given URL, sets the User-Agent property to JOSM's one and optionnaly disables Keep-Alive.
871 * @param httpURL The HTTP url to open (must use http:// or https://)
872 * @param keepAlive whether not to set header {@code Connection=close}
873 * @return An open HTTP connection to the given URL
874 * @throws java.io.IOException if an I/O exception occurs.
875 * @since 5587
876 */
877 public static HttpURLConnection openHttpConnection(URL httpURL, boolean keepAlive) throws IOException {
878 HttpURLConnection connection = openHttpConnection(httpURL);
879 if (!keepAlive) {
880 connection.setRequestProperty("Connection", "close");
881 }
882 if (Main.isDebugEnabled()) {
883 try {
884 Main.debug("REQUEST: "+ connection.getRequestProperties());
885 } catch (IllegalStateException e) {
886 Main.warn(e);
887 }
888 }
889 return connection;
890 }
891
892 /**
893 * An alternative to {@link String#trim()} to effectively remove all leading and trailing white characters, including Unicode ones.
894 * @param str The string to strip
895 * @return <code>str</code>, without leading and trailing characters, according to
896 * {@link Character#isWhitespace(char)} and {@link Character#isSpaceChar(char)}.
897 * @see <a href="http://closingbraces.net/2008/11/11/javastringtrim/">Java’s String.trim has a strange idea of whitespace</a>
898 * @see <a href="https://bugs.openjdk.java.net/browse/JDK-4080617">JDK bug 4080617</a>
899 * @since 5772
900 */
901 public static String strip(String str) {
902 if (str == null || str.isEmpty()) {
903 return str;
904 }
905 int start = 0, end = str.length();
906 boolean leadingWhite = true;
907 while (leadingWhite && start < end) {
908 char c = str.charAt(start);
909 // '\u200B' (ZERO WIDTH SPACE character) needs to be handled manually because of change in Unicode 6.0 (Java 7, see #8918)
910 // same for '\uFEFF' (ZERO WIDTH NO-BREAK SPACE)
911 leadingWhite = (Character.isWhitespace(c) || Character.isSpaceChar(c) || c == '\u200B' || c == '\uFEFF');
912 if (leadingWhite) {
913 start++;
914 }
915 }
916 boolean trailingWhite = true;
917 while (trailingWhite && end > start+1) {
918 char c = str.charAt(end-1);
919 trailingWhite = (Character.isWhitespace(c) || Character.isSpaceChar(c) || c == '\u200B' || c == '\uFEFF');
920 if (trailingWhite) {
921 end--;
922 }
923 }
924 return str.substring(start, end);
925 }
926
927 /**
928 * Runs an external command and returns the standard output.
929 *
930 * The program is expected to execute fast.
931 *
932 * @param command the command with arguments
933 * @return the output
934 * @throws IOException when there was an error, e.g. command does not exist
935 */
936 public static String execOutput(List<String> command) throws IOException {
937 if (Main.isDebugEnabled()) {
938 Main.debug(join(" ", command));
939 }
940 Process p = new ProcessBuilder(command).start();
941 try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
942 StringBuilder all = null;
943 String line;
944 while ((line = input.readLine()) != null) {
945 if (all == null) {
946 all = new StringBuilder(line);
947 } else {
948 all.append('\n');
949 all.append(line);
950 }
951 }
952 return all != null ? all.toString() : null;
953 }
954 }
955
956 /**
957 * Returns the JOSM temp directory.
958 * @return The JOSM temp directory ({@code <java.io.tmpdir>/JOSM}), or {@code null} if {@code java.io.tmpdir} is not defined
959 * @since 6245
960 */
961 public static File getJosmTempDir() {
962 String tmpDir = System.getProperty("java.io.tmpdir");
963 if (tmpDir == null) {
964 return null;
965 }
966 File josmTmpDir = new File(tmpDir, "JOSM");
967 if (!josmTmpDir.exists() && !josmTmpDir.mkdirs()) {
968 Main.warn("Unable to create temp directory "+josmTmpDir);
969 }
970 return josmTmpDir;
971 }
972
973 /**
974 * Returns a simple human readable (hours, minutes, seconds) string for a given duration in milliseconds.
975 * @param elapsedTime The duration in milliseconds
976 * @return A human readable string for the given duration
977 * @throws IllegalArgumentException if elapsedTime is &lt; 0
978 * @since 6354
979 */
980 public static String getDurationString(long elapsedTime) {
981 if (elapsedTime < 0) {
982 throw new IllegalArgumentException("elapsedTime must be >= 0");
983 }
984 // Is it less than 1 second ?
985 if (elapsedTime < MILLIS_OF_SECOND) {
986 return String.format("%d %s", elapsedTime, tr("ms"));
987 }
988 // Is it less than 1 minute ?
989 if (elapsedTime < MILLIS_OF_MINUTE) {
990 return String.format("%.1f %s", elapsedTime / (double) MILLIS_OF_SECOND, tr("s"));
991 }
992 // Is it less than 1 hour ?
993 if (elapsedTime < MILLIS_OF_HOUR) {
994 final long min = elapsedTime / MILLIS_OF_MINUTE;
995 return String.format("%d %s %d %s", min, tr("min"), (elapsedTime - min * MILLIS_OF_MINUTE) / MILLIS_OF_SECOND, tr("s"));
996 }
997 // Is it less than 1 day ?
998 if (elapsedTime < MILLIS_OF_DAY) {
999 final long hour = elapsedTime / MILLIS_OF_HOUR;
1000 return String.format("%d %s %d %s", hour, tr("h"), (elapsedTime - hour * MILLIS_OF_HOUR) / MILLIS_OF_MINUTE, tr("min"));
1001 }
1002 long days = elapsedTime / MILLIS_OF_DAY;
1003 return String.format("%d %s %d %s", days, trn("day", "days", days), (elapsedTime - days * MILLIS_OF_DAY) / MILLIS_OF_HOUR, tr("h"));
1004 }
1005
1006 /**
1007 * Returns a human readable representation of a list of positions.
1008 * <p>
1009 * For instance, {@code [1,5,2,6,7} yields "1-2,5-7
1010 * @param positionList a list of positions
1011 * @return a human readable representation
1012 */
1013 public static String getPositionListString(List<Integer> positionList) {
1014 Collections.sort(positionList);
1015 final StringBuilder sb = new StringBuilder(32);
1016 sb.append(positionList.get(0));
1017 int cnt = 0;
1018 int last = positionList.get(0);
1019 for (int i = 1; i < positionList.size(); ++i) {
1020 int cur = positionList.get(i);
1021 if (cur == last + 1) {
1022 ++cnt;
1023 } else if (cnt == 0) {
1024 sb.append(',').append(cur);
1025 } else {
1026 sb.append('-').append(last);
1027 sb.append(',').append(cur);
1028 cnt = 0;
1029 }
1030 last = cur;
1031 }
1032 if (cnt >= 1) {
1033 sb.append('-').append(last);
1034 }
1035 return sb.toString();
1036 }
1037
1038
1039 /**
1040 * Returns a list of capture groups if {@link Matcher#matches()}, or {@code null}.
1041 * The first element (index 0) is the complete match.
1042 * Further elements correspond to the parts in parentheses of the regular expression.
1043 * @param m the matcher
1044 * @return a list of capture groups if {@link Matcher#matches()}, or {@code null}.
1045 */
1046 public static List<String> getMatches(final Matcher m) {
1047 if (m.matches()) {
1048 List<String> result = new ArrayList<>(m.groupCount() + 1);
1049 for (int i = 0; i <= m.groupCount(); i++) {
1050 result.add(m.group(i));
1051 }
1052 return result;
1053 } else {
1054 return null;
1055 }
1056 }
1057
1058 /**
1059 * Cast an object savely.
1060 * @param <T> the target type
1061 * @param o the object to cast
1062 * @param klass the target class (same as T)
1063 * @return null if <code>o</code> is null or the type <code>o</code> is not
1064 * a subclass of <code>klass</code>. The casted value otherwise.
1065 */
1066 @SuppressWarnings("unchecked")
1067 public static <T> T cast(Object o, Class<T> klass) {
1068 if (klass.isInstance(o)) {
1069 return (T) o;
1070 }
1071 return null;
1072 }
1073
1074 /**
1075 * Returns the root cause of a throwable object.
1076 * @param t The object to get root cause for
1077 * @return the root cause of {@code t}
1078 * @since 6639
1079 */
1080 public static Throwable getRootCause(Throwable t) {
1081 Throwable result = t;
1082 if (result != null) {
1083 Throwable cause = result.getCause();
1084 while (cause != null && !cause.equals(result)) {
1085 result = cause;
1086 cause = result.getCause();
1087 }
1088 }
1089 return result;
1090 }
1091
1092 /**
1093 * Adds the given item at the end of a new copy of given array.
1094 * @param array The source array
1095 * @param item The item to add
1096 * @return An extended copy of {@code array} containing {@code item} as additional last element
1097 * @since 6717
1098 */
1099 public static <T> T[] addInArrayCopy(T[] array, T item) {
1100 T[] biggerCopy = Arrays.copyOf(array, array.length + 1);
1101 biggerCopy[array.length] = item;
1102 return biggerCopy;
1103 }
1104
1105 /**
1106 * If the string {@code s} is longer than {@code maxLength}, the string is cut and "..." is appended.
1107 * @param s String to shorten
1108 * @param maxLength maximum number of characters to keep (not including the "...")
1109 * @return the shortened string
1110 */
1111 public static String shortenString(String s, int maxLength) {
1112 if (s != null && s.length() > maxLength) {
1113 return s.substring(0, maxLength - 3) + "...";
1114 } else {
1115 return s;
1116 }
1117 }
1118
1119 /**
1120 * Fixes URL with illegal characters in the query (and fragment) part by
1121 * percent encoding those characters.
1122 *
1123 * special characters like &amp; and # are not encoded
1124 *
1125 * @param url the URL that should be fixed
1126 * @return the repaired URL
1127 */
1128 public static String fixURLQuery(String url) {
1129 if (url.indexOf('?') == -1)
1130 return url;
1131
1132 String query = url.substring(url.indexOf('?') + 1);
1133
1134 StringBuilder sb = new StringBuilder(url.substring(0, url.indexOf('?') + 1));
1135
1136 for (int i=0; i<query.length(); i++) {
1137 String c = query.substring(i, i+1);
1138 if (URL_CHARS.contains(c)) {
1139 sb.append(c);
1140 } else {
1141 sb.append(encodeUrl(c));
1142 }
1143 }
1144 return sb.toString();
1145 }
1146
1147 /**
1148 * Translates a string into <code>application/x-www-form-urlencoded</code>
1149 * format. This method uses UTF-8 encoding scheme to obtain the bytes for unsafe
1150 * characters.
1151 *
1152 * @param s <code>String</code> to be translated.
1153 * @return the translated <code>String</code>.
1154 * @see #decodeUrl(String)
1155 * @since 8304
1156 */
1157 public static String encodeUrl(String s) {
1158 final String enc = StandardCharsets.UTF_8.name();
1159 try {
1160 return URLEncoder.encode(s, enc);
1161 } catch (UnsupportedEncodingException e) {
1162 Main.error(e);
1163 return null;
1164 }
1165 }
1166
1167 /**
1168 * Decodes a <code>application/x-www-form-urlencoded</code> string.
1169 * UTF-8 encoding is used to determine
1170 * what characters are represented by any consecutive sequences of the
1171 * form "<code>%<i>xy</i></code>".
1172 *
1173 * @param s the <code>String</code> to decode
1174 * @return the newly decoded <code>String</code>
1175 * @see #encodeUrl(String)
1176 * @since 8304
1177 */
1178 public static String decodeUrl(String s) {
1179 final String enc = StandardCharsets.UTF_8.name();
1180 try {
1181 return URLDecoder.decode(s, enc);
1182 } catch (UnsupportedEncodingException e) {
1183 Main.error(e);
1184 return null;
1185 }
1186 }
1187
1188 /**
1189 * Determines if the given URL denotes a file on a local filesystem.
1190 * @param url The URL to test
1191 * @return {@code true} if the url points to a local file
1192 * @since 7356
1193 */
1194 public static boolean isLocalUrl(String url) {
1195 if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("resource://"))
1196 return false;
1197 return true;
1198 }
1199
1200 /**
1201 * Returns a pair containing the number of threads (n), and a thread pool (if n > 1) to perform
1202 * multi-thread computation in the context of the given preference key.
1203 * @param pref The preference key
1204 * @return a pair containing the number of threads (n), and a thread pool (if n > 1, null otherwise)
1205 * @since 7423
1206 */
1207 public static Pair<Integer, ExecutorService> newThreadPool(String pref) {
1208 int noThreads = Main.pref.getInteger(pref, Runtime.getRuntime().availableProcessors());
1209 ExecutorService pool = noThreads <= 1 ? null : Executors.newFixedThreadPool(noThreads);
1210 return new Pair<>(noThreads, pool);
1211 }
1212
1213 /**
1214 * Updates a given system property.
1215 * @param key The property key
1216 * @param value The property value
1217 * @return the previous value of the system property, or {@code null} if it did not have one.
1218 * @since 7894
1219 */
1220 public static String updateSystemProperty(String key, String value) {
1221 if (value != null) {
1222 String old = System.setProperty(key, value);
1223 if (!key.toLowerCase(Locale.ENGLISH).contains("password")) {
1224 Main.debug("System property '"+key+"' set to '"+value+"'. Old value was '"+old+"'");
1225 } else {
1226 Main.debug("System property '"+key+"' changed.");
1227 }
1228 return old;
1229 }
1230 return null;
1231 }
1232
1233 /**
1234 * Returns a new secure SAX parser, supporting XML namespaces.
1235 * @return a new secure SAX parser, supporting XML namespaces
1236 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1237 * @throws SAXException for SAX errors.
1238 * @since 8287
1239 */
1240 public static SAXParser newSafeSAXParser() throws ParserConfigurationException, SAXException {
1241 SAXParserFactory parserFactory = SAXParserFactory.newInstance();
1242 parserFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
1243 parserFactory.setNamespaceAware(true);
1244 return parserFactory.newSAXParser();
1245 }
1246
1247 /**
1248 * Parse the content given {@link org.xml.sax.InputSource} as XML using the specified {@link org.xml.sax.helpers.DefaultHandler}.
1249 * This method uses a secure SAX parser, supporting XML namespaces.
1250 *
1251 * @param is The InputSource containing the content to be parsed.
1252 * @param dh The SAX DefaultHandler to use.
1253 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1254 * @throws SAXException for SAX errors.
1255 * @throws IOException if any IO errors occur.
1256 * @since 8347
1257 */
1258 public static void parseSafeSAX(InputSource is, DefaultHandler dh) throws ParserConfigurationException, SAXException, IOException {
1259 long start = System.currentTimeMillis();
1260 if (Main.isDebugEnabled()) {
1261 Main.debug("Starting SAX parsing of "+is+" using "+dh);
1262 }
1263 newSafeSAXParser().parse(is, dh);
1264 if (Main.isDebugEnabled()) {
1265 Main.debug("SAX parsing done in " + getDurationString(System.currentTimeMillis()-start));
1266 }
1267 }
1268
1269 /**
1270 * Determines if the filename has one of the given extensions, in a robust manner.
1271 * The comparison is case and locale insensitive.
1272 * @param filename The file name
1273 * @param extensions The list of extensions to look for (without dot)
1274 * @return {@code true} if the filename has one of the given extensions
1275 * @since 8404
1276 */
1277 public static boolean hasExtension(String filename, String ... extensions) {
1278 String name = filename.toLowerCase(Locale.ENGLISH);
1279 for (String ext : extensions)
1280 if (name.endsWith("."+ext.toLowerCase(Locale.ENGLISH)))
1281 return true;
1282 return false;
1283 }
1284
1285 /**
1286 * Determines if the file's name has one of the given extensions, in a robust manner.
1287 * The comparison is case and locale insensitive.
1288 * @param file The file
1289 * @param extensions The list of extensions to look for (without dot)
1290 * @return {@code true} if the file's name has one of the given extensions
1291 * @since 8404
1292 */
1293 public static boolean hasExtension(File file, String ... extensions) {
1294 return hasExtension(file.getName(), extensions);
1295 }
1296}
Note: See TracBrowser for help on using the repository browser.