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

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

checkstyle

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