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

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

fix squid:RedundantThrowsDeclarationCheck + consistent Javadoc for exceptions

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