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

Last change on this file since 6999 was 6999, checked in by akks, 10 years ago

fix #9937: Was not importing data from Overpass by remote control (regression of 6972)

  • Property svn:eol-style set to native
File size: 35.1 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.BufferedInputStream;
16import java.io.BufferedReader;
17import java.io.Closeable;
18import java.io.File;
19import java.io.FileInputStream;
20import java.io.FileOutputStream;
21import java.io.IOException;
22import java.io.InputStream;
23import java.io.InputStreamReader;
24import java.io.OutputStream;
25import java.io.UnsupportedEncodingException;
26import java.net.HttpURLConnection;
27import java.net.MalformedURLException;
28import java.net.URL;
29import java.net.URLConnection;
30import java.net.URLEncoder;
31import java.nio.channels.FileChannel;
32import java.nio.charset.Charset;
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.regex.Matcher;
45import java.util.regex.Pattern;
46import java.util.zip.GZIPInputStream;
47import java.util.zip.ZipFile;
48
49import org.apache.tools.bzip2.CBZip2InputStream;
50import org.openstreetmap.josm.Main;
51import org.openstreetmap.josm.data.Version;
52import org.openstreetmap.josm.io.FileImporter;
53
54/**
55 * Basic utils, that can be useful in different parts of the program.
56 */
57public final class Utils {
58
59 public static final Pattern WHITE_SPACES_PATTERN = Pattern.compile("\\s+");
60
61 private Utils() {
62 // Hide default constructor for utils classes
63 }
64
65 /**
66 * UTF-8 (UCS Transformation Format—8-bit).
67 *
68 * <p>Every implementation of the Java platform is required to support UTF-8 (see {@link Charset}).</p>
69 */
70 public static final Charset UTF_8 = Charset.forName("UTF-8");
71
72 private static final int MILLIS_OF_SECOND = 1000;
73 private static final int MILLIS_OF_MINUTE = 60000;
74 private static final int MILLIS_OF_HOUR = 3600000;
75 private static final int MILLIS_OF_DAY = 86400000;
76
77 // Should us keep "%" character when fixing URL or encode it? Let us keep them for now, see #9937
78 public static final String URL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=%";
79
80 /**
81 * Tests whether {@code predicate} applies to at least one elements from {@code collection}.
82 */
83 public static <T> boolean exists(Iterable<? extends T> collection, Predicate<? super T> predicate) {
84 for (T item : collection) {
85 if (predicate.evaluate(item))
86 return true;
87 }
88 return false;
89 }
90
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
98 public static <T> boolean exists(Iterable<T> collection, Class<? extends T> klass) {
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
114 @SuppressWarnings("unchecked")
115 public static <T> T find(Iterable<? super T> collection, Class<? extends T> klass) {
116 for (Object item : collection) {
117 if (klass.isInstance(item))
118 return (T) item;
119 }
120 return null;
121 }
122
123 public static <T> Collection<T> filter(Collection<? extends T> collection, Predicate<? super T> predicate) {
124 return new FilteredCollection<T>(collection, predicate);
125 }
126
127 /**
128 * Returns the first element from {@code items} which is non-null, or null if all elements are null.
129 */
130 public static <T> T firstNonNull(T... items) {
131 for (T i : items) {
132 if (i != null) {
133 return i;
134 }
135 }
136 return null;
137 }
138
139 /**
140 * Filter a collection by (sub)class.
141 * This is an efficient read-only implementation.
142 */
143 public static <S, T extends S> SubclassFilteredCollection<S, T> filteredCollection(Collection<S> collection, final Class<T> klass) {
144 return new SubclassFilteredCollection<S, T>(collection, new Predicate<S>() {
145 @Override
146 public boolean evaluate(S o) {
147 return klass.isInstance(o);
148 }
149 });
150 }
151
152 public static <T> int indexOf(Iterable<? extends T> collection, Predicate<? super T> predicate) {
153 int i = 0;
154 for (T item : collection) {
155 if (predicate.evaluate(item))
156 return i;
157 i++;
158 }
159 return -1;
160 }
161
162 /**
163 * Get minimum of 3 values
164 */
165 public static int min(int a, int b, int c) {
166 if (b < c) {
167 if (a < b)
168 return a;
169 return b;
170 } else {
171 if (a < c)
172 return a;
173 return c;
174 }
175 }
176
177 public static int max(int a, int b, int c, int d) {
178 return Math.max(Math.max(a, b), Math.max(c, d));
179 }
180
181 /**
182 * for convenience: test whether 2 objects are either both null or a.equals(b)
183 */
184 public static <T> boolean equal(T a, T b) {
185 if (a == b)
186 return true;
187 return (a != null && a.equals(b));
188 }
189
190 public static void ensure(boolean condition, String message, Object...data) {
191 if (!condition)
192 throw new AssertionError(
193 MessageFormat.format(message,data)
194 );
195 }
196
197 /**
198 * return the modulus in the range [0, n)
199 */
200 public static int mod(int a, int n) {
201 if (n <= 0)
202 throw new IllegalArgumentException();
203 int res = a % n;
204 if (res < 0) {
205 res += n;
206 }
207 return res;
208 }
209
210 /**
211 * Joins a list of strings (or objects that can be converted to string via
212 * Object.toString()) into a single string with fields separated by sep.
213 * @param sep the separator
214 * @param values collection of objects, null is converted to the
215 * empty string
216 * @return null if values is null. The joined string otherwise.
217 */
218 public static String join(String sep, Collection<?> values) {
219 if (sep == null)
220 throw new IllegalArgumentException();
221 if (values == null)
222 return null;
223 if (values.isEmpty())
224 return "";
225 StringBuilder s = null;
226 for (Object a : values) {
227 if (a == null) {
228 a = "";
229 }
230 if (s != null) {
231 s.append(sep).append(a.toString());
232 } else {
233 s = new StringBuilder(a.toString());
234 }
235 }
236 return s.toString();
237 }
238
239 /**
240 * Converts the given iterable collection as an unordered HTML list.
241 * @param values The iterable collection
242 * @return An unordered HTML list
243 */
244 public static String joinAsHtmlUnorderedList(Iterable<?> values) {
245 StringBuilder sb = new StringBuilder(1024);
246 sb.append("<ul>");
247 for (Object i : values) {
248 sb.append("<li>").append(i).append("</li>");
249 }
250 sb.append("</ul>");
251 return sb.toString();
252 }
253
254 /**
255 * convert Color to String
256 * (Color.toString() omits alpha value)
257 */
258 public static String toString(Color c) {
259 if (c == null)
260 return "null";
261 if (c.getAlpha() == 255)
262 return String.format("#%06x", c.getRGB() & 0x00ffffff);
263 else
264 return String.format("#%06x(alpha=%d)", c.getRGB() & 0x00ffffff, c.getAlpha());
265 }
266
267 /**
268 * convert float range 0 &lt;= x &lt;= 1 to integer range 0..255
269 * when dealing with colors and color alpha value
270 * @return null if val is null, the corresponding int if val is in the
271 * range 0...1. If val is outside that range, return 255
272 */
273 public static Integer color_float2int(Float val) {
274 if (val == null)
275 return null;
276 if (val < 0 || val > 1)
277 return 255;
278 return (int) (255f * val + 0.5f);
279 }
280
281 /**
282 * convert integer range 0..255 to float range 0 &lt;= x &lt;= 1
283 * when dealing with colors and color alpha value
284 */
285 public static Float color_int2float(Integer val) {
286 if (val == null)
287 return null;
288 if (val < 0 || val > 255)
289 return 1f;
290 return ((float) val) / 255f;
291 }
292
293 public static Color complement(Color clr) {
294 return new Color(255 - clr.getRed(), 255 - clr.getGreen(), 255 - clr.getBlue(), clr.getAlpha());
295 }
296
297 /**
298 * Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe.
299 * @param array The array to copy
300 * @return A copy of the original array, or {@code null} if {@code array} is null
301 * @since 6221
302 */
303 public static <T> T[] copyArray(T[] array) {
304 if (array != null) {
305 return Arrays.copyOf(array, array.length);
306 }
307 return null;
308 }
309
310 /**
311 * Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe.
312 * @param array The array to copy
313 * @return A copy of the original array, or {@code null} if {@code array} is null
314 * @since 6222
315 */
316 public static char[] copyArray(char[] array) {
317 if (array != null) {
318 return Arrays.copyOf(array, array.length);
319 }
320 return null;
321 }
322
323 /**
324 * Simple file copy function that will overwrite the target file.<br>
325 * Taken from <a href="http://www.rgagnon.com/javadetails/java-0064.html">this article</a> (CC-NC-BY-SA)
326 * @param in The source file
327 * @param out The destination file
328 * @throws java.io.IOException If any I/O error occurs
329 */
330 public static void copyFile(File in, File out) throws IOException {
331 // TODO: remove this function when we move to Java 7 (use Files.copy instead)
332 FileInputStream inStream = null;
333 FileOutputStream outStream = null;
334 try {
335 inStream = new FileInputStream(in);
336 outStream = new FileOutputStream(out);
337 FileChannel inChannel = inStream.getChannel();
338 inChannel.transferTo(0, inChannel.size(), outStream.getChannel());
339 }
340 catch (IOException e) {
341 throw e;
342 }
343 finally {
344 close(outStream);
345 close(inStream);
346 }
347 }
348
349 public static int copyStream(InputStream source, OutputStream destination) throws IOException {
350 int count = 0;
351 byte[] b = new byte[512];
352 int read;
353 while ((read = source.read(b)) != -1) {
354 count += read;
355 destination.write(b, 0, read);
356 }
357 return count;
358 }
359
360 public static boolean deleteDirectory(File path) {
361 if( path.exists() ) {
362 File[] files = path.listFiles();
363 for (File file : files) {
364 if (file.isDirectory()) {
365 deleteDirectory(file);
366 } else {
367 file.delete();
368 }
369 }
370 }
371 return( path.delete() );
372 }
373
374 /**
375 * <p>Utility method for closing a {@link java.io.Closeable} object.</p>
376 *
377 * @param c the closeable object. May be null.
378 */
379 public static void close(Closeable c) {
380 if (c == null) return;
381 try {
382 c.close();
383 } catch (IOException e) {
384 Main.warn(e);
385 }
386 }
387
388 /**
389 * <p>Utility method for closing a {@link java.util.zip.ZipFile}.</p>
390 *
391 * @param zip the zip file. May be null.
392 */
393 public static void close(ZipFile zip) {
394 if (zip == null) return;
395 try {
396 zip.close();
397 } catch (IOException e) {
398 Main.warn(e);
399 }
400 }
401
402 /**
403 * Converts the given file to its URL.
404 * @param f The file to get URL from
405 * @return The URL of the given file, or {@code null} if not possible.
406 * @since 6615
407 */
408 public static URL fileToURL(File f) {
409 if (f != null) {
410 try {
411 return f.toURI().toURL();
412 } catch (MalformedURLException ex) {
413 Main.error("Unable to convert filename " + f.getAbsolutePath() + " to URL");
414 }
415 }
416 return null;
417 }
418
419 private static final double EPSILON = 1e-11;
420
421 /**
422 * Determines if the two given double values are equal (their delta being smaller than a fixed epsilon)
423 * @param a The first double value to compare
424 * @param b The second double value to compare
425 * @return {@code true} if {@code abs(a - b) <= 1e-11}, {@code false} otherwise
426 */
427 public static boolean equalsEpsilon(double a, double b) {
428 return Math.abs(a - b) <= EPSILON;
429 }
430
431 /**
432 * Copies the string {@code s} to system clipboard.
433 * @param s string to be copied to clipboard.
434 * @return true if succeeded, false otherwise.
435 */
436 public static boolean copyToClipboard(String s) {
437 try {
438 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(s), new ClipboardOwner() {
439
440 @Override
441 public void lostOwnership(Clipboard clpbrd, Transferable t) {
442 }
443 });
444 return true;
445 } catch (IllegalStateException ex) {
446 Main.error(ex);
447 return false;
448 }
449 }
450
451 /**
452 * Extracts clipboard content as string.
453 * @return string clipboard contents if available, {@code null} otherwise.
454 */
455 public static String getClipboardContent() {
456 Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
457 Transferable t = null;
458 for (int tries = 0; t == null && tries < 10; tries++) {
459 try {
460 t = clipboard.getContents(null);
461 } catch (IllegalStateException e) {
462 // Clipboard currently unavailable. On some platforms, the system clipboard is unavailable while it is accessed by another application.
463 try {
464 Thread.sleep(1);
465 } catch (InterruptedException ex) {
466 Main.warn("InterruptedException in "+Utils.class.getSimpleName()+" while getting clipboard content");
467 }
468 }
469 }
470 try {
471 if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
472 return (String) t.getTransferData(DataFlavor.stringFlavor);
473 }
474 } catch (UnsupportedFlavorException ex) {
475 Main.error(ex);
476 return null;
477 } catch (IOException ex) {
478 Main.error(ex);
479 return null;
480 }
481 return null;
482 }
483
484 /**
485 * Calculate MD5 hash of a string and output in hexadecimal format.
486 * @param data arbitrary String
487 * @return MD5 hash of data, string of length 32 with characters in range [0-9a-f]
488 */
489 public static String md5Hex(String data) {
490 byte[] byteData = data.getBytes(UTF_8);
491 MessageDigest md = null;
492 try {
493 md = MessageDigest.getInstance("MD5");
494 } catch (NoSuchAlgorithmException e) {
495 throw new RuntimeException(e);
496 }
497 byte[] byteDigest = md.digest(byteData);
498 return toHexString(byteDigest);
499 }
500
501 private static final char[] HEX_ARRAY = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
502
503 /**
504 * Converts a byte array to a string of hexadecimal characters.
505 * Preserves leading zeros, so the size of the output string is always twice
506 * the number of input bytes.
507 * @param bytes the byte array
508 * @return hexadecimal representation
509 */
510 public static String toHexString(byte[] bytes) {
511
512 if (bytes == null) {
513 return "";
514 }
515
516 final int len = bytes.length;
517 if (len == 0) {
518 return "";
519 }
520
521 char[] hexChars = new char[len * 2];
522 for (int i = 0, j = 0; i < len; i++) {
523 final int v = bytes[i];
524 hexChars[j++] = HEX_ARRAY[(v & 0xf0) >> 4];
525 hexChars[j++] = HEX_ARRAY[v & 0xf];
526 }
527 return new String(hexChars);
528 }
529
530 /**
531 * Topological sort.
532 *
533 * @param dependencies contains mappings (key -&gt; value). In the final list of sorted objects, the key will come
534 * after the value. (In other words, the key depends on the value(s).)
535 * There must not be cyclic dependencies.
536 * @return the list of sorted objects
537 */
538 public static <T> List<T> topologicalSort(final MultiMap<T,T> dependencies) {
539 MultiMap<T,T> deps = new MultiMap<T,T>();
540 for (T key : dependencies.keySet()) {
541 deps.putVoid(key);
542 for (T val : dependencies.get(key)) {
543 deps.putVoid(val);
544 deps.put(key, val);
545 }
546 }
547
548 int size = deps.size();
549 List<T> sorted = new ArrayList<T>();
550 for (int i=0; i<size; ++i) {
551 T parentless = null;
552 for (T key : deps.keySet()) {
553 if (deps.get(key).isEmpty()) {
554 parentless = key;
555 break;
556 }
557 }
558 if (parentless == null) throw new RuntimeException();
559 sorted.add(parentless);
560 deps.remove(parentless);
561 for (T key : deps.keySet()) {
562 deps.remove(key, parentless);
563 }
564 }
565 if (sorted.size() != size) throw new RuntimeException();
566 return sorted;
567 }
568
569 /**
570 * Represents a function that can be applied to objects of {@code A} and
571 * returns objects of {@code B}.
572 * @param <A> class of input objects
573 * @param <B> class of transformed objects
574 */
575 public static interface Function<A, B> {
576
577 /**
578 * Applies the function on {@code x}.
579 * @param x an object of
580 * @return the transformed object
581 */
582 B apply(A x);
583 }
584
585 /**
586 * Transforms the collection {@code c} into an unmodifiable collection and
587 * applies the {@link org.openstreetmap.josm.tools.Utils.Function} {@code f} on each element upon access.
588 * @param <A> class of input collection
589 * @param <B> class of transformed collection
590 * @param c a collection
591 * @param f a function that transforms objects of {@code A} to objects of {@code B}
592 * @return the transformed unmodifiable collection
593 */
594 public static <A, B> Collection<B> transform(final Collection<? extends A> c, final Function<A, B> f) {
595 return new AbstractCollection<B>() {
596
597 @Override
598 public int size() {
599 return c.size();
600 }
601
602 @Override
603 public Iterator<B> iterator() {
604 return new Iterator<B>() {
605
606 private Iterator<? extends A> it = c.iterator();
607
608 @Override
609 public boolean hasNext() {
610 return it.hasNext();
611 }
612
613 @Override
614 public B next() {
615 return f.apply(it.next());
616 }
617
618 @Override
619 public void remove() {
620 throw new UnsupportedOperationException();
621 }
622 };
623 }
624 };
625 }
626
627 /**
628 * Transforms the list {@code l} into an unmodifiable list and
629 * applies the {@link org.openstreetmap.josm.tools.Utils.Function} {@code f} on each element upon access.
630 * @param <A> class of input collection
631 * @param <B> class of transformed collection
632 * @param l a collection
633 * @param f a function that transforms objects of {@code A} to objects of {@code B}
634 * @return the transformed unmodifiable list
635 */
636 public static <A, B> List<B> transform(final List<? extends A> l, final Function<A, B> f) {
637 return new AbstractList<B>() {
638
639
640 @Override
641 public int size() {
642 return l.size();
643 }
644
645 @Override
646 public B get(int index) {
647 return f.apply(l.get(index));
648 }
649
650
651 };
652 }
653
654 private static final Pattern HTTP_PREFFIX_PATTERN = Pattern.compile("https?");
655
656 /**
657 * Opens a HTTP connection to the given URL and sets the User-Agent property to JOSM's one.
658 * @param httpURL The HTTP url to open (must use http:// or https://)
659 * @return An open HTTP connection to the given URL
660 * @throws java.io.IOException if an I/O exception occurs.
661 * @since 5587
662 */
663 public static HttpURLConnection openHttpConnection(URL httpURL) throws IOException {
664 if (httpURL == null || !HTTP_PREFFIX_PATTERN.matcher(httpURL.getProtocol()).matches()) {
665 throw new IllegalArgumentException("Invalid HTTP url");
666 }
667 HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection();
668 connection.setRequestProperty("User-Agent", Version.getInstance().getFullAgentString());
669 connection.setUseCaches(false);
670 return connection;
671 }
672
673 /**
674 * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
675 * @param url The url to open
676 * @return An stream for the given URL
677 * @throws java.io.IOException if an I/O exception occurs.
678 * @since 5867
679 */
680 public static InputStream openURL(URL url) throws IOException {
681 return openURLAndDecompress(url, false);
682 }
683
684 /**
685 * Opens a connection to the given URL, sets the User-Agent property to JOSM's one, and decompresses stream if necessary.
686 * @param url The url to open
687 * @param decompress whether to wrap steam in a {@link GZIPInputStream} or {@link CBZip2InputStream}
688 * if the {@code Content-Type} header is set accordingly.
689 * @return An stream for the given URL
690 * @throws IOException if an I/O exception occurs.
691 * @since 6421
692 */
693 public static InputStream openURLAndDecompress(final URL url, final boolean decompress) throws IOException {
694 final URLConnection connection = setupURLConnection(url.openConnection());
695 if (decompress && "application/x-gzip".equals(connection.getHeaderField("Content-Type"))) {
696 return new GZIPInputStream(connection.getInputStream());
697 } else if (decompress && "application/x-bzip2".equals(connection.getHeaderField("Content-Type"))) {
698 return FileImporter.getBZip2InputStream(new BufferedInputStream(connection.getInputStream()));
699 } else {
700 return connection.getInputStream();
701 }
702 }
703
704 /***
705 * Setups the given URL connection to match JOSM needs by setting its User-Agent and timeout properties.
706 * @param connection The connection to setup
707 * @return {@code connection}, with updated properties
708 * @since 5887
709 */
710 public static URLConnection setupURLConnection(URLConnection connection) {
711 if (connection != null) {
712 connection.setRequestProperty("User-Agent", Version.getInstance().getFullAgentString());
713 connection.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect",15)*1000);
714 connection.setReadTimeout(Main.pref.getInteger("socket.timeout.read",30)*1000);
715 }
716 return connection;
717 }
718
719 /**
720 * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
721 * @param url The url to open
722 * @return An buffered stream reader for the given URL (using UTF-8)
723 * @throws java.io.IOException if an I/O exception occurs.
724 * @since 5868
725 */
726 public static BufferedReader openURLReader(URL url) throws IOException {
727 return openURLReaderAndDecompress(url, false);
728 }
729
730 /**
731 * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
732 * @param url The url to open
733 * @param decompress whether to wrap steam in a {@link GZIPInputStream} or {@link CBZip2InputStream}
734 * if the {@code Content-Type} header is set accordingly.
735 * @return An buffered stream reader for the given URL (using UTF-8)
736 * @throws IOException if an I/O exception occurs.
737 * @since 6421
738 */
739 public static BufferedReader openURLReaderAndDecompress(final URL url, final boolean decompress) throws IOException {
740 return new BufferedReader(new InputStreamReader(openURLAndDecompress(url, decompress), UTF_8));
741 }
742
743 /**
744 * Opens a HTTP connection to the given URL, sets the User-Agent property to JOSM's one and optionnaly disables Keep-Alive.
745 * @param httpURL The HTTP url to open (must use http:// or https://)
746 * @param keepAlive whether not to set header {@code Connection=close}
747 * @return An open HTTP connection to the given URL
748 * @throws java.io.IOException if an I/O exception occurs.
749 * @since 5587
750 */
751 public static HttpURLConnection openHttpConnection(URL httpURL, boolean keepAlive) throws IOException {
752 HttpURLConnection connection = openHttpConnection(httpURL);
753 if (!keepAlive) {
754 connection.setRequestProperty("Connection", "close");
755 }
756 if (Main.isDebugEnabled()) {
757 try {
758 Main.debug("REQUEST: "+ connection.getRequestProperties());
759 } catch (IllegalStateException e) {
760 Main.warn(e);
761 }
762 }
763 return connection;
764 }
765
766 /**
767 * An alternative to {@link String#trim()} to effectively remove all leading and trailing white characters, including Unicode ones.
768 * @see <a href="http://closingbraces.net/2008/11/11/javastringtrim/">Java’s String.trim has a strange idea of whitespace</a>
769 * @see <a href="https://bugs.openjdk.java.net/browse/JDK-4080617">JDK bug 4080617</a>
770 * @param str The string to strip
771 * @return <code>str</code>, without leading and trailing characters, according to
772 * {@link Character#isWhitespace(char)} and {@link Character#isSpaceChar(char)}.
773 * @since 5772
774 */
775 public static String strip(String str) {
776 if (str == null || str.isEmpty()) {
777 return str;
778 }
779 int start = 0, end = str.length();
780 boolean leadingWhite = true;
781 while (leadingWhite && start < end) {
782 char c = str.charAt(start);
783 // '\u200B' (ZERO WIDTH SPACE character) needs to be handled manually because of change in Unicode 6.0 (Java 7, see #8918)
784 // same for '\uFEFF' (ZERO WIDTH NO-BREAK SPACE)
785 leadingWhite = (Character.isWhitespace(c) || Character.isSpaceChar(c) || c == '\u200B' || c == '\uFEFF');
786 if (leadingWhite) {
787 start++;
788 }
789 }
790 boolean trailingWhite = true;
791 while (trailingWhite && end > start+1) {
792 char c = str.charAt(end-1);
793 trailingWhite = (Character.isWhitespace(c) || Character.isSpaceChar(c) || c == '\u200B' || c == '\uFEFF');
794 if (trailingWhite) {
795 end--;
796 }
797 }
798 return str.substring(start, end);
799 }
800
801 /**
802 * Runs an external command and returns the standard output.
803 *
804 * The program is expected to execute fast.
805 *
806 * @param command the command with arguments
807 * @return the output
808 * @throws IOException when there was an error, e.g. command does not exist
809 */
810 public static String execOutput(List<String> command) throws IOException {
811 if (Main.isDebugEnabled()) {
812 Main.debug(join(" ", command));
813 }
814 Process p = new ProcessBuilder(command).start();
815 BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream(), UTF_8));
816 StringBuilder all = null;
817 String line;
818 while ((line = input.readLine()) != null) {
819 if (all == null) {
820 all = new StringBuilder(line);
821 } else {
822 all.append("\n");
823 all.append(line);
824 }
825 }
826 Utils.close(input);
827 return all != null ? all.toString() : null;
828 }
829
830 /**
831 * Returns the JOSM temp directory.
832 * @return The JOSM temp directory ({@code <java.io.tmpdir>/JOSM}), or {@code null} if {@code java.io.tmpdir} is not defined
833 * @since 6245
834 */
835 public static File getJosmTempDir() {
836 String tmpDir = System.getProperty("java.io.tmpdir");
837 if (tmpDir == null) {
838 return null;
839 }
840 File josmTmpDir = new File(tmpDir, "JOSM");
841 if (!josmTmpDir.exists() && !josmTmpDir.mkdirs()) {
842 Main.warn("Unable to create temp directory "+josmTmpDir);
843 }
844 return josmTmpDir;
845 }
846
847 /**
848 * Returns a simple human readable (hours, minutes, seconds) string for a given duration in milliseconds.
849 * @param elapsedTime The duration in milliseconds
850 * @return A human readable string for the given duration
851 * @throws IllegalArgumentException if elapsedTime is &lt; 0
852 * @since 6354
853 */
854 public static String getDurationString(long elapsedTime) throws IllegalArgumentException {
855 if (elapsedTime < 0) {
856 throw new IllegalArgumentException("elapsedTime must be > 0");
857 }
858 // Is it less than 1 second ?
859 if (elapsedTime < MILLIS_OF_SECOND) {
860 return String.format("%d %s", elapsedTime, tr("ms"));
861 }
862 // Is it less than 1 minute ?
863 if (elapsedTime < MILLIS_OF_MINUTE) {
864 return String.format("%.1f %s", elapsedTime / (float) MILLIS_OF_SECOND, tr("s"));
865 }
866 // Is it less than 1 hour ?
867 if (elapsedTime < MILLIS_OF_HOUR) {
868 final long min = elapsedTime / MILLIS_OF_MINUTE;
869 return String.format("%d %s %d %s", min, tr("min"), (elapsedTime - min * MILLIS_OF_MINUTE) / MILLIS_OF_SECOND, tr("s"));
870 }
871 // Is it less than 1 day ?
872 if (elapsedTime < MILLIS_OF_DAY) {
873 final long hour = elapsedTime / MILLIS_OF_HOUR;
874 return String.format("%d %s %d %s", hour, tr("h"), (elapsedTime - hour * MILLIS_OF_HOUR) / MILLIS_OF_MINUTE, tr("min"));
875 }
876 long days = elapsedTime / MILLIS_OF_DAY;
877 return String.format("%d %s %d %s", days, trn("day", "days", days), (elapsedTime - days * MILLIS_OF_DAY) / MILLIS_OF_HOUR, tr("h"));
878 }
879
880 /**
881 * Returns a human readable representation of a list of positions.
882 * <p>
883 * For instance, {@code [1,5,2,6,7} yields "1-2,5-7
884 * @param positionList a list of positions
885 * @return a human readable representation
886 */
887 public static String getPositionListString(List<Integer> positionList) {
888 Collections.sort(positionList);
889 final StringBuilder sb = new StringBuilder(32);
890 sb.append(positionList.get(0));
891 int cnt = 0;
892 int last = positionList.get(0);
893 for (int i = 1; i < positionList.size(); ++i) {
894 int cur = positionList.get(i);
895 if (cur == last + 1) {
896 ++cnt;
897 } else if (cnt == 0) {
898 sb.append(",").append(cur);
899 } else {
900 sb.append("-").append(last);
901 sb.append(",").append(cur);
902 cnt = 0;
903 }
904 last = cur;
905 }
906 if (cnt >= 1) {
907 sb.append("-").append(last);
908 }
909 return sb.toString();
910 }
911
912
913 /**
914 * Returns a list of capture groups if {@link Matcher#matches()}, or {@code null}.
915 * The first element (index 0) is the complete match.
916 * Further elements correspond to the parts in parentheses of the regular expression.
917 * @param m the matcher
918 * @return a list of capture groups if {@link Matcher#matches()}, or {@code null}.
919 */
920 public static List<String> getMatches(final Matcher m) {
921 if (m.matches()) {
922 List<String> result = new ArrayList<String>(m.groupCount() + 1);
923 for (int i = 0; i <= m.groupCount(); i++) {
924 result.add(m.group(i));
925 }
926 return result;
927 } else {
928 return null;
929 }
930 }
931
932 /**
933 * Cast an object savely.
934 * @param <T> the target type
935 * @param o the object to cast
936 * @param klass the target class (same as T)
937 * @return null if <code>o</code> is null or the type <code>o</code> is not
938 * a subclass of <code>klass</code>. The casted value otherwise.
939 */
940 @SuppressWarnings("unchecked")
941 public static <T> T cast(Object o, Class<T> klass) {
942 if (klass.isInstance(o)) {
943 return (T) o;
944 }
945 return null;
946 }
947
948 /**
949 * Returns the root cause of a throwable object.
950 * @param t The object to get root cause for
951 * @return the root cause of {@code t}
952 * @since 6639
953 */
954 public static Throwable getRootCause(Throwable t) {
955 Throwable result = t;
956 if (result != null) {
957 Throwable cause = result.getCause();
958 while (cause != null && cause != result) {
959 result = cause;
960 cause = result.getCause();
961 }
962 }
963 return result;
964 }
965
966 /**
967 * Adds the given item at the end of a new copy of given array.
968 * @param array The source array
969 * @param item The item to add
970 * @return An extended copy of {@code array} containing {@code item} as additional last element
971 * @since 6717
972 */
973 public static <T> T[] addInArrayCopy(T[] array, T item) {
974 T[] biggerCopy = Arrays.copyOf(array, array.length + 1);
975 biggerCopy[array.length] = item;
976 return biggerCopy;
977 }
978
979 /**
980 * If the string {@code s} is longer than {@code maxLength}, the string is cut and "..." is appended.
981 */
982 public static String shortenString(String s, int maxLength) {
983 if (s != null && s.length() > maxLength) {
984 return s.substring(0, maxLength - 3) + "...";
985 } else {
986 return s;
987 }
988 }
989
990 /**
991 * Fixes URL with illegal characters in the query (and fragment) part by
992 * percent encoding those characters.
993 *
994 * special characters like &amp; and # are not encoded
995 *
996 * @param url the URL that should be fixed
997 * @return the repaired URL
998 */
999 public static String fixURLQuery(String url) {
1000 if (url.indexOf('?') == -1)
1001 return url;
1002
1003 String query = url.substring(url.indexOf('?') + 1);
1004
1005 StringBuilder sb = new StringBuilder(url.substring(0, url.indexOf('?') + 1));
1006
1007 for (int i=0; i<query.length(); i++) {
1008 String c = query.substring(i, i+1);
1009 if (URL_CHARS.contains(c)) {
1010 sb.append(c);
1011 } else {
1012 try {
1013 sb.append(URLEncoder.encode(c, "UTF-8"));
1014 } catch (UnsupportedEncodingException ex) {
1015 throw new RuntimeException(ex);
1016 }
1017 }
1018 }
1019 return sb.toString();
1020 }
1021
1022}
Note: See TracBrowser for help on using the repository browser.