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

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

see #8465 - use diamond operator where applicable

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