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

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

fix compilation warnings + minor code refactorization

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