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

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

see #8465 - last batch of try-with-resources

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