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

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

fix some Sonar issues introduced recently

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