/
Utils.java
1788 lines (1662 loc) · 65.7 KB
/
Utils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.tools;
import static org.openstreetmap.josm.tools.I18n.marktr;
import static org.openstreetmap.josm.tools.I18n.tr;
import static org.openstreetmap.josm.tools.I18n.trn;
import java.awt.Color;
import java.awt.Font;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.AccessibleObject;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.security.AccessController;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivilegedAction;
import java.text.Bidi;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.AbstractCollection;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinWorkerThread;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import java.util.zip.ZipFile;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.openstreetmap.josm.spi.preferences.Config;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* Basic utils, that can be useful in different parts of the program.
*/
public final class Utils {
/** Pattern matching white spaces */
public static final Pattern WHITE_SPACES_PATTERN = Pattern.compile("\\s+");
private static final long MILLIS_OF_SECOND = TimeUnit.SECONDS.toMillis(1);
private static final long MILLIS_OF_MINUTE = TimeUnit.MINUTES.toMillis(1);
private static final long MILLIS_OF_HOUR = TimeUnit.HOURS.toMillis(1);
private static final long MILLIS_OF_DAY = TimeUnit.DAYS.toMillis(1);
/**
* A list of all characters allowed in URLs
*/
public static final String URL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=%";
private static final char[] DEFAULT_STRIP = {'\u200B', '\uFEFF'};
private static final String[] SIZE_UNITS = {"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
// Constants backported from Java 9, see https://bugs.openjdk.java.net/browse/JDK-4477961
private static final double TO_DEGREES = 180.0 / Math.PI;
private static final double TO_RADIANS = Math.PI / 180.0;
private Utils() {
// Hide default constructor for utils classes
}
/**
* Checks if an item that is an instance of clazz exists in the collection
* @param <T> The collection type.
* @param collection The collection
* @param clazz The class to search for.
* @return <code>true</code> if that item exists in the collection.
*/
public static <T> boolean exists(Iterable<T> collection, Class<? extends T> clazz) {
CheckParameterUtil.ensureParameterNotNull(clazz, "clazz");
return StreamUtils.toStream(collection).anyMatch(clazz::isInstance);
}
/**
* Finds the first item in the iterable for which the predicate matches.
* @param <T> The iterable type.
* @param collection The iterable to search in.
* @param predicate The predicate to match
* @return the item or <code>null</code> if there was not match.
*/
public static <T> T find(Iterable<? extends T> collection, Predicate<? super T> predicate) {
for (T item : collection) {
if (predicate.test(item)) {
return item;
}
}
return null;
}
/**
* Finds the first item in the iterable which is of the given type.
* @param <T> The iterable type.
* @param collection The iterable to search in.
* @param clazz The class to search for.
* @return the item or <code>null</code> if there was not match.
*/
@SuppressWarnings("unchecked")
public static <T> T find(Iterable<? extends Object> collection, Class<? extends T> clazz) {
CheckParameterUtil.ensureParameterNotNull(clazz, "clazz");
return (T) find(collection, clazz::isInstance);
}
/**
* Returns the first element from {@code items} which is non-null, or null if all elements are null.
* @param <T> type of items
* @param items the items to look for
* @return first non-null item if there is one
*/
@SafeVarargs
public static <T> T firstNonNull(T... items) {
for (T i : items) {
if (i != null) {
return i;
}
}
return null;
}
/**
* Filter a collection by (sub)class.
* This is an efficient read-only implementation.
* @param <S> Super type of items
* @param <T> type of items
* @param collection the collection
* @param clazz the (sub)class
* @return a read-only filtered collection
*/
public static <S, T extends S> SubclassFilteredCollection<S, T> filteredCollection(Collection<S> collection, final Class<T> clazz) {
CheckParameterUtil.ensureParameterNotNull(clazz, "clazz");
return new SubclassFilteredCollection<>(collection, clazz::isInstance);
}
/**
* Find the index of the first item that matches the predicate.
* @param <T> The iterable type
* @param collection The iterable to iterate over.
* @param predicate The predicate to search for.
* @return The index of the first item or -1 if none was found.
*/
public static <T> int indexOf(Iterable<? extends T> collection, Predicate<? super T> predicate) {
int i = 0;
for (T item : collection) {
if (predicate.test(item))
return i;
i++;
}
return -1;
}
/**
* Ensures a logical condition is met. Otherwise throws an assertion error.
* @param condition the condition to be met
* @param message Formatted error message to raise if condition is not met
* @param data Message parameters, optional
* @throws AssertionError if the condition is not met
*/
public static void ensure(boolean condition, String message, Object...data) {
if (!condition)
throw new AssertionError(
MessageFormat.format(message, data)
);
}
/**
* Return the modulus in the range [0, n)
* @param a dividend
* @param n divisor
* @return modulo (remainder of the Euclidian division of a by n)
*/
public static int mod(int a, int n) {
if (n <= 0)
throw new IllegalArgumentException("n must be <= 0 but is "+n);
int res = a % n;
if (res < 0) {
res += n;
}
return res;
}
/**
* Joins a list of strings (or objects that can be converted to string via
* Object.toString()) into a single string with fields separated by sep.
* @param sep the separator
* @param values collection of objects, null is converted to the
* empty string
* @return null if values is null. The joined string otherwise.
*/
public static String join(String sep, Collection<?> values) {
CheckParameterUtil.ensureParameterNotNull(sep, "sep");
if (values == null)
return null;
StringBuilder s = null;
for (Object a : values) {
if (a == null) {
a = "";
}
if (s != null) {
s.append(sep).append(a);
} else {
s = new StringBuilder(a.toString());
}
}
return s != null ? s.toString() : "";
}
/**
* Converts the given iterable collection as an unordered HTML list.
* @param values The iterable collection
* @return An unordered HTML list
*/
public static String joinAsHtmlUnorderedList(Iterable<?> values) {
return StreamUtils.toStream(values).map(Object::toString).collect(StreamUtils.toHtmlList());
}
/**
* convert Color to String
* (Color.toString() omits alpha value)
* @param c the color
* @return the String representation, including alpha
*/
public static String toString(Color c) {
if (c == null)
return "null";
if (c.getAlpha() == 255)
return String.format("#%06x", c.getRGB() & 0x00ffffff);
else
return String.format("#%06x(alpha=%d)", c.getRGB() & 0x00ffffff, c.getAlpha());
}
/**
* convert float range 0 <= x <= 1 to integer range 0..255
* when dealing with colors and color alpha value
* @param val float value between 0 and 1
* @return null if val is null, the corresponding int if val is in the
* range 0...1. If val is outside that range, return 255
*/
public static Integer colorFloat2int(Float val) {
if (val == null)
return null;
if (val < 0 || val > 1)
return 255;
return (int) (255f * val + 0.5f);
}
/**
* convert integer range 0..255 to float range 0 <= x <= 1
* when dealing with colors and color alpha value
* @param val integer value
* @return corresponding float value in range 0 <= x <= 1
*/
public static Float colorInt2float(Integer val) {
if (val == null)
return null;
if (val < 0 || val > 255)
return 1f;
return ((float) val) / 255f;
}
/**
* Multiply the alpha value of the given color with the factor. The alpha value is clamped to 0..255
* @param color The color
* @param alphaFactor The factor to multiply alpha with.
* @return The new color.
* @since 11692
*/
public static Color alphaMultiply(Color color, float alphaFactor) {
int alpha = Utils.colorFloat2int(Utils.colorInt2float(color.getAlpha()) * alphaFactor);
alpha = clamp(alpha, 0, 255);
return new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha);
}
/**
* Returns the complementary color of {@code clr}.
* @param clr the color to complement
* @return the complementary color of {@code clr}
*/
public static Color complement(Color clr) {
return new Color(255 - clr.getRed(), 255 - clr.getGreen(), 255 - clr.getBlue(), clr.getAlpha());
}
/**
* Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe.
* @param <T> type of items
* @param array The array to copy
* @return A copy of the original array, or {@code null} if {@code array} is null
* @since 6221
*/
public static <T> T[] copyArray(T[] array) {
if (array != null) {
return Arrays.copyOf(array, array.length);
}
return array;
}
/**
* Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe.
* @param array The array to copy
* @return A copy of the original array, or {@code null} if {@code array} is null
* @since 6222
*/
public static char[] copyArray(char... array) {
if (array != null) {
return Arrays.copyOf(array, array.length);
}
return array;
}
/**
* Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe.
* @param array The array to copy
* @return A copy of the original array, or {@code null} if {@code array} is null
* @since 7436
*/
public static int[] copyArray(int... array) {
if (array != null) {
return Arrays.copyOf(array, array.length);
}
return array;
}
/**
* Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe.
* @param array The array to copy
* @return A copy of the original array, or {@code null} if {@code array} is null
* @since 11879
*/
public static byte[] copyArray(byte... array) {
if (array != null) {
return Arrays.copyOf(array, array.length);
}
return array;
}
/**
* Simple file copy function that will overwrite the target file.
* @param in The source file
* @param out The destination file
* @return the path to the target file
* @throws IOException if any I/O error occurs
* @throws IllegalArgumentException if {@code in} or {@code out} is {@code null}
* @since 7003
*/
public static Path copyFile(File in, File out) throws IOException {
CheckParameterUtil.ensureParameterNotNull(in, "in");
CheckParameterUtil.ensureParameterNotNull(out, "out");
return Files.copy(in.toPath(), out.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
/**
* Recursive directory copy function
* @param in The source directory
* @param out The destination directory
* @throws IOException if any I/O error ooccurs
* @throws IllegalArgumentException if {@code in} or {@code out} is {@code null}
* @since 7835
*/
public static void copyDirectory(File in, File out) throws IOException {
CheckParameterUtil.ensureParameterNotNull(in, "in");
CheckParameterUtil.ensureParameterNotNull(out, "out");
if (!out.exists() && !out.mkdirs()) {
Logging.warn("Unable to create directory "+out.getPath());
}
File[] files = in.listFiles();
if (files != null) {
for (File f : files) {
File target = new File(out, f.getName());
if (f.isDirectory()) {
copyDirectory(f, target);
} else {
copyFile(f, target);
}
}
}
}
/**
* Deletes a directory recursively.
* @param path The directory to delete
* @return <code>true</code> if and only if the file or directory is
* successfully deleted; <code>false</code> otherwise
*/
public static boolean deleteDirectory(File path) {
if (path.exists()) {
File[] files = path.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
deleteDirectory(file);
} else {
deleteFile(file);
}
}
}
}
return path.delete();
}
/**
* Deletes a file and log a default warning if the file exists but the deletion fails.
* @param file file to delete
* @return {@code true} if and only if the file does not exist or is successfully deleted; {@code false} otherwise
* @since 10569
*/
public static boolean deleteFileIfExists(File file) {
if (file.exists()) {
return deleteFile(file);
} else {
return true;
}
}
/**
* Deletes a file and log a default warning if the deletion fails.
* @param file file to delete
* @return {@code true} if and only if the file is successfully deleted; {@code false} otherwise
* @since 9296
*/
public static boolean deleteFile(File file) {
return deleteFile(file, marktr("Unable to delete file {0}"));
}
/**
* Deletes a file and log a configurable warning if the deletion fails.
* @param file file to delete
* @param warnMsg warning message. It will be translated with {@code tr()}
* and must contain a single parameter <code>{0}</code> for the file path
* @return {@code true} if and only if the file is successfully deleted; {@code false} otherwise
* @since 9296
*/
public static boolean deleteFile(File file, String warnMsg) {
boolean result = file.delete();
if (!result) {
Logging.warn(tr(warnMsg, file.getPath()));
}
return result;
}
/**
* Creates a directory and log a default warning if the creation fails.
* @param dir directory to create
* @return {@code true} if and only if the directory is successfully created; {@code false} otherwise
* @since 9645
*/
public static boolean mkDirs(File dir) {
return mkDirs(dir, marktr("Unable to create directory {0}"));
}
/**
* Creates a directory and log a configurable warning if the creation fails.
* @param dir directory to create
* @param warnMsg warning message. It will be translated with {@code tr()}
* and must contain a single parameter <code>{0}</code> for the directory path
* @return {@code true} if and only if the directory is successfully created; {@code false} otherwise
* @since 9645
*/
public static boolean mkDirs(File dir, String warnMsg) {
boolean result = dir.mkdirs();
if (!result) {
Logging.warn(tr(warnMsg, dir.getPath()));
}
return result;
}
/**
* <p>Utility method for closing a {@link java.io.Closeable} object.</p>
*
* @param c the closeable object. May be null.
*/
public static void close(Closeable c) {
if (c == null) return;
try {
c.close();
} catch (IOException e) {
Logging.warn(e);
}
}
/**
* <p>Utility method for closing a {@link java.util.zip.ZipFile}.</p>
*
* @param zip the zip file. May be null.
*/
public static void close(ZipFile zip) {
close((Closeable) zip);
}
/**
* Converts the given file to its URL.
* @param f The file to get URL from
* @return The URL of the given file, or {@code null} if not possible.
* @since 6615
*/
public static URL fileToURL(File f) {
if (f != null) {
try {
return f.toURI().toURL();
} catch (MalformedURLException ex) {
Logging.error("Unable to convert filename " + f.getAbsolutePath() + " to URL");
}
}
return null;
}
private static final double EPSILON = 1e-11;
/**
* Determines if the two given double values are equal (their delta being smaller than a fixed epsilon)
* @param a The first double value to compare
* @param b The second double value to compare
* @return {@code true} if {@code abs(a - b) <= 1e-11}, {@code false} otherwise
*/
public static boolean equalsEpsilon(double a, double b) {
return Math.abs(a - b) <= EPSILON;
}
/**
* Calculate MD5 hash of a string and output in hexadecimal format.
* @param data arbitrary String
* @return MD5 hash of data, string of length 32 with characters in range [0-9a-f]
*/
public static String md5Hex(String data) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new JosmRuntimeException(e);
}
byte[] byteData = data.getBytes(StandardCharsets.UTF_8);
byte[] byteDigest = md.digest(byteData);
return toHexString(byteDigest);
}
private static final char[] HEX_ARRAY = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* Converts a byte array to a string of hexadecimal characters.
* Preserves leading zeros, so the size of the output string is always twice
* the number of input bytes.
* @param bytes the byte array
* @return hexadecimal representation
*/
public static String toHexString(byte[] bytes) {
if (bytes == null) {
return "";
}
final int len = bytes.length;
if (len == 0) {
return "";
}
char[] hexChars = new char[len * 2];
for (int i = 0, j = 0; i < len; i++) {
final int v = bytes[i];
hexChars[j++] = HEX_ARRAY[(v & 0xf0) >> 4];
hexChars[j++] = HEX_ARRAY[v & 0xf];
}
return new String(hexChars);
}
/**
* Topological sort.
* @param <T> type of items
*
* @param dependencies contains mappings (key -> value). In the final list of sorted objects, the key will come
* after the value. (In other words, the key depends on the value(s).)
* There must not be cyclic dependencies.
* @return the list of sorted objects
*/
public static <T> List<T> topologicalSort(final MultiMap<T, T> dependencies) {
MultiMap<T, T> deps = new MultiMap<>();
for (T key : dependencies.keySet()) {
deps.putVoid(key);
for (T val : dependencies.get(key)) {
deps.putVoid(val);
deps.put(key, val);
}
}
int size = deps.size();
List<T> sorted = new ArrayList<>();
for (int i = 0; i < size; ++i) {
T parentless = null;
for (T key : deps.keySet()) {
if (deps.get(key).isEmpty()) {
parentless = key;
break;
}
}
if (parentless == null) throw new JosmRuntimeException("parentless");
sorted.add(parentless);
deps.remove(parentless);
for (T key : deps.keySet()) {
deps.remove(key, parentless);
}
}
if (sorted.size() != size) throw new JosmRuntimeException("Wrong size");
return sorted;
}
/**
* Replaces some HTML reserved characters (<, > and &) by their equivalent entity (&lt;, &gt; and &amp;);
* @param s The unescaped string
* @return The escaped string
*/
public static String escapeReservedCharactersHTML(String s) {
return s == null ? "" : s.replace("&", "&").replace("<", "<").replace(">", ">");
}
/**
* Transforms the collection {@code c} into an unmodifiable collection and
* applies the {@link Function} {@code f} on each element upon access.
* @param <A> class of input collection
* @param <B> class of transformed collection
* @param c a collection
* @param f a function that transforms objects of {@code A} to objects of {@code B}
* @return the transformed unmodifiable collection
*/
public static <A, B> Collection<B> transform(final Collection<? extends A> c, final Function<A, B> f) {
return new AbstractCollection<B>() {
@Override
public int size() {
return c.size();
}
@Override
public Iterator<B> iterator() {
return new Iterator<B>() {
private final Iterator<? extends A> it = c.iterator();
@Override
public boolean hasNext() {
return it.hasNext();
}
@Override
public B next() {
return f.apply(it.next());
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
/**
* Transforms the list {@code l} into an unmodifiable list and
* applies the {@link Function} {@code f} on each element upon access.
* @param <A> class of input collection
* @param <B> class of transformed collection
* @param l a collection
* @param f a function that transforms objects of {@code A} to objects of {@code B}
* @return the transformed unmodifiable list
*/
public static <A, B> List<B> transform(final List<? extends A> l, final Function<A, B> f) {
return new AbstractList<B>() {
@Override
public int size() {
return l.size();
}
@Override
public B get(int index) {
return f.apply(l.get(index));
}
};
}
/**
* Determines if the given String would be empty if stripped.
* This is an efficient alternative to {@code strip(s).isEmpty()} that avoids to create useless String object.
* @param str The string to test
* @return {@code true} if the stripped version of {@code s} would be empty.
* @since 11435
*/
public static boolean isStripEmpty(String str) {
if (str != null) {
for (int i = 0; i < str.length(); i++) {
if (!isStrippedChar(str.charAt(i), DEFAULT_STRIP)) {
return false;
}
}
}
return true;
}
/**
* An alternative to {@link String#trim()} to effectively remove all leading
* and trailing white characters, including Unicode ones.
* @param str The string to strip
* @return <code>str</code>, without leading and trailing characters, according to
* {@link Character#isWhitespace(char)} and {@link Character#isSpaceChar(char)}.
* @see <a href="http://closingbraces.net/2008/11/11/javastringtrim/">Java String.trim has a strange idea of whitespace</a>
* @see <a href="https://bugs.openjdk.java.net/browse/JDK-4080617">JDK bug 4080617</a>
* @see <a href="https://bugs.openjdk.java.net/browse/JDK-7190385">JDK bug 7190385</a>
* @since 5772
*/
public static String strip(final String str) {
if (str == null || str.isEmpty()) {
return str;
}
return strip(str, DEFAULT_STRIP);
}
/**
* An alternative to {@link String#trim()} to effectively remove all leading
* and trailing white characters, including Unicode ones.
* @param str The string to strip
* @param skipChars additional characters to skip
* @return <code>str</code>, without leading and trailing characters, according to
* {@link Character#isWhitespace(char)}, {@link Character#isSpaceChar(char)} and skipChars.
* @since 8435
*/
public static String strip(final String str, final String skipChars) {
if (str == null || str.isEmpty()) {
return str;
}
return strip(str, stripChars(skipChars));
}
private static String strip(final String str, final char... skipChars) {
int start = 0;
int end = str.length();
boolean leadingSkipChar = true;
while (leadingSkipChar && start < end) {
leadingSkipChar = isStrippedChar(str.charAt(start), skipChars);
if (leadingSkipChar) {
start++;
}
}
boolean trailingSkipChar = true;
while (trailingSkipChar && end > start + 1) {
trailingSkipChar = isStrippedChar(str.charAt(end - 1), skipChars);
if (trailingSkipChar) {
end--;
}
}
return str.substring(start, end);
}
private static boolean isStrippedChar(char c, final char... skipChars) {
return Character.isWhitespace(c) || Character.isSpaceChar(c) || stripChar(skipChars, c);
}
private static char[] stripChars(final String skipChars) {
if (skipChars == null || skipChars.isEmpty()) {
return DEFAULT_STRIP;
}
char[] chars = new char[DEFAULT_STRIP.length + skipChars.length()];
System.arraycopy(DEFAULT_STRIP, 0, chars, 0, DEFAULT_STRIP.length);
skipChars.getChars(0, skipChars.length(), chars, DEFAULT_STRIP.length);
return chars;
}
private static boolean stripChar(final char[] strip, char c) {
for (char s : strip) {
if (c == s) {
return true;
}
}
return false;
}
/**
* Runs an external command and returns the standard output.
*
* The program is expected to execute fast.
*
* @param command the command with arguments
* @return the output
* @throws IOException when there was an error, e.g. command does not exist
* @throws ExecutionException when the return code is != 0. The output is can be retrieved in the exception message
* @throws InterruptedException if the current thread is {@linkplain Thread#interrupt() interrupted} by another thread while waiting
*/
public static String execOutput(List<String> command) throws IOException, ExecutionException, InterruptedException {
if (Logging.isDebugEnabled()) {
Logging.debug(join(" ", command));
}
Process p = new ProcessBuilder(command).start();
try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder all = null;
String line;
while ((line = input.readLine()) != null) {
if (all == null) {
all = new StringBuilder(line);
} else {
all.append('\n')
.append(line);
}
}
String msg = all != null ? all.toString() : null;
if (p.waitFor() != 0) {
throw new ExecutionException(msg, null);
}
return msg;
}
}
/**
* Returns the JOSM temp directory.
* @return The JOSM temp directory ({@code <java.io.tmpdir>/JOSM}), or {@code null} if {@code java.io.tmpdir} is not defined
* @since 6245
*/
public static File getJosmTempDir() {
String tmpDir = System.getProperty("java.io.tmpdir");
if (tmpDir == null) {
return null;
}
File josmTmpDir = new File(tmpDir, "JOSM");
if (!josmTmpDir.exists() && !josmTmpDir.mkdirs()) {
Logging.warn("Unable to create temp directory " + josmTmpDir);
}
return josmTmpDir;
}
/**
* Returns a simple human readable (hours, minutes, seconds) string for a given duration in milliseconds.
* @param elapsedTime The duration in milliseconds
* @return A human readable string for the given duration
* @throws IllegalArgumentException if elapsedTime is < 0
* @since 6354
*/
public static String getDurationString(long elapsedTime) {
if (elapsedTime < 0) {
throw new IllegalArgumentException("elapsedTime must be >= 0");
}
// Is it less than 1 second ?
if (elapsedTime < MILLIS_OF_SECOND) {
return String.format("%d %s", elapsedTime, tr("ms"));
}
// Is it less than 1 minute ?
if (elapsedTime < MILLIS_OF_MINUTE) {
return String.format("%.1f %s", elapsedTime / (double) MILLIS_OF_SECOND, tr("s"));
}
// Is it less than 1 hour ?
if (elapsedTime < MILLIS_OF_HOUR) {
final long min = elapsedTime / MILLIS_OF_MINUTE;
return String.format("%d %s %d %s", min, tr("min"), (elapsedTime - min * MILLIS_OF_MINUTE) / MILLIS_OF_SECOND, tr("s"));
}
// Is it less than 1 day ?
if (elapsedTime < MILLIS_OF_DAY) {
final long hour = elapsedTime / MILLIS_OF_HOUR;
return String.format("%d %s %d %s", hour, tr("h"), (elapsedTime - hour * MILLIS_OF_HOUR) / MILLIS_OF_MINUTE, tr("min"));
}
long days = elapsedTime / MILLIS_OF_DAY;
return String.format("%d %s %d %s", days, trn("day", "days", days), (elapsedTime - days * MILLIS_OF_DAY) / MILLIS_OF_HOUR, tr("h"));
}
/**
* Returns a human readable representation (B, kB, MB, ...) for the given number of byes.
* @param bytes the number of bytes
* @param locale the locale used for formatting
* @return a human readable representation
* @since 9274
*/
public static String getSizeString(long bytes, Locale locale) {
if (bytes < 0) {
throw new IllegalArgumentException("bytes must be >= 0");
}
int unitIndex = 0;
double value = bytes;
while (value >= 1024 && unitIndex < SIZE_UNITS.length) {
value /= 1024;
unitIndex++;
}
if (value > 100 || unitIndex == 0) {
return String.format(locale, "%.0f %s", value, SIZE_UNITS[unitIndex]);
} else if (value > 10) {
return String.format(locale, "%.1f %s", value, SIZE_UNITS[unitIndex]);
} else {
return String.format(locale, "%.2f %s", value, SIZE_UNITS[unitIndex]);
}
}
/**
* Returns a human readable representation of a list of positions.
* <p>
* For instance, {@code [1,5,2,6,7} yields "1-2,5-7
* @param positionList a list of positions
* @return a human readable representation
*/
public static String getPositionListString(List<Integer> positionList) {
Collections.sort(positionList);
final StringBuilder sb = new StringBuilder(32);
sb.append(positionList.get(0));
int cnt = 0;
int last = positionList.get(0);
for (int i = 1; i < positionList.size(); ++i) {
int cur = positionList.get(i);
if (cur == last + 1) {
++cnt;
} else if (cnt == 0) {
sb.append(',').append(cur);
} else {
sb.append('-').append(last);
sb.append(',').append(cur);
cnt = 0;
}
last = cur;
}
if (cnt >= 1) {
sb.append('-').append(last);
}
return sb.toString();
}
/**
* Returns a list of capture groups if {@link Matcher#matches()}, or {@code null}.
* The first element (index 0) is the complete match.
* Further elements correspond to the parts in parentheses of the regular expression.
* @param m the matcher
* @return a list of capture groups if {@link Matcher#matches()}, or {@code null}.
*/
public static List<String> getMatches(final Matcher m) {
if (m.matches()) {
List<String> result = new ArrayList<>(m.groupCount() + 1);
for (int i = 0; i <= m.groupCount(); i++) {
result.add(m.group(i));
}
return result;
} else {
return null;
}
}
/**
* Cast an object savely.
* @param <T> the target type
* @param o the object to cast
* @param klass the target class (same as T)
* @return null if <code>o</code> is null or the type <code>o</code> is not
* a subclass of <code>klass</code>. The casted value otherwise.
*/
@SuppressWarnings("unchecked")
public static <T> T cast(Object o, Class<T> klass) {
if (klass.isInstance(o)) {
return (T) o;
}