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

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

see #9952: added parameter extrude.initial-move-threshold (to tune ignoring small movements in extrude mode)

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