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

Last change on this file since 6740 was 6740, checked in by simon04, 10 years ago

fix #9191 - MapCSS: Add option to include colour preferences of external styles

The syntax is the same as for the XML styles: name#123456

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