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