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