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

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

see #15310 - remove most of deprecated APIs

  • Property svn:eol-style set to native
File size: 61.9 KB
RevLine 
[3504]1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
[9296]4import static org.openstreetmap.josm.tools.I18n.marktr;
[6354]5import static org.openstreetmap.josm.tools.I18n.tr;
6import static org.openstreetmap.josm.tools.I18n.trn;
7
[3859]8import java.awt.Color;
[8994]9import java.awt.Font;
10import java.awt.font.FontRenderContext;
11import java.awt.font.GlyphVector;
[5868]12import java.io.BufferedReader;
[8568]13import java.io.ByteArrayOutputStream;
[5874]14import java.io.Closeable;
[4065]15import java.io.File;
16import java.io.IOException;
17import java.io.InputStream;
[5868]18import java.io.InputStreamReader;
[6972]19import java.io.UnsupportedEncodingException;
[10223]20import java.lang.reflect.AccessibleObject;
[6615]21import java.net.MalformedURLException;
[5587]22import java.net.URL;
[8304]23import java.net.URLDecoder;
[6972]24import java.net.URLEncoder;
[7082]25import java.nio.charset.StandardCharsets;
[7003]26import java.nio.file.Files;
27import java.nio.file.Path;
28import java.nio.file.StandardCopyOption;
[10223]29import java.security.AccessController;
[4403]30import java.security.MessageDigest;
31import java.security.NoSuchAlgorithmException;
[10223]32import java.security.PrivilegedAction;
[8994]33import java.text.Bidi;
[12219]34import java.text.DateFormat;
[4069]35import java.text.MessageFormat;
[12219]36import java.text.ParseException;
[5578]37import java.util.AbstractCollection;
38import java.util.AbstractList;
[4668]39import java.util.ArrayList;
[6221]40import java.util.Arrays;
[3848]41import java.util.Collection;
[6652]42import java.util.Collections;
[12219]43import java.util.Date;
[4816]44import java.util.Iterator;
[4668]45import java.util.List;
[8404]46import java.util.Locale;
[12987]47import java.util.Optional;
[12830]48import java.util.concurrent.ExecutionException;
[9352]49import java.util.concurrent.Executor;
[9351]50import java.util.concurrent.ForkJoinPool;
51import java.util.concurrent.ForkJoinWorkerThread;
[8602]52import java.util.concurrent.ThreadFactory;
[11288]53import java.util.concurrent.TimeUnit;
[8734]54import java.util.concurrent.atomic.AtomicLong;
[12604]55import java.util.function.Consumer;
[10692]56import java.util.function.Function;
[10691]57import java.util.function.Predicate;
[6538]58import java.util.regex.Matcher;
[6823]59import java.util.regex.Pattern;
[12594]60import java.util.stream.Stream;
[5874]61import java.util.zip.ZipFile;
[3848]62
[8287]63import javax.xml.XMLConstants;
[10404]64import javax.xml.parsers.DocumentBuilder;
65import javax.xml.parsers.DocumentBuilderFactory;
[8287]66import javax.xml.parsers.ParserConfigurationException;
67import javax.xml.parsers.SAXParser;
68import javax.xml.parsers.SAXParserFactory;
69
[12846]70import org.openstreetmap.josm.spi.preferences.Config;
[10404]71import org.w3c.dom.Document;
[8347]72import org.xml.sax.InputSource;
[8287]73import org.xml.sax.SAXException;
[8347]74import org.xml.sax.helpers.DefaultHandler;
[5587]75
[4069]76/**
77 * Basic utils, that can be useful in different parts of the program.
78 */
[6362]79public final class Utils {
[3504]80
[9231]81 /** Pattern matching white spaces */
[6823]82 public static final Pattern WHITE_SPACES_PATTERN = Pattern.compile("\\s+");
83
[11288]84 private static final long MILLIS_OF_SECOND = TimeUnit.SECONDS.toMillis(1);
85 private static final long MILLIS_OF_MINUTE = TimeUnit.MINUTES.toMillis(1);
86 private static final long MILLIS_OF_HOUR = TimeUnit.HOURS.toMillis(1);
87 private static final long MILLIS_OF_DAY = TimeUnit.DAYS.toMillis(1);
[6806]88
[10287]89 /**
90 * A list of all characters allowed in URLs
91 */
[6999]92 public static final String URL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=%";
93
[9419]94 private static final char[] DEFAULT_STRIP = {'\u200B', '\uFEFF'};
[8567]95
[9954]96 private static final String[] SIZE_UNITS = {"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
97
[12015]98 // Constants backported from Java 9, see https://bugs.openjdk.java.net/browse/JDK-4477961
[12013]99 private static final double TO_DEGREES = 180.0 / Math.PI;
100 private static final double TO_RADIANS = Math.PI / 180.0;
101
[10287]102 private Utils() {
103 // Hide default constructor for utils classes
104 }
105
[6772]106 /**
[10287]107 * Checks if an item that is an instance of clazz exists in the collection
108 * @param <T> The collection type.
109 * @param collection The collection
110 * @param clazz The class to search for.
111 * @return <code>true</code> if that item exists in the collection.
112 */
113 public static <T> boolean exists(Iterable<T> collection, Class<? extends T> clazz) {
[10715]114 CheckParameterUtil.ensureParameterNotNull(clazz, "clazz");
[10742]115 return StreamUtils.toStream(collection).anyMatch(clazz::isInstance);
[3836]116 }
117
[10287]118 /**
119 * Finds the first item in the iterable for which the predicate matches.
120 * @param <T> The iterable type.
121 * @param collection The iterable to search in.
122 * @param predicate The predicate to match
123 * @return the item or <code>null</code> if there was not match.
124 */
[3836]125 public static <T> T find(Iterable<? extends T> collection, Predicate<? super T> predicate) {
126 for (T item : collection) {
[10691]127 if (predicate.test(item)) {
[3836]128 return item;
[10287]129 }
[3836]130 }
131 return null;
132 }
133
[10287]134 /**
135 * Finds the first item in the iterable which is of the given type.
136 * @param <T> The iterable type.
137 * @param collection The iterable to search in.
138 * @param clazz The class to search for.
139 * @return the item or <code>null</code> if there was not match.
140 */
[4065]141 @SuppressWarnings("unchecked")
[10287]142 public static <T> T find(Iterable<? extends Object> collection, Class<? extends T> clazz) {
[10715]143 CheckParameterUtil.ensureParameterNotNull(clazz, "clazz");
144 return (T) find(collection, clazz::isInstance);
[3836]145 }
[4408]146
[10287]147 /**
[6610]148 * Returns the first element from {@code items} which is non-null, or null if all elements are null.
[9246]149 * @param <T> type of items
[7019]150 * @param items the items to look for
151 * @return first non-null item if there is one
[6610]152 */
[7019]153 @SafeVarargs
[5159]154 public static <T> T firstNonNull(T... items) {
155 for (T i : items) {
156 if (i != null) {
157 return i;
158 }
159 }
160 return null;
161 }
162
[4100]163 /**
164 * Filter a collection by (sub)class.
165 * This is an efficient read-only implementation.
[9246]166 * @param <S> Super type of items
167 * @param <T> type of items
[8928]168 * @param collection the collection
[10287]169 * @param clazz the (sub)class
[8928]170 * @return a read-only filtered collection
[4100]171 */
[10287]172 public static <S, T extends S> SubclassFilteredCollection<S, T> filteredCollection(Collection<S> collection, final Class<T> clazz) {
[10715]173 CheckParameterUtil.ensureParameterNotNull(clazz, "clazz");
174 return new SubclassFilteredCollection<>(collection, clazz::isInstance);
[4100]175 }
[3836]176
[10287]177 /**
178 * Find the index of the first item that matches the predicate.
179 * @param <T> The iterable type
180 * @param collection The iterable to iterate over.
181 * @param predicate The predicate to search for.
182 * @return The index of the first item or -1 if none was found.
183 */
[3869]184 public static <T> int indexOf(Iterable<? extends T> collection, Predicate<? super T> predicate) {
185 int i = 0;
186 for (T item : collection) {
[10691]187 if (predicate.test(item))
[3869]188 return i;
189 i++;
190 }
191 return -1;
192 }
193
[3674]194 /**
[7867]195 * Ensures a logical condition is met. Otherwise throws an assertion error.
196 * @param condition the condition to be met
197 * @param message Formatted error message to raise if condition is not met
198 * @param data Message parameters, optional
199 * @throws AssertionError if the condition is not met
200 */
[4069]201 public static void ensure(boolean condition, String message, Object...data) {
202 if (!condition)
203 throw new AssertionError(
[8510]204 MessageFormat.format(message, data)
[4069]205 );
206 }
207
[3796]208 /**
[8926]209 * Return the modulus in the range [0, n)
210 * @param a dividend
211 * @param n divisor
212 * @return modulo (remainder of the Euclidian division of a by n)
[3711]213 */
214 public static int mod(int a, int n) {
215 if (n <= 0)
[7864]216 throw new IllegalArgumentException("n must be <= 0 but is "+n);
[3711]217 int res = a % n;
218 if (res < 0) {
219 res += n;
220 }
221 return res;
222 }
223
[3848]224 /**
225 * Joins a list of strings (or objects that can be converted to string via
226 * Object.toString()) into a single string with fields separated by sep.
227 * @param sep the separator
228 * @param values collection of objects, null is converted to the
229 * empty string
230 * @return null if values is null. The joined string otherwise.
231 */
232 public static String join(String sep, Collection<?> values) {
[7864]233 CheckParameterUtil.ensureParameterNotNull(sep, "sep");
[3848]234 if (values == null)
235 return null;
236 StringBuilder s = null;
237 for (Object a : values) {
238 if (a == null) {
239 a = "";
240 }
[4197]241 if (s != null) {
[8376]242 s.append(sep).append(a);
[3848]243 } else {
244 s = new StringBuilder(a.toString());
245 }
246 }
[7867]247 return s != null ? s.toString() : "";
[3848]248 }
[3859]249
[6524]250 /**
251 * Converts the given iterable collection as an unordered HTML list.
252 * @param values The iterable collection
253 * @return An unordered HTML list
254 */
255 public static String joinAsHtmlUnorderedList(Iterable<?> values) {
[10718]256 return StreamUtils.toStream(values).map(Object::toString).collect(StreamUtils.toHtmlList());
[5132]257 }
258
[3859]259 /**
260 * convert Color to String
261 * (Color.toString() omits alpha value)
[8928]262 * @param c the color
263 * @return the String representation, including alpha
[3859]264 */
265 public static String toString(Color c) {
266 if (c == null)
267 return "null";
268 if (c.getAlpha() == 255)
269 return String.format("#%06x", c.getRGB() & 0x00ffffff);
270 else
271 return String.format("#%06x(alpha=%d)", c.getRGB() & 0x00ffffff, c.getAlpha());
272 }
[3865]273
274 /**
[6830]275 * convert float range 0 &lt;= x &lt;= 1 to integer range 0..255
[3865]276 * when dealing with colors and color alpha value
[9231]277 * @param val float value between 0 and 1
[3879]278 * @return null if val is null, the corresponding int if val is in the
279 * range 0...1. If val is outside that range, return 255
[3865]280 */
[10748]281 public static Integer colorFloat2int(Float val) {
[3865]282 if (val == null)
283 return null;
284 if (val < 0 || val > 1)
285 return 255;
286 return (int) (255f * val + 0.5f);
287 }
288
289 /**
[6830]290 * convert integer range 0..255 to float range 0 &lt;= x &lt;= 1
[6749]291 * when dealing with colors and color alpha value
[8928]292 * @param val integer value
293 * @return corresponding float value in range 0 &lt;= x &lt;= 1
[3865]294 */
[10748]295 public static Float colorInt2float(Integer val) {
[3865]296 if (val == null)
297 return null;
298 if (val < 0 || val > 255)
299 return 1f;
300 return ((float) val) / 255f;
301 }
302
[9231]303 /**
[11692]304 * Multiply the alpha value of the given color with the factor. The alpha value is clamped to 0..255
305 * @param color The color
306 * @param alphaFactor The factor to multiply alpha with.
307 * @return The new color.
308 * @since 11692
309 */
310 public static Color alphaMultiply(Color color, float alphaFactor) {
311 int alpha = Utils.colorFloat2int(Utils.colorInt2float(color.getAlpha()) * alphaFactor);
312 alpha = clamp(alpha, 0, 255);
313 return new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha);
314 }
315
316 /**
[9231]317 * Returns the complementary color of {@code clr}.
318 * @param clr the color to complement
319 * @return the complementary color of {@code clr}
320 */
[4069]321 public static Color complement(Color clr) {
322 return new Color(255 - clr.getRed(), 255 - clr.getGreen(), 255 - clr.getBlue(), clr.getAlpha());
323 }
[4065]324
[5874]325 /**
[6221]326 * Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe.
[9246]327 * @param <T> type of items
[6221]328 * @param array The array to copy
329 * @return A copy of the original array, or {@code null} if {@code array} is null
330 * @since 6221
331 */
332 public static <T> T[] copyArray(T[] array) {
333 if (array != null) {
334 return Arrays.copyOf(array, array.length);
335 }
[10315]336 return array;
[6221]337 }
[6792]338
[6221]339 /**
[6222]340 * Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe.
341 * @param array The array to copy
342 * @return A copy of the original array, or {@code null} if {@code array} is null
343 * @since 6222
344 */
[12798]345 public static char[] copyArray(char... array) {
[6222]346 if (array != null) {
347 return Arrays.copyOf(array, array.length);
348 }
[10315]349 return array;
[6222]350 }
[6792]351
[6222]352 /**
[7436]353 * Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe.
354 * @param array The array to copy
355 * @return A copy of the original array, or {@code null} if {@code array} is null
356 * @since 7436
357 */
[11747]358 public static int[] copyArray(int... array) {
[7436]359 if (array != null) {
360 return Arrays.copyOf(array, array.length);
361 }
[10315]362 return array;
[7436]363 }
364
365 /**
[11879]366 * Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe.
367 * @param array The array to copy
368 * @return A copy of the original array, or {@code null} if {@code array} is null
369 * @since 11879
370 */
371 public static byte[] copyArray(byte... array) {
372 if (array != null) {
373 return Arrays.copyOf(array, array.length);
374 }
375 return array;
376 }
377
378 /**
[7835]379 * Simple file copy function that will overwrite the target file.
[5874]380 * @param in The source file
381 * @param out The destination file
[7003]382 * @return the path to the target file
[8291]383 * @throws IOException if any I/O error occurs
384 * @throws IllegalArgumentException if {@code in} or {@code out} is {@code null}
[7003]385 * @since 7003
[5874]386 */
[7835]387 public static Path copyFile(File in, File out) throws IOException {
[7003]388 CheckParameterUtil.ensureParameterNotNull(in, "in");
389 CheckParameterUtil.ensureParameterNotNull(out, "out");
390 return Files.copy(in.toPath(), out.toPath(), StandardCopyOption.REPLACE_EXISTING);
[5874]391 }
[6070]392
[7835]393 /**
394 * Recursive directory copy function
395 * @param in The source directory
396 * @param out The destination directory
[8291]397 * @throws IOException if any I/O error ooccurs
398 * @throws IllegalArgumentException if {@code in} or {@code out} is {@code null}
[7835]399 * @since 7835
400 */
401 public static void copyDirectory(File in, File out) throws IOException {
402 CheckParameterUtil.ensureParameterNotNull(in, "in");
403 CheckParameterUtil.ensureParameterNotNull(out, "out");
404 if (!out.exists() && !out.mkdirs()) {
[12620]405 Logging.warn("Unable to create directory "+out.getPath());
[7835]406 }
[8308]407 File[] files = in.listFiles();
408 if (files != null) {
409 for (File f : files) {
410 File target = new File(out, f.getName());
411 if (f.isDirectory()) {
412 copyDirectory(f, target);
413 } else {
414 copyFile(f, target);
415 }
[7835]416 }
417 }
418 }
419
[7867]420 /**
[7835]421 * Deletes a directory recursively.
422 * @param path The directory to delete
423 * @return <code>true</code> if and only if the file or directory is
424 * successfully deleted; <code>false</code> otherwise
425 */
[4065]426 public static boolean deleteDirectory(File path) {
[8443]427 if (path.exists()) {
[4065]428 File[] files = path.listFiles();
[8308]429 if (files != null) {
430 for (File file : files) {
431 if (file.isDirectory()) {
432 deleteDirectory(file);
[9296]433 } else {
434 deleteFile(file);
[8308]435 }
[4065]436 }
437 }
438 }
[7835]439 return path.delete();
[4065]440 }
[4087]441
442 /**
[10570]443 * Deletes a file and log a default warning if the file exists but the deletion fails.
444 * @param file file to delete
445 * @return {@code true} if and only if the file does not exist or is successfully deleted; {@code false} otherwise
446 * @since 10569
447 */
448 public static boolean deleteFileIfExists(File file) {
449 if (file.exists()) {
450 return deleteFile(file);
451 } else {
452 return true;
453 }
454 }
455
456 /**
[9296]457 * Deletes a file and log a default warning if the deletion fails.
458 * @param file file to delete
459 * @return {@code true} if and only if the file is successfully deleted; {@code false} otherwise
[9297]460 * @since 9296
[9296]461 */
462 public static boolean deleteFile(File file) {
463 return deleteFile(file, marktr("Unable to delete file {0}"));
464 }
465
466 /**
467 * Deletes a file and log a configurable warning if the deletion fails.
468 * @param file file to delete
469 * @param warnMsg warning message. It will be translated with {@code tr()}
470 * and must contain a single parameter <code>{0}</code> for the file path
471 * @return {@code true} if and only if the file is successfully deleted; {@code false} otherwise
[9297]472 * @since 9296
[9296]473 */
474 public static boolean deleteFile(File file, String warnMsg) {
475 boolean result = file.delete();
476 if (!result) {
[12620]477 Logging.warn(tr(warnMsg, file.getPath()));
[9296]478 }
479 return result;
480 }
481
482 /**
[9645]483 * Creates a directory and log a default warning if the creation fails.
484 * @param dir directory to create
485 * @return {@code true} if and only if the directory is successfully created; {@code false} otherwise
486 * @since 9645
487 */
488 public static boolean mkDirs(File dir) {
489 return mkDirs(dir, marktr("Unable to create directory {0}"));
490 }
491
492 /**
493 * Creates a directory and log a configurable warning if the creation fails.
494 * @param dir directory to create
495 * @param warnMsg warning message. It will be translated with {@code tr()}
496 * and must contain a single parameter <code>{0}</code> for the directory path
497 * @return {@code true} if and only if the directory is successfully created; {@code false} otherwise
498 * @since 9645
499 */
500 public static boolean mkDirs(File dir, String warnMsg) {
501 boolean result = dir.mkdirs();
502 if (!result) {
[12620]503 Logging.warn(tr(warnMsg, dir.getPath()));
[9645]504 }
505 return result;
506 }
507
508 /**
[6823]509 * <p>Utility method for closing a {@link java.io.Closeable} object.</p>
[4668]510 *
[5874]511 * @param c the closeable object. May be null.
[4087]512 */
[5874]513 public static void close(Closeable c) {
514 if (c == null) return;
[4087]515 try {
[5874]516 c.close();
[6268]517 } catch (IOException e) {
[12620]518 Logging.warn(e);
[4087]519 }
520 }
[6070]521
[4087]522 /**
[6823]523 * <p>Utility method for closing a {@link java.util.zip.ZipFile}.</p>
[4668]524 *
[5874]525 * @param zip the zip file. May be null.
[4087]526 */
[5874]527 public static void close(ZipFile zip) {
[10721]528 close((Closeable) zip);
[4087]529 }
[6792]530
[6615]531 /**
532 * Converts the given file to its URL.
533 * @param f The file to get URL from
534 * @return The URL of the given file, or {@code null} if not possible.
535 * @since 6615
536 */
537 public static URL fileToURL(File f) {
538 if (f != null) {
539 try {
540 return f.toURI().toURL();
541 } catch (MalformedURLException ex) {
[12620]542 Logging.error("Unable to convert filename " + f.getAbsolutePath() + " to URL");
[6615]543 }
544 }
545 return null;
546 }
[4087]547
[6889]548 private static final double EPSILON = 1e-11;
[4272]549
[6268]550 /**
551 * Determines if the two given double values are equal (their delta being smaller than a fixed epsilon)
552 * @param a The first double value to compare
553 * @param b The second double value to compare
554 * @return {@code true} if {@code abs(a - b) <= 1e-11}, {@code false} otherwise
555 */
[4272]556 public static boolean equalsEpsilon(double a, double b) {
[6268]557 return Math.abs(a - b) <= EPSILON;
[4272]558 }
[4380]559
560 /**
[4403]561 * Calculate MD5 hash of a string and output in hexadecimal format.
[5589]562 * @param data arbitrary String
563 * @return MD5 hash of data, string of length 32 with characters in range [0-9a-f]
[4403]564 */
565 public static String md5Hex(String data) {
566 MessageDigest md = null;
567 try {
568 md = MessageDigest.getInstance("MD5");
569 } catch (NoSuchAlgorithmException e) {
[11374]570 throw new JosmRuntimeException(e);
[4403]571 }
[8429]572 byte[] byteData = data.getBytes(StandardCharsets.UTF_8);
[4403]573 byte[] byteDigest = md.digest(byteData);
574 return toHexString(byteDigest);
575 }
576
[8510]577 private static final char[] HEX_ARRAY = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
[6175]578
[4403]579 /**
[5589]580 * Converts a byte array to a string of hexadecimal characters.
581 * Preserves leading zeros, so the size of the output string is always twice
582 * the number of input bytes.
583 * @param bytes the byte array
584 * @return hexadecimal representation
[4403]585 */
586 public static String toHexString(byte[] bytes) {
[6175]587
588 if (bytes == null) {
589 return "";
[4403]590 }
[6175]591
592 final int len = bytes.length;
593 if (len == 0) {
594 return "";
595 }
596
597 char[] hexChars = new char[len * 2];
598 for (int i = 0, j = 0; i < len; i++) {
599 final int v = bytes[i];
600 hexChars[j++] = HEX_ARRAY[(v & 0xf0) >> 4];
601 hexChars[j++] = HEX_ARRAY[v & 0xf];
602 }
[4403]603 return new String(hexChars);
604 }
[4668]605
606 /**
607 * Topological sort.
[9246]608 * @param <T> type of items
[4668]609 *
[6830]610 * @param dependencies contains mappings (key -&gt; value). In the final list of sorted objects, the key will come
[4668]611 * after the value. (In other words, the key depends on the value(s).)
612 * There must not be cyclic dependencies.
613 * @return the list of sorted objects
614 */
[8510]615 public static <T> List<T> topologicalSort(final MultiMap<T, T> dependencies) {
616 MultiMap<T, T> deps = new MultiMap<>();
[4668]617 for (T key : dependencies.keySet()) {
618 deps.putVoid(key);
619 for (T val : dependencies.get(key)) {
620 deps.putVoid(val);
621 deps.put(key, val);
622 }
623 }
624
625 int size = deps.size();
[7005]626 List<T> sorted = new ArrayList<>();
[8510]627 for (int i = 0; i < size; ++i) {
[4668]628 T parentless = null;
629 for (T key : deps.keySet()) {
[6093]630 if (deps.get(key).isEmpty()) {
[4668]631 parentless = key;
632 break;
633 }
634 }
[11374]635 if (parentless == null) throw new JosmRuntimeException("parentless");
[4668]636 sorted.add(parentless);
637 deps.remove(parentless);
638 for (T key : deps.keySet()) {
639 deps.remove(key, parentless);
640 }
641 }
[11374]642 if (sorted.size() != size) throw new JosmRuntimeException("Wrong size");
[4668]643 return sorted;
644 }
[4816]645
646 /**
[8756]647 * Replaces some HTML reserved characters (&lt;, &gt; and &amp;) by their equivalent entity (&amp;lt;, &amp;gt; and &amp;amp;);
648 * @param s The unescaped string
649 * @return The escaped string
650 */
651 public static String escapeReservedCharactersHTML(String s) {
652 return s == null ? "" : s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;");
653 }
654
655 /**
[4816]656 * Transforms the collection {@code c} into an unmodifiable collection and
[10692]657 * applies the {@link Function} {@code f} on each element upon access.
[4816]658 * @param <A> class of input collection
659 * @param <B> class of transformed collection
660 * @param c a collection
661 * @param f a function that transforms objects of {@code A} to objects of {@code B}
662 * @return the transformed unmodifiable collection
663 */
[10692]664 public static <A, B> Collection<B> transform(final Collection<? extends A> c, final Function<A, B> f) {
[5578]665 return new AbstractCollection<B>() {
[4816]666
667 @Override
668 public int size() {
669 return c.size();
670 }
671
672 @Override
673 public Iterator<B> iterator() {
674 return new Iterator<B>() {
675
[12604]676 private final Iterator<? extends A> it = c.iterator();
[4816]677
678 @Override
679 public boolean hasNext() {
680 return it.hasNext();
681 }
682
683 @Override
684 public B next() {
685 return f.apply(it.next());
686 }
687
688 @Override
689 public void remove() {
690 throw new UnsupportedOperationException();
691 }
692 };
693 }
[5578]694 };
695 }
[4816]696
[5578]697 /**
698 * Transforms the list {@code l} into an unmodifiable list and
[10692]699 * applies the {@link Function} {@code f} on each element upon access.
[5578]700 * @param <A> class of input collection
701 * @param <B> class of transformed collection
702 * @param l a collection
703 * @param f a function that transforms objects of {@code A} to objects of {@code B}
704 * @return the transformed unmodifiable list
705 */
[10692]706 public static <A, B> List<B> transform(final List<? extends A> l, final Function<A, B> f) {
[5578]707 return new AbstractList<B>() {
[4816]708
709 @Override
[5578]710 public int size() {
711 return l.size();
[4816]712 }
713
714 @Override
[5578]715 public B get(int index) {
716 return f.apply(l.get(index));
[4816]717 }
718 };
719 }
[5577]720
721 /**
[11435]722 * Determines if the given String would be empty if stripped.
723 * This is an efficient alternative to {@code strip(s).isEmpty()} that avoids to create useless String object.
724 * @param str The string to test
725 * @return {@code true} if the stripped version of {@code s} would be empty.
726 * @since 11435
727 */
728 public static boolean isStripEmpty(String str) {
729 if (str != null) {
730 for (int i = 0; i < str.length(); i++) {
731 if (!isStrippedChar(str.charAt(i), DEFAULT_STRIP)) {
732 return false;
733 }
734 }
735 }
736 return true;
737 }
738
739 /**
[9419]740 * An alternative to {@link String#trim()} to effectively remove all leading
741 * and trailing white characters, including Unicode ones.
[5772]742 * @param str The string to strip
[6070]743 * @return <code>str</code>, without leading and trailing characters, according to
[5772]744 * {@link Character#isWhitespace(char)} and {@link Character#isSpaceChar(char)}.
[10873]745 * @see <a href="http://closingbraces.net/2008/11/11/javastringtrim/">Java String.trim has a strange idea of whitespace</a>
[8419]746 * @see <a href="https://bugs.openjdk.java.net/browse/JDK-4080617">JDK bug 4080617</a>
[8924]747 * @see <a href="https://bugs.openjdk.java.net/browse/JDK-7190385">JDK bug 7190385</a>
[5772]748 * @since 5772
749 */
[8435]750 public static String strip(final String str) {
[8567]751 if (str == null || str.isEmpty()) {
752 return str;
753 }
754 return strip(str, DEFAULT_STRIP);
[8435]755 }
756
757 /**
[9419]758 * An alternative to {@link String#trim()} to effectively remove all leading
759 * and trailing white characters, including Unicode ones.
[8435]760 * @param str The string to strip
761 * @param skipChars additional characters to skip
762 * @return <code>str</code>, without leading and trailing characters, according to
763 * {@link Character#isWhitespace(char)}, {@link Character#isSpaceChar(char)} and skipChars.
764 * @since 8435
765 */
766 public static String strip(final String str, final String skipChars) {
[5772]767 if (str == null || str.isEmpty()) {
768 return str;
769 }
[8567]770 return strip(str, stripChars(skipChars));
771 }
772
[12798]773 private static String strip(final String str, final char... skipChars) {
[8567]774
[8435]775 int start = 0;
776 int end = str.length();
777 boolean leadingSkipChar = true;
778 while (leadingSkipChar && start < end) {
[11435]779 leadingSkipChar = isStrippedChar(str.charAt(start), skipChars);
[8435]780 if (leadingSkipChar) {
[5772]781 start++;
782 }
783 }
[8435]784 boolean trailingSkipChar = true;
[8567]785 while (trailingSkipChar && end > start + 1) {
[11435]786 trailingSkipChar = isStrippedChar(str.charAt(end - 1), skipChars);
[8435]787 if (trailingSkipChar) {
[5772]788 end--;
789 }
790 }
[8567]791
[5772]792 return str.substring(start, end);
793 }
[6103]794
[12798]795 private static boolean isStrippedChar(char c, final char... skipChars) {
[11435]796 return Character.isWhitespace(c) || Character.isSpaceChar(c) || stripChar(skipChars, c);
797 }
798
[8567]799 private static char[] stripChars(final String skipChars) {
800 if (skipChars == null || skipChars.isEmpty()) {
801 return DEFAULT_STRIP;
802 }
803
804 char[] chars = new char[DEFAULT_STRIP.length + skipChars.length()];
805 System.arraycopy(DEFAULT_STRIP, 0, chars, 0, DEFAULT_STRIP.length);
806 skipChars.getChars(0, skipChars.length(), chars, DEFAULT_STRIP.length);
807
808 return chars;
809 }
810
811 private static boolean stripChar(final char[] strip, char c) {
812 for (char s : strip) {
813 if (c == s) {
814 return true;
815 }
816 }
817 return false;
818 }
819
[6103]820 /**
821 * Runs an external command and returns the standard output.
[6792]822 *
[6103]823 * The program is expected to execute fast.
[6792]824 *
[6103]825 * @param command the command with arguments
826 * @return the output
827 * @throws IOException when there was an error, e.g. command does not exist
[12830]828 * @throws ExecutionException when the return code is != 0. The output is can be retrieved in the exception message
829 * @throws InterruptedException if the current thread is {@linkplain Thread#interrupt() interrupted} by another thread while waiting
[6103]830 */
[12830]831 public static String execOutput(List<String> command) throws IOException, ExecutionException, InterruptedException {
[12620]832 if (Logging.isDebugEnabled()) {
833 Logging.debug(join(" ", command));
[6962]834 }
[6103]835 Process p = new ProcessBuilder(command).start();
[7082]836 try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
[7037]837 StringBuilder all = null;
838 String line;
839 while ((line = input.readLine()) != null) {
840 if (all == null) {
841 all = new StringBuilder(line);
842 } else {
[8390]843 all.append('\n');
[7037]844 all.append(line);
845 }
[6103]846 }
[12830]847 String msg = all != null ? all.toString() : null;
848 if (p.waitFor() != 0) {
849 throw new ExecutionException(msg, null);
850 }
851 return msg;
[6103]852 }
853 }
[6245]854
855 /**
856 * Returns the JOSM temp directory.
857 * @return The JOSM temp directory ({@code <java.io.tmpdir>/JOSM}), or {@code null} if {@code java.io.tmpdir} is not defined
858 * @since 6245
859 */
860 public static File getJosmTempDir() {
861 String tmpDir = System.getProperty("java.io.tmpdir");
862 if (tmpDir == null) {
863 return null;
864 }
865 File josmTmpDir = new File(tmpDir, "JOSM");
[6883]866 if (!josmTmpDir.exists() && !josmTmpDir.mkdirs()) {
[12620]867 Logging.warn("Unable to create temp directory " + josmTmpDir);
[6245]868 }
869 return josmTmpDir;
870 }
[6354]871
872 /**
873 * Returns a simple human readable (hours, minutes, seconds) string for a given duration in milliseconds.
874 * @param elapsedTime The duration in milliseconds
[6661]875 * @return A human readable string for the given duration
[6830]876 * @throws IllegalArgumentException if elapsedTime is &lt; 0
[6354]877 * @since 6354
878 */
[7867]879 public static String getDurationString(long elapsedTime) {
[6354]880 if (elapsedTime < 0) {
[7321]881 throw new IllegalArgumentException("elapsedTime must be >= 0");
[6354]882 }
883 // Is it less than 1 second ?
[6661]884 if (elapsedTime < MILLIS_OF_SECOND) {
[6354]885 return String.format("%d %s", elapsedTime, tr("ms"));
886 }
887 // Is it less than 1 minute ?
[6661]888 if (elapsedTime < MILLIS_OF_MINUTE) {
[8385]889 return String.format("%.1f %s", elapsedTime / (double) MILLIS_OF_SECOND, tr("s"));
[6354]890 }
891 // Is it less than 1 hour ?
[6661]892 if (elapsedTime < MILLIS_OF_HOUR) {
893 final long min = elapsedTime / MILLIS_OF_MINUTE;
894 return String.format("%d %s %d %s", min, tr("min"), (elapsedTime - min * MILLIS_OF_MINUTE) / MILLIS_OF_SECOND, tr("s"));
[6354]895 }
896 // Is it less than 1 day ?
[6661]897 if (elapsedTime < MILLIS_OF_DAY) {
898 final long hour = elapsedTime / MILLIS_OF_HOUR;
899 return String.format("%d %s %d %s", hour, tr("h"), (elapsedTime - hour * MILLIS_OF_HOUR) / MILLIS_OF_MINUTE, tr("min"));
[6354]900 }
[6661]901 long days = elapsedTime / MILLIS_OF_DAY;
902 return String.format("%d %s %d %s", days, trn("day", "days", days), (elapsedTime - days * MILLIS_OF_DAY) / MILLIS_OF_HOUR, tr("h"));
[6354]903 }
[6538]904
905 /**
[9274]906 * Returns a human readable representation (B, kB, MB, ...) for the given number of byes.
907 * @param bytes the number of bytes
908 * @param locale the locale used for formatting
909 * @return a human readable representation
910 * @since 9274
911 */
912 public static String getSizeString(long bytes, Locale locale) {
913 if (bytes < 0) {
914 throw new IllegalArgumentException("bytes must be >= 0");
915 }
916 int unitIndex = 0;
917 double value = bytes;
[9954]918 while (value >= 1024 && unitIndex < SIZE_UNITS.length) {
[9274]919 value /= 1024;
920 unitIndex++;
921 }
922 if (value > 100 || unitIndex == 0) {
[9954]923 return String.format(locale, "%.0f %s", value, SIZE_UNITS[unitIndex]);
[9274]924 } else if (value > 10) {
[9954]925 return String.format(locale, "%.1f %s", value, SIZE_UNITS[unitIndex]);
[9274]926 } else {
[9954]927 return String.format(locale, "%.2f %s", value, SIZE_UNITS[unitIndex]);
[9274]928 }
929 }
930
931 /**
[6652]932 * Returns a human readable representation of a list of positions.
[6830]933 * <p>
[6652]934 * For instance, {@code [1,5,2,6,7} yields "1-2,5-7
935 * @param positionList a list of positions
936 * @return a human readable representation
937 */
[8567]938 public static String getPositionListString(List<Integer> positionList) {
[6652]939 Collections.sort(positionList);
940 final StringBuilder sb = new StringBuilder(32);
941 sb.append(positionList.get(0));
942 int cnt = 0;
943 int last = positionList.get(0);
944 for (int i = 1; i < positionList.size(); ++i) {
945 int cur = positionList.get(i);
946 if (cur == last + 1) {
947 ++cnt;
948 } else if (cnt == 0) {
[8390]949 sb.append(',').append(cur);
[6652]950 } else {
[8390]951 sb.append('-').append(last);
952 sb.append(',').append(cur);
[6652]953 cnt = 0;
954 }
955 last = cur;
956 }
957 if (cnt >= 1) {
[8390]958 sb.append('-').append(last);
[6652]959 }
960 return sb.toString();
961 }
962
963 /**
[6538]964 * Returns a list of capture groups if {@link Matcher#matches()}, or {@code null}.
965 * The first element (index 0) is the complete match.
966 * Further elements correspond to the parts in parentheses of the regular expression.
967 * @param m the matcher
968 * @return a list of capture groups if {@link Matcher#matches()}, or {@code null}.
969 */
970 public static List<String> getMatches(final Matcher m) {
971 if (m.matches()) {
[7005]972 List<String> result = new ArrayList<>(m.groupCount() + 1);
[6538]973 for (int i = 0; i <= m.groupCount(); i++) {
974 result.add(m.group(i));
975 }
976 return result;
977 } else {
978 return null;
979 }
980 }
[6578]981
982 /**
983 * Cast an object savely.
984 * @param <T> the target type
985 * @param o the object to cast
986 * @param klass the target class (same as T)
987 * @return null if <code>o</code> is null or the type <code>o</code> is not
988 * a subclass of <code>klass</code>. The casted value otherwise.
989 */
[6623]990 @SuppressWarnings("unchecked")
[6578]991 public static <T> T cast(Object o, Class<T> klass) {
992 if (klass.isInstance(o)) {
[6623]993 return (T) o;
[6578]994 }
995 return null;
996 }
997
[6642]998 /**
999 * Returns the root cause of a throwable object.
1000 * @param t The object to get root cause for
1001 * @return the root cause of {@code t}
1002 * @since 6639
1003 */
1004 public static Throwable getRootCause(Throwable t) {
1005 Throwable result = t;
1006 if (result != null) {
1007 Throwable cause = result.getCause();
[7867]1008 while (cause != null && !cause.equals(result)) {
[6642]1009 result = cause;
1010 cause = result.getCause();
1011 }
1012 }
1013 return result;
1014 }
[6792]1015
[6717]1016 /**
1017 * Adds the given item at the end of a new copy of given array.
[9246]1018 * @param <T> type of items
[6717]1019 * @param array The source array
1020 * @param item The item to add
1021 * @return An extended copy of {@code array} containing {@code item} as additional last element
1022 * @since 6717
1023 */
1024 public static <T> T[] addInArrayCopy(T[] array, T item) {
1025 T[] biggerCopy = Arrays.copyOf(array, array.length + 1);
1026 biggerCopy[array.length] = item;
1027 return biggerCopy;
1028 }
[6742]1029
1030 /**
1031 * If the string {@code s} is longer than {@code maxLength}, the string is cut and "..." is appended.
[7867]1032 * @param s String to shorten
1033 * @param maxLength maximum number of characters to keep (not including the "...")
1034 * @return the shortened string
[6742]1035 */
1036 public static String shortenString(String s, int maxLength) {
1037 if (s != null && s.length() > maxLength) {
1038 return s.substring(0, maxLength - 3) + "...";
1039 } else {
1040 return s;
1041 }
1042 }
[7019]1043
[6972]1044 /**
[8756]1045 * If the string {@code s} is longer than {@code maxLines} lines, the string is cut and a "..." line is appended.
1046 * @param s String to shorten
1047 * @param maxLines maximum number of lines to keep (including including the "..." line)
1048 * @return the shortened string
1049 */
1050 public static String restrictStringLines(String s, int maxLines) {
1051 if (s == null) {
1052 return null;
1053 } else {
[9473]1054 return join("\n", limit(Arrays.asList(s.split("\\n")), maxLines, "..."));
1055 }
1056 }
1057
1058 /**
1059 * If the collection {@code elements} is larger than {@code maxElements} elements,
1060 * the collection is shortened and the {@code overflowIndicator} is appended.
[9477]1061 * @param <T> type of elements
[9473]1062 * @param elements collection to shorten
1063 * @param maxElements maximum number of elements to keep (including including the {@code overflowIndicator})
1064 * @param overflowIndicator the element used to indicate that the collection has been shortened
1065 * @return the shortened collection
1066 */
1067 public static <T> Collection<T> limit(Collection<T> elements, int maxElements, T overflowIndicator) {
1068 if (elements == null) {
1069 return null;
1070 } else {
1071 if (elements.size() > maxElements) {
1072 final Collection<T> r = new ArrayList<>(maxElements);
1073 final Iterator<T> it = elements.iterator();
1074 while (r.size() < maxElements - 1) {
1075 r.add(it.next());
1076 }
1077 r.add(overflowIndicator);
1078 return r;
[8756]1079 } else {
[9473]1080 return elements;
[8756]1081 }
1082 }
1083 }
1084
1085 /**
[7019]1086 * Fixes URL with illegal characters in the query (and fragment) part by
[6972]1087 * percent encoding those characters.
[7019]1088 *
[6972]1089 * special characters like &amp; and # are not encoded
[7019]1090 *
[6972]1091 * @param url the URL that should be fixed
1092 * @return the repaired URL
1093 */
1094 public static String fixURLQuery(String url) {
[9732]1095 if (url == null || url.indexOf('?') == -1)
[6972]1096 return url;
[7019]1097
[6972]1098 String query = url.substring(url.indexOf('?') + 1);
[7019]1099
[6972]1100 StringBuilder sb = new StringBuilder(url.substring(0, url.indexOf('?') + 1));
[7019]1101
[8510]1102 for (int i = 0; i < query.length(); i++) {
[8567]1103 String c = query.substring(i, i + 1);
[6972]1104 if (URL_CHARS.contains(c)) {
1105 sb.append(c);
1106 } else {
[8304]1107 sb.append(encodeUrl(c));
[6972]1108 }
1109 }
1110 return sb.toString();
1111 }
[7019]1112
[7356]1113 /**
[8304]1114 * Translates a string into <code>application/x-www-form-urlencoded</code>
1115 * format. This method uses UTF-8 encoding scheme to obtain the bytes for unsafe
1116 * characters.
1117 *
1118 * @param s <code>String</code> to be translated.
1119 * @return the translated <code>String</code>.
1120 * @see #decodeUrl(String)
1121 * @since 8304
1122 */
1123 public static String encodeUrl(String s) {
1124 final String enc = StandardCharsets.UTF_8.name();
1125 try {
1126 return URLEncoder.encode(s, enc);
1127 } catch (UnsupportedEncodingException e) {
[9196]1128 throw new IllegalStateException(e);
[8304]1129 }
1130 }
1131
1132 /**
1133 * Decodes a <code>application/x-www-form-urlencoded</code> string.
1134 * UTF-8 encoding is used to determine
1135 * what characters are represented by any consecutive sequences of the
1136 * form "<code>%<i>xy</i></code>".
1137 *
1138 * @param s the <code>String</code> to decode
1139 * @return the newly decoded <code>String</code>
1140 * @see #encodeUrl(String)
1141 * @since 8304
1142 */
1143 public static String decodeUrl(String s) {
1144 final String enc = StandardCharsets.UTF_8.name();
1145 try {
1146 return URLDecoder.decode(s, enc);
1147 } catch (UnsupportedEncodingException e) {
[9196]1148 throw new IllegalStateException(e);
[8304]1149 }
1150 }
1151
1152 /**
[7356]1153 * Determines if the given URL denotes a file on a local filesystem.
1154 * @param url The URL to test
1155 * @return {@code true} if the url points to a local file
1156 * @since 7356
1157 */
1158 public static boolean isLocalUrl(String url) {
[11893]1159 return url != null && !url.startsWith("http://") && !url.startsWith("https://") && !url.startsWith("resource://");
[7356]1160 }
[7423]1161
1162 /**
[10294]1163 * Determines if the given URL is valid.
1164 * @param url The URL to test
1165 * @return {@code true} if the url is valid
1166 * @since 10294
1167 */
1168 public static boolean isValidUrl(String url) {
[10761]1169 if (url != null) {
1170 try {
1171 new URL(url);
1172 return true;
1173 } catch (MalformedURLException e) {
[12620]1174 Logging.trace(e);
[10761]1175 }
[10294]1176 }
[10761]1177 return false;
[10294]1178 }
1179
1180 /**
[8734]1181 * Creates a new {@link ThreadFactory} which creates threads with names according to {@code nameFormat}.
1182 * @param nameFormat a {@link String#format(String, Object...)} compatible name format; its first argument is a unique thread index
1183 * @param threadPriority the priority of the created threads, see {@link Thread#setPriority(int)}
1184 * @return a new {@link ThreadFactory}
1185 */
1186 public static ThreadFactory newThreadFactory(final String nameFormat, final int threadPriority) {
1187 return new ThreadFactory() {
1188 final AtomicLong count = new AtomicLong(0);
1189 @Override
1190 public Thread newThread(final Runnable runnable) {
1191 final Thread thread = new Thread(runnable, String.format(Locale.ENGLISH, nameFormat, count.getAndIncrement()));
1192 thread.setPriority(threadPriority);
1193 return thread;
1194 }
1195 };
1196 }
1197
1198 /**
[9351]1199 * Returns a {@link ForkJoinPool} with the parallelism given by the preference key.
1200 * @param pref The preference key to determine parallelism
[8734]1201 * @param nameFormat see {@link #newThreadFactory(String, int)}
1202 * @param threadPriority see {@link #newThreadFactory(String, int)}
[9351]1203 * @return a {@link ForkJoinPool}
[7423]1204 */
[9351]1205 public static ForkJoinPool newForkJoinPool(String pref, final String nameFormat, final int threadPriority) {
[12846]1206 int noThreads = Config.getPref().getInt(pref, Runtime.getRuntime().availableProcessors());
[9351]1207 return new ForkJoinPool(noThreads, new ForkJoinPool.ForkJoinWorkerThreadFactory() {
1208 final AtomicLong count = new AtomicLong(0);
1209 @Override
1210 public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
1211 final ForkJoinWorkerThread thread = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
1212 thread.setName(String.format(Locale.ENGLISH, nameFormat, count.getAndIncrement()));
1213 thread.setPriority(threadPriority);
1214 return thread;
1215 }
1216 }, null, true);
[7423]1217 }
[7894]1218
1219 /**
[9352]1220 * Returns an executor which executes commands in the calling thread
1221 * @return an executor
1222 */
1223 public static Executor newDirectExecutor() {
[10717]1224 return Runnable::run;
[9352]1225 }
1226
1227 /**
[7894]1228 * Updates a given system property.
1229 * @param key The property key
1230 * @param value The property value
1231 * @return the previous value of the system property, or {@code null} if it did not have one.
1232 * @since 7894
1233 */
1234 public static String updateSystemProperty(String key, String value) {
1235 if (value != null) {
1236 String old = System.setProperty(key, value);
[12620]1237 if (Logging.isDebugEnabled() && !value.equals(old)) {
[10931]1238 if (!key.toLowerCase(Locale.ENGLISH).contains("password")) {
[12620]1239 Logging.debug("System property '" + key + "' set to '" + value + "'. Old value was '" + old + '\'');
[10931]1240 } else {
[12620]1241 Logging.debug("System property '" + key + "' changed.");
[10931]1242 }
[7894]1243 }
1244 return old;
1245 }
1246 return null;
1247 }
[8287]1248
1249 /**
[10404]1250 * Returns a new secure DOM builder, supporting XML namespaces.
1251 * @return a new secure DOM builder, supporting XML namespaces
1252 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1253 * @since 10404
1254 */
1255 public static DocumentBuilder newSafeDOMBuilder() throws ParserConfigurationException {
1256 DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
1257 builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
1258 builderFactory.setNamespaceAware(true);
1259 builderFactory.setValidating(false);
1260 return builderFactory.newDocumentBuilder();
1261 }
1262
1263 /**
1264 * Parse the content given {@link InputStream} as XML.
1265 * This method uses a secure DOM builder, supporting XML namespaces.
1266 *
1267 * @param is The InputStream containing the content to be parsed.
1268 * @return the result DOM document
1269 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1270 * @throws IOException if any IO errors occur.
1271 * @throws SAXException for SAX errors.
1272 * @since 10404
1273 */
1274 public static Document parseSafeDOM(InputStream is) throws ParserConfigurationException, IOException, SAXException {
1275 long start = System.currentTimeMillis();
[12620]1276 Logging.debug("Starting DOM parsing of {0}", is);
[10404]1277 Document result = newSafeDOMBuilder().parse(is);
[12620]1278 if (Logging.isDebugEnabled()) {
1279 Logging.debug("DOM parsing done in {0}", getDurationString(System.currentTimeMillis() - start));
[10404]1280 }
1281 return result;
1282 }
1283
1284 /**
[8287]1285 * Returns a new secure SAX parser, supporting XML namespaces.
1286 * @return a new secure SAX parser, supporting XML namespaces
1287 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1288 * @throws SAXException for SAX errors.
1289 * @since 8287
1290 */
1291 public static SAXParser newSafeSAXParser() throws ParserConfigurationException, SAXException {
1292 SAXParserFactory parserFactory = SAXParserFactory.newInstance();
1293 parserFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
1294 parserFactory.setNamespaceAware(true);
1295 return parserFactory.newSAXParser();
1296 }
[8347]1297
1298 /**
1299 * Parse the content given {@link org.xml.sax.InputSource} as XML using the specified {@link org.xml.sax.helpers.DefaultHandler}.
1300 * This method uses a secure SAX parser, supporting XML namespaces.
1301 *
1302 * @param is The InputSource containing the content to be parsed.
1303 * @param dh The SAX DefaultHandler to use.
1304 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1305 * @throws SAXException for SAX errors.
1306 * @throws IOException if any IO errors occur.
1307 * @since 8347
1308 */
1309 public static void parseSafeSAX(InputSource is, DefaultHandler dh) throws ParserConfigurationException, SAXException, IOException {
1310 long start = System.currentTimeMillis();
[12620]1311 Logging.debug("Starting SAX parsing of {0} using {1}", is, dh);
[8347]1312 newSafeSAXParser().parse(is, dh);
[12620]1313 if (Logging.isDebugEnabled()) {
1314 Logging.debug("SAX parsing done in {0}", getDurationString(System.currentTimeMillis() - start));
[8347]1315 }
1316 }
[8404]1317
1318 /**
1319 * Determines if the filename has one of the given extensions, in a robust manner.
1320 * The comparison is case and locale insensitive.
1321 * @param filename The file name
1322 * @param extensions The list of extensions to look for (without dot)
1323 * @return {@code true} if the filename has one of the given extensions
1324 * @since 8404
1325 */
[8567]1326 public static boolean hasExtension(String filename, String... extensions) {
[8933]1327 String name = filename.toLowerCase(Locale.ENGLISH).replace("?format=raw", "");
[8513]1328 for (String ext : extensions) {
[8846]1329 if (name.endsWith('.' + ext.toLowerCase(Locale.ENGLISH)))
[8404]1330 return true;
[8513]1331 }
[8404]1332 return false;
1333 }
1334
1335 /**
1336 * Determines if the file's name has one of the given extensions, in a robust manner.
1337 * The comparison is case and locale insensitive.
1338 * @param file The file
1339 * @param extensions The list of extensions to look for (without dot)
1340 * @return {@code true} if the file's name has one of the given extensions
1341 * @since 8404
1342 */
[8567]1343 public static boolean hasExtension(File file, String... extensions) {
[8404]1344 return hasExtension(file.getName(), extensions);
1345 }
[8568]1346
1347 /**
1348 * Reads the input stream and closes the stream at the end of processing (regardless if an exception was thrown)
1349 *
[8570]1350 * @param stream input stream
[11330]1351 * @return byte array of data in input stream (empty if stream is null)
[8570]1352 * @throws IOException if any I/O error occurs
[8568]1353 */
1354 public static byte[] readBytesFromStream(InputStream stream) throws IOException {
[11320]1355 if (stream == null) {
[11330]1356 return new byte[0];
[11320]1357 }
[8568]1358 try {
1359 ByteArrayOutputStream bout = new ByteArrayOutputStream(stream.available());
1360 byte[] buffer = new byte[2048];
1361 boolean finished = false;
1362 do {
1363 int read = stream.read(buffer);
1364 if (read >= 0) {
1365 bout.write(buffer, 0, read);
1366 } else {
1367 finished = true;
1368 }
1369 } while (!finished);
1370 if (bout.size() == 0)
[11330]1371 return new byte[0];
[8568]1372 return bout.toByteArray();
1373 } finally {
[11330]1374 stream.close();
[8568]1375 }
1376 }
[8574]1377
1378 /**
1379 * Returns the initial capacity to pass to the HashMap / HashSet constructor
1380 * when it is initialized with a known number of entries.
[8602]1381 *
[8574]1382 * When a HashMap is filled with entries, the underlying array is copied over
1383 * to a larger one multiple times. To avoid this process when the number of
1384 * entries is known in advance, the initial capacity of the array can be
1385 * given to the HashMap constructor. This method returns a suitable value
1386 * that avoids rehashing but doesn't waste memory.
1387 * @param nEntries the number of entries expected
1388 * @param loadFactor the load factor
1389 * @return the initial capacity for the HashMap constructor
1390 */
[9987]1391 public static int hashMapInitialCapacity(int nEntries, double loadFactor) {
[8574]1392 return (int) Math.ceil(nEntries / loadFactor);
1393 }
1394
1395 /**
1396 * Returns the initial capacity to pass to the HashMap / HashSet constructor
1397 * when it is initialized with a known number of entries.
[8602]1398 *
[8574]1399 * When a HashMap is filled with entries, the underlying array is copied over
1400 * to a larger one multiple times. To avoid this process when the number of
1401 * entries is known in advance, the initial capacity of the array can be
1402 * given to the HashMap constructor. This method returns a suitable value
1403 * that avoids rehashing but doesn't waste memory.
[8602]1404 *
[8574]1405 * Assumes default load factor (0.75).
1406 * @param nEntries the number of entries expected
1407 * @return the initial capacity for the HashMap constructor
1408 */
1409 public static int hashMapInitialCapacity(int nEntries) {
[9987]1410 return hashMapInitialCapacity(nEntries, 0.75d);
[8574]1411 }
[8994]1412
1413 /**
1414 * Utility class to save a string along with its rendering direction
1415 * (left-to-right or right-to-left).
1416 */
1417 private static class DirectionString {
[8997]1418 public final int direction;
1419 public final String str;
[8994]1420
[8997]1421 DirectionString(int direction, String str) {
[8994]1422 this.direction = direction;
1423 this.str = str;
1424 }
1425 }
1426
1427 /**
1428 * Convert a string to a list of {@link GlyphVector}s. The string may contain
1429 * bi-directional text. The result will be in correct visual order.
1430 * Each element of the resulting list corresponds to one section of the
1431 * string with consistent writing direction (left-to-right or right-to-left).
1432 *
1433 * @param string the string to render
1434 * @param font the font
1435 * @param frc a FontRenderContext object
1436 * @return a list of GlyphVectors
1437 */
1438 public static List<GlyphVector> getGlyphVectorsBidi(String string, Font font, FontRenderContext frc) {
1439 List<GlyphVector> gvs = new ArrayList<>();
1440 Bidi bidi = new Bidi(string, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
1441 byte[] levels = new byte[bidi.getRunCount()];
1442 DirectionString[] dirStrings = new DirectionString[levels.length];
1443 for (int i = 0; i < levels.length; ++i) {
1444 levels[i] = (byte) bidi.getRunLevel(i);
1445 String substr = string.substring(bidi.getRunStart(i), bidi.getRunLimit(i));
1446 int dir = levels[i] % 2 == 0 ? Bidi.DIRECTION_LEFT_TO_RIGHT : Bidi.DIRECTION_RIGHT_TO_LEFT;
1447 dirStrings[i] = new DirectionString(dir, substr);
1448 }
1449 Bidi.reorderVisually(levels, 0, dirStrings, 0, levels.length);
1450 for (int i = 0; i < dirStrings.length; ++i) {
1451 char[] chars = dirStrings[i].str.toCharArray();
1452 gvs.add(font.layoutGlyphVector(frc, chars, 0, chars.length, dirStrings[i].direction));
1453 }
1454 return gvs;
1455 }
1456
[10223]1457 /**
1458 * Sets {@code AccessibleObject}(s) accessible.
1459 * @param objects objects
1460 * @see AccessibleObject#setAccessible
1461 * @since 10223
1462 */
[12798]1463 public static void setObjectsAccessible(final AccessibleObject... objects) {
[10223]1464 if (objects != null && objects.length > 0) {
[10616]1465 AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
1466 for (AccessibleObject o : objects) {
1467 o.setAccessible(true);
[10223]1468 }
[10616]1469 return null;
[10223]1470 });
1471 }
1472 }
[10805]1473
1474 /**
1475 * Clamp a value to the given range
1476 * @param val The value
1477 * @param min minimum value
1478 * @param max maximum value
1479 * @return the value
[11740]1480 * @throws IllegalArgumentException if {@code min > max}
[10805]1481 * @since 10805
1482 */
1483 public static double clamp(double val, double min, double max) {
[11721]1484 if (min > max) {
[11732]1485 throw new IllegalArgumentException(MessageFormat.format("Parameter min ({0}) cannot be greater than max ({1})", min, max));
[11721]1486 } else if (val < min) {
[10805]1487 return min;
1488 } else if (val > max) {
1489 return max;
1490 } else {
1491 return val;
1492 }
1493 }
[11055]1494
1495 /**
1496 * Clamp a integer value to the given range
1497 * @param val The value
1498 * @param min minimum value
1499 * @param max maximum value
1500 * @return the value
[11740]1501 * @throws IllegalArgumentException if {@code min > max}
[11056]1502 * @since 11055
[11055]1503 */
1504 public static int clamp(int val, int min, int max) {
[11721]1505 if (min > max) {
[11732]1506 throw new IllegalArgumentException(MessageFormat.format("Parameter min ({0}) cannot be greater than max ({1})", min, max));
[11721]1507 } else if (val < min) {
[11055]1508 return min;
1509 } else if (val > max) {
1510 return max;
1511 } else {
1512 return val;
1513 }
1514 }
[12013]1515
1516 /**
1517 * Convert angle from radians to degrees.
1518 *
1519 * Replacement for {@link Math#toDegrees(double)} to match the Java 9
1520 * version of that method. (Can be removed when JOSM support for Java 8 ends.)
1521 * Only relevant in relation to ProjectionRegressionTest.
1522 * @param angleRad an angle in radians
1523 * @return the same angle in degrees
[12015]1524 * @see <a href="https://josm.openstreetmap.de/ticket/11889">#11889</a>
1525 * @since 12013
[12013]1526 */
1527 public static double toDegrees(double angleRad) {
1528 return angleRad * TO_DEGREES;
1529 }
1530
1531 /**
1532 * Convert angle from degrees to radians.
1533 *
1534 * Replacement for {@link Math#toRadians(double)} to match the Java 9
1535 * version of that method. (Can be removed when JOSM support for Java 8 ends.)
1536 * Only relevant in relation to ProjectionRegressionTest.
1537 * @param angleDeg an angle in degrees
1538 * @return the same angle in radians
[12015]1539 * @see <a href="https://josm.openstreetmap.de/ticket/11889">#11889</a>
1540 * @since 12013
[12013]1541 */
1542 public static double toRadians(double angleDeg) {
1543 return angleDeg * TO_RADIANS;
1544 }
[12130]1545
1546 /**
1547 * Returns the Java version as an int value.
1548 * @return the Java version as an int value (8, 9, etc.)
1549 * @since 12130
1550 */
1551 public static int getJavaVersion() {
1552 String version = System.getProperty("java.version");
1553 if (version.startsWith("1.")) {
1554 version = version.substring(2);
1555 }
1556 // Allow these formats:
1557 // 1.8.0_72-ea
1558 // 9-ea
1559 // 9
1560 // 9.0.1
1561 int dotPos = version.indexOf('.');
1562 int dashPos = version.indexOf('-');
1563 return Integer.parseInt(version.substring(0,
1564 dotPos > -1 ? dotPos : dashPos > -1 ? dashPos : 1));
1565 }
[12217]1566
1567 /**
1568 * Returns the Java update as an int value.
1569 * @return the Java update as an int value (121, 131, etc.)
1570 * @since 12217
1571 */
1572 public static int getJavaUpdate() {
1573 String version = System.getProperty("java.version");
1574 if (version.startsWith("1.")) {
1575 version = version.substring(2);
1576 }
1577 // Allow these formats:
1578 // 1.8.0_72-ea
1579 // 9-ea
1580 // 9
1581 // 9.0.1
1582 int undePos = version.indexOf('_');
1583 int dashPos = version.indexOf('-');
1584 if (undePos > -1) {
1585 return Integer.parseInt(version.substring(undePos + 1,
1586 dashPos > -1 ? dashPos : version.length()));
1587 }
1588 int firstDotPos = version.indexOf('.');
1589 int lastDotPos = version.lastIndexOf('.');
[12703]1590 if (firstDotPos == lastDotPos) {
1591 return 0;
1592 }
[12798]1593 return firstDotPos > -1 ? Integer.parseInt(version.substring(firstDotPos + 1,
[12217]1594 lastDotPos > -1 ? lastDotPos : version.length())) : 0;
1595 }
1596
1597 /**
1598 * Returns the Java build number as an int value.
1599 * @return the Java build number as an int value (0, 1, etc.)
1600 * @since 12217
1601 */
1602 public static int getJavaBuild() {
1603 String version = System.getProperty("java.runtime.version");
1604 int bPos = version.indexOf('b');
1605 int pPos = version.indexOf('+');
[12703]1606 try {
1607 return Integer.parseInt(version.substring(bPos > -1 ? bPos + 1 : pPos + 1, version.length()));
1608 } catch (NumberFormatException e) {
1609 Logging.trace(e);
1610 return 0;
1611 }
[12217]1612 }
[12219]1613
1614 /**
1615 * Returns the JRE expiration date.
1616 * @return the JRE expiration date, or null
1617 * @since 12219
1618 */
1619 public static Date getJavaExpirationDate() {
1620 try {
[12238]1621 Object value = null;
1622 Class<?> c = Class.forName("com.sun.deploy.config.BuiltInProperties");
1623 try {
1624 value = c.getDeclaredField("JRE_EXPIRATION_DATE").get(null);
1625 } catch (NoSuchFieldException e) {
1626 // Field is gone with Java 9, there's a method instead
[12620]1627 Logging.trace(e);
[12238]1628 value = c.getDeclaredMethod("getProperty", String.class).invoke(null, "JRE_EXPIRATION_DATE");
1629 }
[12219]1630 if (value instanceof String) {
1631 return DateFormat.getDateInstance(3, Locale.US).parse((String) value);
1632 }
1633 } catch (IllegalArgumentException | ReflectiveOperationException | SecurityException | ParseException e) {
[12620]1634 Logging.debug(e);
[12219]1635 }
1636 return null;
1637 }
1638
1639 /**
1640 * Returns the latest version of Java, from Oracle website.
1641 * @return the latest version of Java, from Oracle website
1642 * @since 12219
1643 */
1644 public static String getJavaLatestVersion() {
1645 try {
[12854]1646 return HttpClient.create(
1647 new URL(Config.getPref().get(
1648 "java.baseline.version.url",
1649 "http://javadl-esd-secure.oracle.com/update/baseline.version")))
[12219]1650 .connect().fetchContent().split("\n")[0];
1651 } catch (IOException e) {
[12620]1652 Logging.error(e);
[12219]1653 }
1654 return null;
1655 }
[12594]1656
1657 /**
1658 * Get a function that converts an object to a singleton stream of a certain
1659 * class (or null if the object cannot be cast to that class).
1660 *
1661 * Can be useful in relation with streams, but be aware of the performance
1662 * implications of creating a stream for each element.
1663 * @param <T> type of the objects to convert
1664 * @param <U> type of the elements in the resulting stream
1665 * @param klass the class U
1666 * @return function converting an object to a singleton stream or null
[12604]1667 * @since 12594
[12594]1668 */
1669 public static <T, U> Function<T, Stream<U>> castToStream(Class<U> klass) {
1670 return x -> klass.isInstance(x) ? Stream.of(klass.cast(x)) : null;
1671 }
[12604]1672
1673 /**
1674 * Helper method to replace the "<code>instanceof</code>-check and cast" pattern.
1675 * Checks if an object is instance of class T and performs an action if that
1676 * is the case.
1677 * Syntactic sugar to avoid typing the class name two times, when one time
1678 * would suffice.
1679 * @param <T> the type for the instanceof check and cast
1680 * @param o the object to check and cast
1681 * @param klass the class T
1682 * @param consumer action to take when o is and instance of T
1683 * @since 12604
1684 */
[12618]1685 @SuppressWarnings("unchecked")
[12604]1686 public static <T> void instanceOfThen(Object o, Class<T> klass, Consumer<? super T> consumer) {
1687 if (klass.isInstance(o)) {
1688 consumer.accept((T) o);
1689 }
1690 }
[12987]1691
1692 /**
1693 * Helper method to replace the "<code>instanceof</code>-check and cast" pattern.
1694 *
1695 * @param <T> the type for the instanceof check and cast
1696 * @param o the object to check and cast
1697 * @param klass the class T
1698 * @return {@link Optional} containing the result of the cast, if it is possible, an empty
1699 * Optional otherwise
1700 */
1701 @SuppressWarnings("unchecked")
1702 public static <T> Optional<T> instanceOfAndCast(Object o, Class<T> klass) {
1703 if (klass.isInstance(o))
1704 return Optional.of((T) o);
1705 return Optional.empty();
1706 }
1707
[4069]1708}
Note: See TracBrowser for help on using the repository browser.