[3504] | 1 | // License: GPL. For details, see LICENSE file.
|
---|
| 2 | package org.openstreetmap.josm.tools;
|
---|
| 3 |
|
---|
[6354] | 4 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
| 5 | import static org.openstreetmap.josm.tools.I18n.trn;
|
---|
| 6 |
|
---|
[3859] | 7 | import java.awt.Color;
|
---|
[4380] | 8 | import java.awt.Toolkit;
|
---|
| 9 | import java.awt.datatransfer.Clipboard;
|
---|
| 10 | import java.awt.datatransfer.ClipboardOwner;
|
---|
| 11 | import java.awt.datatransfer.DataFlavor;
|
---|
| 12 | import java.awt.datatransfer.StringSelection;
|
---|
| 13 | import java.awt.datatransfer.Transferable;
|
---|
| 14 | import java.awt.datatransfer.UnsupportedFlavorException;
|
---|
[5868] | 15 | import java.io.BufferedReader;
|
---|
[8568] | 16 | import java.io.ByteArrayOutputStream;
|
---|
[5874] | 17 | import java.io.Closeable;
|
---|
[4065] | 18 | import java.io.File;
|
---|
| 19 | import java.io.IOException;
|
---|
| 20 | import java.io.InputStream;
|
---|
[5868] | 21 | import java.io.InputStreamReader;
|
---|
[4065] | 22 | import java.io.OutputStream;
|
---|
[6972] | 23 | import java.io.UnsupportedEncodingException;
|
---|
[5587] | 24 | import java.net.HttpURLConnection;
|
---|
[6615] | 25 | import java.net.MalformedURLException;
|
---|
[5587] | 26 | import java.net.URL;
|
---|
[5868] | 27 | import java.net.URLConnection;
|
---|
[8304] | 28 | import java.net.URLDecoder;
|
---|
[6972] | 29 | import java.net.URLEncoder;
|
---|
[7082] | 30 | import java.nio.charset.StandardCharsets;
|
---|
[7003] | 31 | import java.nio.file.Files;
|
---|
| 32 | import java.nio.file.Path;
|
---|
| 33 | import java.nio.file.StandardCopyOption;
|
---|
[4403] | 34 | import java.security.MessageDigest;
|
---|
| 35 | import java.security.NoSuchAlgorithmException;
|
---|
[4069] | 36 | import java.text.MessageFormat;
|
---|
[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;
|
---|
[4816] | 43 | import java.util.Iterator;
|
---|
[4668] | 44 | import java.util.List;
|
---|
[8404] | 45 | import java.util.Locale;
|
---|
[7423] | 46 | import java.util.concurrent.ExecutorService;
|
---|
| 47 | import java.util.concurrent.Executors;
|
---|
[6538] | 48 | import java.util.regex.Matcher;
|
---|
[6823] | 49 | import java.util.regex.Pattern;
|
---|
[6421] | 50 | import java.util.zip.GZIPInputStream;
|
---|
[7119] | 51 | import java.util.zip.ZipEntry;
|
---|
[5874] | 52 | import java.util.zip.ZipFile;
|
---|
[7119] | 53 | import java.util.zip.ZipInputStream;
|
---|
[3848] | 54 |
|
---|
[8287] | 55 | import javax.xml.XMLConstants;
|
---|
| 56 | import javax.xml.parsers.ParserConfigurationException;
|
---|
| 57 | import javax.xml.parsers.SAXParser;
|
---|
| 58 | import javax.xml.parsers.SAXParserFactory;
|
---|
| 59 |
|
---|
[7867] | 60 | import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
|
---|
[5868] | 61 | import org.openstreetmap.josm.Main;
|
---|
[5587] | 62 | import org.openstreetmap.josm.data.Version;
|
---|
[8347] | 63 | import org.xml.sax.InputSource;
|
---|
[8287] | 64 | import org.xml.sax.SAXException;
|
---|
[8347] | 65 | import org.xml.sax.helpers.DefaultHandler;
|
---|
[5587] | 66 |
|
---|
[4069] | 67 | /**
|
---|
| 68 | * Basic utils, that can be useful in different parts of the program.
|
---|
| 69 | */
|
---|
[6362] | 70 | public final class Utils {
|
---|
[3504] | 71 |
|
---|
[6823] | 72 | public static final Pattern WHITE_SPACES_PATTERN = Pattern.compile("\\s+");
|
---|
| 73 |
|
---|
[6360] | 74 | private Utils() {
|
---|
| 75 | // Hide default constructor for utils classes
|
---|
| 76 | }
|
---|
| 77 |
|
---|
[6806] | 78 | private static final int MILLIS_OF_SECOND = 1000;
|
---|
| 79 | private static final int MILLIS_OF_MINUTE = 60000;
|
---|
| 80 | private static final int MILLIS_OF_HOUR = 3600000;
|
---|
| 81 | private static final int MILLIS_OF_DAY = 86400000;
|
---|
| 82 |
|
---|
[6999] | 83 | public static final String URL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=%";
|
---|
| 84 |
|
---|
[8567] | 85 | private static char[] DEFAULT_STRIP = {'\u200B', '\uFEFF'};
|
---|
| 86 |
|
---|
[6772] | 87 | /**
|
---|
| 88 | * Tests whether {@code predicate} applies to at least one elements from {@code collection}.
|
---|
| 89 | */
|
---|
[3836] | 90 | public static <T> boolean exists(Iterable<? extends T> collection, Predicate<? super T> predicate) {
|
---|
| 91 | for (T item : collection) {
|
---|
| 92 | if (predicate.evaluate(item))
|
---|
[3504] | 93 | return true;
|
---|
| 94 | }
|
---|
| 95 | return false;
|
---|
| 96 | }
|
---|
[3674] | 97 |
|
---|
[6772] | 98 | /**
|
---|
| 99 | * Tests whether {@code predicate} applies to all elements from {@code collection}.
|
---|
| 100 | */
|
---|
| 101 | public static <T> boolean forAll(Iterable<? extends T> collection, Predicate<? super T> predicate) {
|
---|
| 102 | return !exists(collection, Predicates.not(predicate));
|
---|
| 103 | }
|
---|
| 104 |
|
---|
[4065] | 105 | public static <T> boolean exists(Iterable<T> collection, Class<? extends T> klass) {
|
---|
[3836] | 106 | for (Object item : collection) {
|
---|
| 107 | if (klass.isInstance(item))
|
---|
| 108 | return true;
|
---|
| 109 | }
|
---|
| 110 | return false;
|
---|
| 111 | }
|
---|
| 112 |
|
---|
| 113 | public static <T> T find(Iterable<? extends T> collection, Predicate<? super T> predicate) {
|
---|
| 114 | for (T item : collection) {
|
---|
| 115 | if (predicate.evaluate(item))
|
---|
| 116 | return item;
|
---|
| 117 | }
|
---|
| 118 | return null;
|
---|
| 119 | }
|
---|
| 120 |
|
---|
[4065] | 121 | @SuppressWarnings("unchecked")
|
---|
| 122 | public static <T> T find(Iterable<? super T> collection, Class<? extends T> klass) {
|
---|
[3836] | 123 | for (Object item : collection) {
|
---|
[4065] | 124 | if (klass.isInstance(item))
|
---|
| 125 | return (T) item;
|
---|
[3836] | 126 | }
|
---|
| 127 | return null;
|
---|
| 128 | }
|
---|
[4408] | 129 |
|
---|
[5159] | 130 | public static <T> Collection<T> filter(Collection<? extends T> collection, Predicate<? super T> predicate) {
|
---|
[7005] | 131 | return new FilteredCollection<>(collection, predicate);
|
---|
[5159] | 132 | }
|
---|
[4668] | 133 |
|
---|
[6610] | 134 | /**
|
---|
| 135 | * Returns the first element from {@code items} which is non-null, or null if all elements are null.
|
---|
[7019] | 136 | * @param items the items to look for
|
---|
| 137 | * @return first non-null item if there is one
|
---|
[6610] | 138 | */
|
---|
[7019] | 139 | @SafeVarargs
|
---|
[5159] | 140 | public static <T> T firstNonNull(T... items) {
|
---|
| 141 | for (T i : items) {
|
---|
| 142 | if (i != null) {
|
---|
| 143 | return i;
|
---|
| 144 | }
|
---|
| 145 | }
|
---|
| 146 | return null;
|
---|
| 147 | }
|
---|
| 148 |
|
---|
[4100] | 149 | /**
|
---|
| 150 | * Filter a collection by (sub)class.
|
---|
| 151 | * This is an efficient read-only implementation.
|
---|
| 152 | */
|
---|
| 153 | public static <S, T extends S> SubclassFilteredCollection<S, T> filteredCollection(Collection<S> collection, final Class<T> klass) {
|
---|
[7005] | 154 | return new SubclassFilteredCollection<>(collection, new Predicate<S>() {
|
---|
[4100] | 155 | @Override
|
---|
| 156 | public boolean evaluate(S o) {
|
---|
| 157 | return klass.isInstance(o);
|
---|
| 158 | }
|
---|
| 159 | });
|
---|
| 160 | }
|
---|
[3836] | 161 |
|
---|
[3869] | 162 | public static <T> int indexOf(Iterable<? extends T> collection, Predicate<? super T> predicate) {
|
---|
| 163 | int i = 0;
|
---|
| 164 | for (T item : collection) {
|
---|
| 165 | if (predicate.evaluate(item))
|
---|
| 166 | return i;
|
---|
| 167 | i++;
|
---|
| 168 | }
|
---|
| 169 | return -1;
|
---|
| 170 | }
|
---|
| 171 |
|
---|
[3674] | 172 | /**
|
---|
[7867] | 173 | * Returns the minimum of three values.
|
---|
| 174 | * @param a an argument.
|
---|
| 175 | * @param b another argument.
|
---|
| 176 | * @param c another argument.
|
---|
| 177 | * @return the smaller of {@code a}, {@code b} and {@code c}.
|
---|
[3674] | 178 | */
|
---|
| 179 | public static int min(int a, int b, int c) {
|
---|
| 180 | if (b < c) {
|
---|
| 181 | if (a < b)
|
---|
| 182 | return a;
|
---|
| 183 | return b;
|
---|
| 184 | } else {
|
---|
[4065] | 185 | if (a < c)
|
---|
[3674] | 186 | return a;
|
---|
| 187 | return c;
|
---|
| 188 | }
|
---|
| 189 | }
|
---|
[3711] | 190 |
|
---|
[7867] | 191 | /**
|
---|
| 192 | * Returns the greater of four {@code int} values. That is, the
|
---|
| 193 | * result is the argument closer to the value of
|
---|
| 194 | * {@link Integer#MAX_VALUE}. If the arguments have the same value,
|
---|
| 195 | * the result is that same value.
|
---|
| 196 | *
|
---|
| 197 | * @param a an argument.
|
---|
| 198 | * @param b another argument.
|
---|
| 199 | * @param c another argument.
|
---|
| 200 | * @param d another argument.
|
---|
| 201 | * @return the larger of {@code a}, {@code b}, {@code c} and {@code d}.
|
---|
| 202 | */
|
---|
[3836] | 203 | public static int max(int a, int b, int c, int d) {
|
---|
| 204 | return Math.max(Math.max(a, b), Math.max(c, d));
|
---|
| 205 | }
|
---|
| 206 |
|
---|
[7867] | 207 | /**
|
---|
| 208 | * Ensures a logical condition is met. Otherwise throws an assertion error.
|
---|
| 209 | * @param condition the condition to be met
|
---|
| 210 | * @param message Formatted error message to raise if condition is not met
|
---|
| 211 | * @param data Message parameters, optional
|
---|
| 212 | * @throws AssertionError if the condition is not met
|
---|
| 213 | */
|
---|
[4069] | 214 | public static void ensure(boolean condition, String message, Object...data) {
|
---|
| 215 | if (!condition)
|
---|
| 216 | throw new AssertionError(
|
---|
[8510] | 217 | MessageFormat.format(message, data)
|
---|
[4069] | 218 | );
|
---|
| 219 | }
|
---|
| 220 |
|
---|
[3796] | 221 | /**
|
---|
[3711] | 222 | * return the modulus in the range [0, n)
|
---|
| 223 | */
|
---|
| 224 | public static int mod(int a, int n) {
|
---|
| 225 | if (n <= 0)
|
---|
[7864] | 226 | throw new IllegalArgumentException("n must be <= 0 but is "+n);
|
---|
[3711] | 227 | int res = a % n;
|
---|
| 228 | if (res < 0) {
|
---|
| 229 | res += n;
|
---|
| 230 | }
|
---|
| 231 | return res;
|
---|
| 232 | }
|
---|
| 233 |
|
---|
[3848] | 234 | /**
|
---|
| 235 | * Joins a list of strings (or objects that can be converted to string via
|
---|
| 236 | * Object.toString()) into a single string with fields separated by sep.
|
---|
| 237 | * @param sep the separator
|
---|
| 238 | * @param values collection of objects, null is converted to the
|
---|
| 239 | * empty string
|
---|
| 240 | * @return null if values is null. The joined string otherwise.
|
---|
| 241 | */
|
---|
| 242 | public static String join(String sep, Collection<?> values) {
|
---|
[7864] | 243 | CheckParameterUtil.ensureParameterNotNull(sep, "sep");
|
---|
[3848] | 244 | if (values == null)
|
---|
| 245 | return null;
|
---|
| 246 | StringBuilder s = null;
|
---|
| 247 | for (Object a : values) {
|
---|
| 248 | if (a == null) {
|
---|
| 249 | a = "";
|
---|
| 250 | }
|
---|
[4197] | 251 | if (s != null) {
|
---|
[8376] | 252 | s.append(sep).append(a);
|
---|
[3848] | 253 | } else {
|
---|
| 254 | s = new StringBuilder(a.toString());
|
---|
| 255 | }
|
---|
| 256 | }
|
---|
[7867] | 257 | return s != null ? s.toString() : "";
|
---|
[3848] | 258 | }
|
---|
[3859] | 259 |
|
---|
[6524] | 260 | /**
|
---|
| 261 | * Converts the given iterable collection as an unordered HTML list.
|
---|
| 262 | * @param values The iterable collection
|
---|
| 263 | * @return An unordered HTML list
|
---|
| 264 | */
|
---|
| 265 | public static String joinAsHtmlUnorderedList(Iterable<?> values) {
|
---|
[5132] | 266 | StringBuilder sb = new StringBuilder(1024);
|
---|
| 267 | sb.append("<ul>");
|
---|
| 268 | for (Object i : values) {
|
---|
| 269 | sb.append("<li>").append(i).append("</li>");
|
---|
| 270 | }
|
---|
| 271 | sb.append("</ul>");
|
---|
| 272 | return sb.toString();
|
---|
| 273 | }
|
---|
| 274 |
|
---|
[3859] | 275 | /**
|
---|
| 276 | * convert Color to String
|
---|
| 277 | * (Color.toString() omits alpha value)
|
---|
| 278 | */
|
---|
| 279 | public static String toString(Color c) {
|
---|
| 280 | if (c == null)
|
---|
| 281 | return "null";
|
---|
| 282 | if (c.getAlpha() == 255)
|
---|
| 283 | return String.format("#%06x", c.getRGB() & 0x00ffffff);
|
---|
| 284 | else
|
---|
| 285 | return String.format("#%06x(alpha=%d)", c.getRGB() & 0x00ffffff, c.getAlpha());
|
---|
| 286 | }
|
---|
[3865] | 287 |
|
---|
| 288 | /**
|
---|
[6830] | 289 | * convert float range 0 <= x <= 1 to integer range 0..255
|
---|
[3865] | 290 | * when dealing with colors and color alpha value
|
---|
[3879] | 291 | * @return null if val is null, the corresponding int if val is in the
|
---|
| 292 | * range 0...1. If val is outside that range, return 255
|
---|
[3865] | 293 | */
|
---|
| 294 | public static Integer color_float2int(Float val) {
|
---|
| 295 | if (val == null)
|
---|
| 296 | return null;
|
---|
| 297 | if (val < 0 || val > 1)
|
---|
| 298 | return 255;
|
---|
| 299 | return (int) (255f * val + 0.5f);
|
---|
| 300 | }
|
---|
| 301 |
|
---|
| 302 | /**
|
---|
[6830] | 303 | * convert integer range 0..255 to float range 0 <= x <= 1
|
---|
[6749] | 304 | * when dealing with colors and color alpha value
|
---|
[3865] | 305 | */
|
---|
| 306 | public static Float color_int2float(Integer val) {
|
---|
| 307 | if (val == null)
|
---|
| 308 | return null;
|
---|
| 309 | if (val < 0 || val > 255)
|
---|
| 310 | return 1f;
|
---|
| 311 | return ((float) val) / 255f;
|
---|
| 312 | }
|
---|
| 313 |
|
---|
[4069] | 314 | public static Color complement(Color clr) {
|
---|
| 315 | return new Color(255 - clr.getRed(), 255 - clr.getGreen(), 255 - clr.getBlue(), clr.getAlpha());
|
---|
| 316 | }
|
---|
[4065] | 317 |
|
---|
[5874] | 318 | /**
|
---|
[6221] | 319 | * Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe.
|
---|
| 320 | * @param array The array to copy
|
---|
| 321 | * @return A copy of the original array, or {@code null} if {@code array} is null
|
---|
| 322 | * @since 6221
|
---|
| 323 | */
|
---|
| 324 | public static <T> T[] copyArray(T[] array) {
|
---|
| 325 | if (array != null) {
|
---|
| 326 | return Arrays.copyOf(array, array.length);
|
---|
| 327 | }
|
---|
| 328 | return null;
|
---|
| 329 | }
|
---|
[6792] | 330 |
|
---|
[6221] | 331 | /**
|
---|
[6222] | 332 | * Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe.
|
---|
| 333 | * @param array The array to copy
|
---|
| 334 | * @return A copy of the original array, or {@code null} if {@code array} is null
|
---|
| 335 | * @since 6222
|
---|
| 336 | */
|
---|
| 337 | public static char[] copyArray(char[] array) {
|
---|
| 338 | if (array != null) {
|
---|
| 339 | return Arrays.copyOf(array, array.length);
|
---|
| 340 | }
|
---|
| 341 | return null;
|
---|
| 342 | }
|
---|
[6792] | 343 |
|
---|
[6222] | 344 | /**
|
---|
[7436] | 345 | * Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe.
|
---|
| 346 | * @param array The array to copy
|
---|
| 347 | * @return A copy of the original array, or {@code null} if {@code array} is null
|
---|
| 348 | * @since 7436
|
---|
| 349 | */
|
---|
| 350 | public static int[] copyArray(int[] array) {
|
---|
| 351 | if (array != null) {
|
---|
| 352 | return Arrays.copyOf(array, array.length);
|
---|
| 353 | }
|
---|
| 354 | return null;
|
---|
| 355 | }
|
---|
| 356 |
|
---|
| 357 | /**
|
---|
[7835] | 358 | * Simple file copy function that will overwrite the target file.
|
---|
[5874] | 359 | * @param in The source file
|
---|
| 360 | * @param out The destination file
|
---|
[7003] | 361 | * @return the path to the target file
|
---|
[8291] | 362 | * @throws IOException if any I/O error occurs
|
---|
| 363 | * @throws IllegalArgumentException if {@code in} or {@code out} is {@code null}
|
---|
[7003] | 364 | * @since 7003
|
---|
[5874] | 365 | */
|
---|
[7835] | 366 | public static Path copyFile(File in, File out) throws IOException {
|
---|
[7003] | 367 | CheckParameterUtil.ensureParameterNotNull(in, "in");
|
---|
| 368 | CheckParameterUtil.ensureParameterNotNull(out, "out");
|
---|
| 369 | return Files.copy(in.toPath(), out.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
---|
[5874] | 370 | }
|
---|
[6070] | 371 |
|
---|
[7835] | 372 | /**
|
---|
| 373 | * Recursive directory copy function
|
---|
| 374 | * @param in The source directory
|
---|
| 375 | * @param out The destination directory
|
---|
[8291] | 376 | * @throws IOException if any I/O error ooccurs
|
---|
| 377 | * @throws IllegalArgumentException if {@code in} or {@code out} is {@code null}
|
---|
[7835] | 378 | * @since 7835
|
---|
| 379 | */
|
---|
| 380 | public static void copyDirectory(File in, File out) throws IOException {
|
---|
| 381 | CheckParameterUtil.ensureParameterNotNull(in, "in");
|
---|
| 382 | CheckParameterUtil.ensureParameterNotNull(out, "out");
|
---|
| 383 | if (!out.exists() && !out.mkdirs()) {
|
---|
| 384 | Main.warn("Unable to create directory "+out.getPath());
|
---|
| 385 | }
|
---|
[8308] | 386 | File[] files = in.listFiles();
|
---|
| 387 | if (files != null) {
|
---|
| 388 | for (File f : files) {
|
---|
| 389 | File target = new File(out, f.getName());
|
---|
| 390 | if (f.isDirectory()) {
|
---|
| 391 | copyDirectory(f, target);
|
---|
| 392 | } else {
|
---|
| 393 | copyFile(f, target);
|
---|
| 394 | }
|
---|
[7835] | 395 | }
|
---|
| 396 | }
|
---|
| 397 | }
|
---|
| 398 |
|
---|
[7867] | 399 | /**
|
---|
| 400 | * Copy data from source stream to output stream.
|
---|
| 401 | * @param source source stream
|
---|
| 402 | * @param destination target stream
|
---|
| 403 | * @return number of bytes copied
|
---|
| 404 | * @throws IOException if any I/O error occurs
|
---|
| 405 | */
|
---|
[4065] | 406 | public static int copyStream(InputStream source, OutputStream destination) throws IOException {
|
---|
| 407 | int count = 0;
|
---|
| 408 | byte[] b = new byte[512];
|
---|
| 409 | int read;
|
---|
| 410 | while ((read = source.read(b)) != -1) {
|
---|
| 411 | count += read;
|
---|
| 412 | destination.write(b, 0, read);
|
---|
| 413 | }
|
---|
| 414 | return count;
|
---|
| 415 | }
|
---|
| 416 |
|
---|
[7835] | 417 | /**
|
---|
| 418 | * Deletes a directory recursively.
|
---|
| 419 | * @param path The directory to delete
|
---|
| 420 | * @return <code>true</code> if and only if the file or directory is
|
---|
| 421 | * successfully deleted; <code>false</code> otherwise
|
---|
| 422 | */
|
---|
[4065] | 423 | public static boolean deleteDirectory(File path) {
|
---|
[8443] | 424 | if (path.exists()) {
|
---|
[4065] | 425 | File[] files = path.listFiles();
|
---|
[8308] | 426 | if (files != null) {
|
---|
| 427 | for (File file : files) {
|
---|
| 428 | if (file.isDirectory()) {
|
---|
| 429 | deleteDirectory(file);
|
---|
| 430 | } else if (!file.delete()) {
|
---|
| 431 | Main.warn("Unable to delete file: "+file.getPath());
|
---|
| 432 | }
|
---|
[4065] | 433 | }
|
---|
| 434 | }
|
---|
| 435 | }
|
---|
[7835] | 436 | return path.delete();
|
---|
[4065] | 437 | }
|
---|
[4087] | 438 |
|
---|
| 439 | /**
|
---|
[6823] | 440 | * <p>Utility method for closing a {@link java.io.Closeable} object.</p>
|
---|
[4668] | 441 | *
|
---|
[5874] | 442 | * @param c the closeable object. May be null.
|
---|
[4087] | 443 | */
|
---|
[5874] | 444 | public static void close(Closeable c) {
|
---|
| 445 | if (c == null) return;
|
---|
[4087] | 446 | try {
|
---|
[5874] | 447 | c.close();
|
---|
[6268] | 448 | } catch (IOException e) {
|
---|
| 449 | Main.warn(e);
|
---|
[4087] | 450 | }
|
---|
| 451 | }
|
---|
[6070] | 452 |
|
---|
[4087] | 453 | /**
|
---|
[6823] | 454 | * <p>Utility method for closing a {@link java.util.zip.ZipFile}.</p>
|
---|
[4668] | 455 | *
|
---|
[5874] | 456 | * @param zip the zip file. May be null.
|
---|
[4087] | 457 | */
|
---|
[5874] | 458 | public static void close(ZipFile zip) {
|
---|
| 459 | if (zip == null) return;
|
---|
[4087] | 460 | try {
|
---|
[5874] | 461 | zip.close();
|
---|
[6268] | 462 | } catch (IOException e) {
|
---|
| 463 | Main.warn(e);
|
---|
[4087] | 464 | }
|
---|
| 465 | }
|
---|
[6792] | 466 |
|
---|
[6615] | 467 | /**
|
---|
| 468 | * Converts the given file to its URL.
|
---|
| 469 | * @param f The file to get URL from
|
---|
| 470 | * @return The URL of the given file, or {@code null} if not possible.
|
---|
| 471 | * @since 6615
|
---|
| 472 | */
|
---|
| 473 | public static URL fileToURL(File f) {
|
---|
| 474 | if (f != null) {
|
---|
| 475 | try {
|
---|
| 476 | return f.toURI().toURL();
|
---|
| 477 | } catch (MalformedURLException ex) {
|
---|
| 478 | Main.error("Unable to convert filename " + f.getAbsolutePath() + " to URL");
|
---|
| 479 | }
|
---|
| 480 | }
|
---|
| 481 | return null;
|
---|
| 482 | }
|
---|
[4087] | 483 |
|
---|
[6889] | 484 | private static final double EPSILON = 1e-11;
|
---|
[4272] | 485 |
|
---|
[6268] | 486 | /**
|
---|
| 487 | * Determines if the two given double values are equal (their delta being smaller than a fixed epsilon)
|
---|
| 488 | * @param a The first double value to compare
|
---|
| 489 | * @param b The second double value to compare
|
---|
| 490 | * @return {@code true} if {@code abs(a - b) <= 1e-11}, {@code false} otherwise
|
---|
| 491 | */
|
---|
[4272] | 492 | public static boolean equalsEpsilon(double a, double b) {
|
---|
[6268] | 493 | return Math.abs(a - b) <= EPSILON;
|
---|
[4272] | 494 | }
|
---|
[4380] | 495 |
|
---|
| 496 | /**
|
---|
| 497 | * Copies the string {@code s} to system clipboard.
|
---|
| 498 | * @param s string to be copied to clipboard.
|
---|
| 499 | * @return true if succeeded, false otherwise.
|
---|
| 500 | */
|
---|
| 501 | public static boolean copyToClipboard(String s) {
|
---|
| 502 | try {
|
---|
| 503 | Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(s), new ClipboardOwner() {
|
---|
| 504 | @Override
|
---|
| 505 | public void lostOwnership(Clipboard clpbrd, Transferable t) {
|
---|
[8429] | 506 | // Do nothing
|
---|
[4380] | 507 | }
|
---|
| 508 | });
|
---|
| 509 | return true;
|
---|
| 510 | } catch (IllegalStateException ex) {
|
---|
[6642] | 511 | Main.error(ex);
|
---|
[4380] | 512 | return false;
|
---|
| 513 | }
|
---|
| 514 | }
|
---|
| 515 |
|
---|
| 516 | /**
|
---|
[8429] | 517 | * Extracts clipboard content as {@code Transferable} object.
|
---|
| 518 | * @param clipboard clipboard from which contents are retrieved
|
---|
| 519 | * @return clipboard contents if available, {@code null} otherwise.
|
---|
| 520 | * @since 8429
|
---|
[4380] | 521 | */
|
---|
[8429] | 522 | public static Transferable getTransferableContent(Clipboard clipboard) {
|
---|
[5221] | 523 | Transferable t = null;
|
---|
| 524 | for (int tries = 0; t == null && tries < 10; tries++) {
|
---|
| 525 | try {
|
---|
| 526 | t = clipboard.getContents(null);
|
---|
[6070] | 527 | } catch (IllegalStateException e) {
|
---|
[8429] | 528 | // Clipboard currently unavailable.
|
---|
| 529 | // On some platforms, the system clipboard is unavailable while it is accessed by another application.
|
---|
[5221] | 530 | try {
|
---|
| 531 | Thread.sleep(1);
|
---|
| 532 | } catch (InterruptedException ex) {
|
---|
[6313] | 533 | Main.warn("InterruptedException in "+Utils.class.getSimpleName()+" while getting clipboard content");
|
---|
[5221] | 534 | }
|
---|
[8429] | 535 | } catch (NullPointerException e) {
|
---|
| 536 | // JDK-6322854: On Linux/X11, NPE can happen for unknown reasons, on all versions of Java
|
---|
| 537 | Main.error(e);
|
---|
[5221] | 538 | }
|
---|
| 539 | }
|
---|
[8429] | 540 | return t;
|
---|
| 541 | }
|
---|
| 542 |
|
---|
| 543 | /**
|
---|
| 544 | * Extracts clipboard content as string.
|
---|
| 545 | * @return string clipboard contents if available, {@code null} otherwise.
|
---|
| 546 | */
|
---|
| 547 | public static String getClipboardContent() {
|
---|
| 548 | Transferable t = getTransferableContent(Toolkit.getDefaultToolkit().getSystemClipboard());
|
---|
[4380] | 549 | try {
|
---|
| 550 | if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
|
---|
[6792] | 551 | return (String) t.getTransferData(DataFlavor.stringFlavor);
|
---|
[4380] | 552 | }
|
---|
[7004] | 553 | } catch (UnsupportedFlavorException | IOException ex) {
|
---|
[6642] | 554 | Main.error(ex);
|
---|
[4380] | 555 | return null;
|
---|
| 556 | }
|
---|
| 557 | return null;
|
---|
| 558 | }
|
---|
[4403] | 559 |
|
---|
| 560 | /**
|
---|
| 561 | * Calculate MD5 hash of a string and output in hexadecimal format.
|
---|
[5589] | 562 | * @param data arbitrary String
|
---|
| 563 | * @return MD5 hash of data, string of length 32 with characters in range [0-9a-f]
|
---|
[4403] | 564 | */
|
---|
| 565 | public static String md5Hex(String data) {
|
---|
| 566 | MessageDigest md = null;
|
---|
| 567 | try {
|
---|
| 568 | md = MessageDigest.getInstance("MD5");
|
---|
| 569 | } catch (NoSuchAlgorithmException e) {
|
---|
[6798] | 570 | throw new RuntimeException(e);
|
---|
[4403] | 571 | }
|
---|
[8429] | 572 | byte[] byteData = data.getBytes(StandardCharsets.UTF_8);
|
---|
[4403] | 573 | byte[] byteDigest = md.digest(byteData);
|
---|
| 574 | return toHexString(byteDigest);
|
---|
| 575 | }
|
---|
| 576 |
|
---|
[8510] | 577 | private static final char[] HEX_ARRAY = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
|
---|
[6175] | 578 |
|
---|
[4403] | 579 | /**
|
---|
[5589] | 580 | * Converts a byte array to a string of hexadecimal characters.
|
---|
| 581 | * Preserves leading zeros, so the size of the output string is always twice
|
---|
| 582 | * the number of input bytes.
|
---|
| 583 | * @param bytes the byte array
|
---|
| 584 | * @return hexadecimal representation
|
---|
[4403] | 585 | */
|
---|
| 586 | public static String toHexString(byte[] bytes) {
|
---|
[6175] | 587 |
|
---|
| 588 | if (bytes == null) {
|
---|
| 589 | return "";
|
---|
[4403] | 590 | }
|
---|
[6175] | 591 |
|
---|
| 592 | final int len = bytes.length;
|
---|
| 593 | if (len == 0) {
|
---|
| 594 | return "";
|
---|
| 595 | }
|
---|
| 596 |
|
---|
| 597 | char[] hexChars = new char[len * 2];
|
---|
| 598 | for (int i = 0, j = 0; i < len; i++) {
|
---|
| 599 | final int v = bytes[i];
|
---|
| 600 | hexChars[j++] = HEX_ARRAY[(v & 0xf0) >> 4];
|
---|
| 601 | hexChars[j++] = HEX_ARRAY[v & 0xf];
|
---|
| 602 | }
|
---|
[4403] | 603 | return new String(hexChars);
|
---|
| 604 | }
|
---|
[4668] | 605 |
|
---|
| 606 | /**
|
---|
| 607 | * Topological sort.
|
---|
| 608 | *
|
---|
[6830] | 609 | * @param dependencies contains mappings (key -> value). In the final list of sorted objects, the key will come
|
---|
[4668] | 610 | * after the value. (In other words, the key depends on the value(s).)
|
---|
| 611 | * There must not be cyclic dependencies.
|
---|
| 612 | * @return the list of sorted objects
|
---|
| 613 | */
|
---|
[8510] | 614 | public static <T> List<T> topologicalSort(final MultiMap<T, T> dependencies) {
|
---|
| 615 | MultiMap<T, T> deps = new MultiMap<>();
|
---|
[4668] | 616 | for (T key : dependencies.keySet()) {
|
---|
| 617 | deps.putVoid(key);
|
---|
| 618 | for (T val : dependencies.get(key)) {
|
---|
| 619 | deps.putVoid(val);
|
---|
| 620 | deps.put(key, val);
|
---|
| 621 | }
|
---|
| 622 | }
|
---|
| 623 |
|
---|
| 624 | int size = deps.size();
|
---|
[7005] | 625 | List<T> sorted = new ArrayList<>();
|
---|
[8510] | 626 | for (int i = 0; i < size; ++i) {
|
---|
[4668] | 627 | T parentless = null;
|
---|
| 628 | for (T key : deps.keySet()) {
|
---|
[6093] | 629 | if (deps.get(key).isEmpty()) {
|
---|
[4668] | 630 | parentless = key;
|
---|
| 631 | break;
|
---|
| 632 | }
|
---|
| 633 | }
|
---|
| 634 | if (parentless == null) throw new RuntimeException();
|
---|
| 635 | sorted.add(parentless);
|
---|
| 636 | deps.remove(parentless);
|
---|
| 637 | for (T key : deps.keySet()) {
|
---|
| 638 | deps.remove(key, parentless);
|
---|
| 639 | }
|
---|
| 640 | }
|
---|
| 641 | if (sorted.size() != size) throw new RuntimeException();
|
---|
| 642 | return sorted;
|
---|
| 643 | }
|
---|
[4816] | 644 |
|
---|
| 645 | /**
|
---|
| 646 | * Represents a function that can be applied to objects of {@code A} and
|
---|
| 647 | * returns objects of {@code B}.
|
---|
| 648 | * @param <A> class of input objects
|
---|
| 649 | * @param <B> class of transformed objects
|
---|
| 650 | */
|
---|
[8512] | 651 | public interface Function<A, B> {
|
---|
[4816] | 652 |
|
---|
| 653 | /**
|
---|
| 654 | * Applies the function on {@code x}.
|
---|
| 655 | * @param x an object of
|
---|
| 656 | * @return the transformed object
|
---|
| 657 | */
|
---|
| 658 | B apply(A x);
|
---|
| 659 | }
|
---|
| 660 |
|
---|
| 661 | /**
|
---|
| 662 | * Transforms the collection {@code c} into an unmodifiable collection and
|
---|
[6823] | 663 | * applies the {@link org.openstreetmap.josm.tools.Utils.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 | */
|
---|
[5132] | 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 |
|
---|
[5132] | 682 | private 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
|
---|
[6823] | 705 | * applies the {@link org.openstreetmap.josm.tools.Utils.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 | */
|
---|
| 712 | public static <A, B> List<B> transform(final List<? extends A> l, final Function<A, B> f) {
|
---|
| 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 |
|
---|
[6823] | 727 | private static final Pattern HTTP_PREFFIX_PATTERN = Pattern.compile("https?");
|
---|
| 728 |
|
---|
[5577] | 729 | /**
|
---|
[5587] | 730 | * Opens a HTTP connection to the given URL and sets the User-Agent property to JOSM's one.
|
---|
| 731 | * @param httpURL The HTTP url to open (must use http:// or https://)
|
---|
| 732 | * @return An open HTTP connection to the given URL
|
---|
[6823] | 733 | * @throws java.io.IOException if an I/O exception occurs.
|
---|
[5587] | 734 | * @since 5587
|
---|
| 735 | */
|
---|
| 736 | public static HttpURLConnection openHttpConnection(URL httpURL) throws IOException {
|
---|
[6823] | 737 | if (httpURL == null || !HTTP_PREFFIX_PATTERN.matcher(httpURL.getProtocol()).matches()) {
|
---|
[5587] | 738 | throw new IllegalArgumentException("Invalid HTTP url");
|
---|
| 739 | }
|
---|
[7473] | 740 | if (Main.isDebugEnabled()) {
|
---|
| 741 | Main.debug("Opening HTTP connection to "+httpURL.toExternalForm());
|
---|
| 742 | }
|
---|
[5587] | 743 | HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection();
|
---|
[5868] | 744 | connection.setRequestProperty("User-Agent", Version.getInstance().getFullAgentString());
|
---|
[6123] | 745 | connection.setUseCaches(false);
|
---|
[5587] | 746 | return connection;
|
---|
| 747 | }
|
---|
[6070] | 748 |
|
---|
[5587] | 749 | /**
|
---|
[5868] | 750 | * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
|
---|
| 751 | * @param url The url to open
|
---|
| 752 | * @return An stream for the given URL
|
---|
[6823] | 753 | * @throws java.io.IOException if an I/O exception occurs.
|
---|
[5868] | 754 | * @since 5867
|
---|
| 755 | */
|
---|
| 756 | public static InputStream openURL(URL url) throws IOException {
|
---|
[6421] | 757 | return openURLAndDecompress(url, false);
|
---|
[5868] | 758 | }
|
---|
| 759 |
|
---|
[6421] | 760 | /**
|
---|
| 761 | * Opens a connection to the given URL, sets the User-Agent property to JOSM's one, and decompresses stream if necessary.
|
---|
| 762 | * @param url The url to open
|
---|
[7867] | 763 | * @param decompress whether to wrap steam in a {@link GZIPInputStream} or {@link BZip2CompressorInputStream}
|
---|
[6421] | 764 | * if the {@code Content-Type} header is set accordingly.
|
---|
| 765 | * @return An stream for the given URL
|
---|
| 766 | * @throws IOException if an I/O exception occurs.
|
---|
| 767 | * @since 6421
|
---|
| 768 | */
|
---|
| 769 | public static InputStream openURLAndDecompress(final URL url, final boolean decompress) throws IOException {
|
---|
| 770 | final URLConnection connection = setupURLConnection(url.openConnection());
|
---|
[7119] | 771 | final InputStream in = connection.getInputStream();
|
---|
| 772 | if (decompress) {
|
---|
| 773 | switch (connection.getHeaderField("Content-Type")) {
|
---|
| 774 | case "application/zip":
|
---|
| 775 | return getZipInputStream(in);
|
---|
| 776 | case "application/x-gzip":
|
---|
| 777 | return getGZipInputStream(in);
|
---|
| 778 | case "application/x-bzip2":
|
---|
| 779 | return getBZip2InputStream(in);
|
---|
| 780 | }
|
---|
[6421] | 781 | }
|
---|
[7119] | 782 | return in;
|
---|
[6421] | 783 | }
|
---|
| 784 |
|
---|
[7119] | 785 | /**
|
---|
| 786 | * Returns a Bzip2 input stream wrapping given input stream.
|
---|
| 787 | * @param in The raw input stream
|
---|
| 788 | * @return a Bzip2 input stream wrapping given input stream, or {@code null} if {@code in} is {@code null}
|
---|
| 789 | * @throws IOException if the given input stream does not contain valid BZ2 header
|
---|
[7867] | 790 | * @since 7867
|
---|
[7119] | 791 | */
|
---|
[7867] | 792 | public static BZip2CompressorInputStream getBZip2InputStream(InputStream in) throws IOException {
|
---|
[7119] | 793 | if (in == null) {
|
---|
| 794 | return null;
|
---|
| 795 | }
|
---|
[7869] | 796 | return new BZip2CompressorInputStream(in, /* see #9537 */ true);
|
---|
[7119] | 797 | }
|
---|
| 798 |
|
---|
| 799 | /**
|
---|
| 800 | * Returns a Gzip input stream wrapping given input stream.
|
---|
| 801 | * @param in The raw input stream
|
---|
| 802 | * @return a Gzip input stream wrapping given input stream, or {@code null} if {@code in} is {@code null}
|
---|
| 803 | * @throws IOException if an I/O error has occurred
|
---|
| 804 | * @since 7119
|
---|
| 805 | */
|
---|
| 806 | public static GZIPInputStream getGZipInputStream(InputStream in) throws IOException {
|
---|
| 807 | if (in == null) {
|
---|
| 808 | return null;
|
---|
| 809 | }
|
---|
| 810 | return new GZIPInputStream(in);
|
---|
| 811 | }
|
---|
| 812 |
|
---|
| 813 | /**
|
---|
| 814 | * Returns a Zip input stream wrapping given input stream.
|
---|
| 815 | * @param in The raw input stream
|
---|
| 816 | * @return a Zip input stream wrapping given input stream, or {@code null} if {@code in} is {@code null}
|
---|
| 817 | * @throws IOException if an I/O error has occurred
|
---|
| 818 | * @since 7119
|
---|
| 819 | */
|
---|
| 820 | public static ZipInputStream getZipInputStream(InputStream in) throws IOException {
|
---|
| 821 | if (in == null) {
|
---|
| 822 | return null;
|
---|
| 823 | }
|
---|
| 824 | ZipInputStream zis = new ZipInputStream(in, StandardCharsets.UTF_8);
|
---|
| 825 | // Positions the stream at the beginning of first entry
|
---|
| 826 | ZipEntry ze = zis.getNextEntry();
|
---|
| 827 | if (ze != null && Main.isDebugEnabled()) {
|
---|
| 828 | Main.debug("Zip entry: "+ze.getName());
|
---|
| 829 | }
|
---|
| 830 | return zis;
|
---|
| 831 | }
|
---|
| 832 |
|
---|
[5887] | 833 | /***
|
---|
| 834 | * Setups the given URL connection to match JOSM needs by setting its User-Agent and timeout properties.
|
---|
| 835 | * @param connection The connection to setup
|
---|
| 836 | * @return {@code connection}, with updated properties
|
---|
| 837 | * @since 5887
|
---|
| 838 | */
|
---|
| 839 | public static URLConnection setupURLConnection(URLConnection connection) {
|
---|
| 840 | if (connection != null) {
|
---|
| 841 | connection.setRequestProperty("User-Agent", Version.getInstance().getFullAgentString());
|
---|
[8510] | 842 | connection.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect", 15)*1000);
|
---|
| 843 | connection.setReadTimeout(Main.pref.getInteger("socket.timeout.read", 30)*1000);
|
---|
[5887] | 844 | }
|
---|
| 845 | return connection;
|
---|
| 846 | }
|
---|
| 847 |
|
---|
[5868] | 848 | /**
|
---|
| 849 | * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
|
---|
| 850 | * @param url The url to open
|
---|
| 851 | * @return An buffered stream reader for the given URL (using UTF-8)
|
---|
[6823] | 852 | * @throws java.io.IOException if an I/O exception occurs.
|
---|
[5881] | 853 | * @since 5868
|
---|
[5868] | 854 | */
|
---|
| 855 | public static BufferedReader openURLReader(URL url) throws IOException {
|
---|
[6421] | 856 | return openURLReaderAndDecompress(url, false);
|
---|
[5868] | 857 | }
|
---|
| 858 |
|
---|
| 859 | /**
|
---|
[6421] | 860 | * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
|
---|
| 861 | * @param url The url to open
|
---|
[7867] | 862 | * @param decompress whether to wrap steam in a {@link GZIPInputStream} or {@link BZip2CompressorInputStream}
|
---|
[6421] | 863 | * if the {@code Content-Type} header is set accordingly.
|
---|
| 864 | * @return An buffered stream reader for the given URL (using UTF-8)
|
---|
| 865 | * @throws IOException if an I/O exception occurs.
|
---|
| 866 | * @since 6421
|
---|
| 867 | */
|
---|
| 868 | public static BufferedReader openURLReaderAndDecompress(final URL url, final boolean decompress) throws IOException {
|
---|
[7082] | 869 | return new BufferedReader(new InputStreamReader(openURLAndDecompress(url, decompress), StandardCharsets.UTF_8));
|
---|
[6421] | 870 | }
|
---|
| 871 |
|
---|
| 872 | /**
|
---|
[5587] | 873 | * Opens a HTTP connection to the given URL, sets the User-Agent property to JOSM's one and optionnaly disables Keep-Alive.
|
---|
| 874 | * @param httpURL The HTTP url to open (must use http:// or https://)
|
---|
[6421] | 875 | * @param keepAlive whether not to set header {@code Connection=close}
|
---|
[5587] | 876 | * @return An open HTTP connection to the given URL
|
---|
[6823] | 877 | * @throws java.io.IOException if an I/O exception occurs.
|
---|
[5587] | 878 | * @since 5587
|
---|
| 879 | */
|
---|
| 880 | public static HttpURLConnection openHttpConnection(URL httpURL, boolean keepAlive) throws IOException {
|
---|
| 881 | HttpURLConnection connection = openHttpConnection(httpURL);
|
---|
| 882 | if (!keepAlive) {
|
---|
| 883 | connection.setRequestProperty("Connection", "close");
|
---|
| 884 | }
|
---|
[6852] | 885 | if (Main.isDebugEnabled()) {
|
---|
| 886 | try {
|
---|
| 887 | Main.debug("REQUEST: "+ connection.getRequestProperties());
|
---|
| 888 | } catch (IllegalStateException e) {
|
---|
| 889 | Main.warn(e);
|
---|
| 890 | }
|
---|
| 891 | }
|
---|
[5587] | 892 | return connection;
|
---|
| 893 | }
|
---|
[6070] | 894 |
|
---|
[5772] | 895 | /**
|
---|
| 896 | * An alternative to {@link String#trim()} to effectively remove all leading and trailing white characters, including Unicode ones.
|
---|
| 897 | * @param str The string to strip
|
---|
[6070] | 898 | * @return <code>str</code>, without leading and trailing characters, according to
|
---|
[5772] | 899 | * {@link Character#isWhitespace(char)} and {@link Character#isSpaceChar(char)}.
|
---|
[8419] | 900 | * @see <a href="http://closingbraces.net/2008/11/11/javastringtrim/">Java’s String.trim has a strange idea of whitespace</a>
|
---|
| 901 | * @see <a href="https://bugs.openjdk.java.net/browse/JDK-4080617">JDK bug 4080617</a>
|
---|
[5772] | 902 | * @since 5772
|
---|
| 903 | */
|
---|
[8435] | 904 | public static String strip(final String str) {
|
---|
[8567] | 905 | if (str == null || str.isEmpty()) {
|
---|
| 906 | return str;
|
---|
| 907 | }
|
---|
| 908 | return strip(str, DEFAULT_STRIP);
|
---|
[8435] | 909 | }
|
---|
| 910 |
|
---|
| 911 | /**
|
---|
| 912 | * An alternative to {@link String#trim()} to effectively remove all leading and trailing white characters, including Unicode ones.
|
---|
| 913 | * @param str The string to strip
|
---|
| 914 | * @param skipChars additional characters to skip
|
---|
| 915 | * @return <code>str</code>, without leading and trailing characters, according to
|
---|
| 916 | * {@link Character#isWhitespace(char)}, {@link Character#isSpaceChar(char)} and skipChars.
|
---|
| 917 | * @since 8435
|
---|
| 918 | */
|
---|
| 919 | public static String strip(final String str, final String skipChars) {
|
---|
[5772] | 920 | if (str == null || str.isEmpty()) {
|
---|
| 921 | return str;
|
---|
| 922 | }
|
---|
[8567] | 923 | return strip(str, stripChars(skipChars));
|
---|
| 924 | }
|
---|
| 925 |
|
---|
| 926 | private static String strip(final String str, final char[] skipChars) {
|
---|
| 927 |
|
---|
[8435] | 928 | int start = 0;
|
---|
| 929 | int end = str.length();
|
---|
| 930 | boolean leadingSkipChar = true;
|
---|
| 931 | while (leadingSkipChar && start < end) {
|
---|
[5772] | 932 | char c = str.charAt(start);
|
---|
[8567] | 933 | leadingSkipChar = Character.isWhitespace(c) || Character.isSpaceChar(c) || stripChar(skipChars, c);
|
---|
[8435] | 934 | if (leadingSkipChar) {
|
---|
[5772] | 935 | start++;
|
---|
| 936 | }
|
---|
| 937 | }
|
---|
[8435] | 938 | boolean trailingSkipChar = true;
|
---|
[8567] | 939 | while (trailingSkipChar && end > start + 1) {
|
---|
| 940 | char c = str.charAt(end - 1);
|
---|
| 941 | trailingSkipChar = Character.isWhitespace(c) || Character.isSpaceChar(c) || stripChar(skipChars, c);
|
---|
[8435] | 942 | if (trailingSkipChar) {
|
---|
[5772] | 943 | end--;
|
---|
| 944 | }
|
---|
| 945 | }
|
---|
[8567] | 946 |
|
---|
[5772] | 947 | return str.substring(start, end);
|
---|
| 948 | }
|
---|
[6103] | 949 |
|
---|
[8567] | 950 | private static char[] stripChars(final String skipChars) {
|
---|
| 951 | if (skipChars == null || skipChars.isEmpty()) {
|
---|
| 952 | return DEFAULT_STRIP;
|
---|
| 953 | }
|
---|
| 954 |
|
---|
| 955 | char[] chars = new char[DEFAULT_STRIP.length + skipChars.length()];
|
---|
| 956 | System.arraycopy(DEFAULT_STRIP, 0, chars, 0, DEFAULT_STRIP.length);
|
---|
| 957 | skipChars.getChars(0, skipChars.length(), chars, DEFAULT_STRIP.length);
|
---|
| 958 |
|
---|
| 959 | return chars;
|
---|
| 960 | }
|
---|
| 961 |
|
---|
| 962 | private static boolean stripChar(final char[] strip, char c) {
|
---|
| 963 | for (char s : strip) {
|
---|
| 964 | if (c == s) {
|
---|
| 965 | return true;
|
---|
| 966 | }
|
---|
| 967 | }
|
---|
| 968 | return false;
|
---|
| 969 | }
|
---|
| 970 |
|
---|
[6103] | 971 | /**
|
---|
| 972 | * Runs an external command and returns the standard output.
|
---|
[6792] | 973 | *
|
---|
[6103] | 974 | * The program is expected to execute fast.
|
---|
[6792] | 975 | *
|
---|
[6103] | 976 | * @param command the command with arguments
|
---|
| 977 | * @return the output
|
---|
| 978 | * @throws IOException when there was an error, e.g. command does not exist
|
---|
| 979 | */
|
---|
| 980 | public static String execOutput(List<String> command) throws IOException {
|
---|
[6962] | 981 | if (Main.isDebugEnabled()) {
|
---|
| 982 | Main.debug(join(" ", command));
|
---|
| 983 | }
|
---|
[6103] | 984 | Process p = new ProcessBuilder(command).start();
|
---|
[7082] | 985 | try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
|
---|
[7037] | 986 | StringBuilder all = null;
|
---|
| 987 | String line;
|
---|
| 988 | while ((line = input.readLine()) != null) {
|
---|
| 989 | if (all == null) {
|
---|
| 990 | all = new StringBuilder(line);
|
---|
| 991 | } else {
|
---|
[8390] | 992 | all.append('\n');
|
---|
[7037] | 993 | all.append(line);
|
---|
| 994 | }
|
---|
[6103] | 995 | }
|
---|
[7037] | 996 | return all != null ? all.toString() : null;
|
---|
[6103] | 997 | }
|
---|
| 998 | }
|
---|
[6245] | 999 |
|
---|
| 1000 | /**
|
---|
| 1001 | * Returns the JOSM temp directory.
|
---|
| 1002 | * @return The JOSM temp directory ({@code <java.io.tmpdir>/JOSM}), or {@code null} if {@code java.io.tmpdir} is not defined
|
---|
| 1003 | * @since 6245
|
---|
| 1004 | */
|
---|
| 1005 | public static File getJosmTempDir() {
|
---|
| 1006 | String tmpDir = System.getProperty("java.io.tmpdir");
|
---|
| 1007 | if (tmpDir == null) {
|
---|
| 1008 | return null;
|
---|
| 1009 | }
|
---|
| 1010 | File josmTmpDir = new File(tmpDir, "JOSM");
|
---|
[6883] | 1011 | if (!josmTmpDir.exists() && !josmTmpDir.mkdirs()) {
|
---|
[8567] | 1012 | Main.warn("Unable to create temp directory " + josmTmpDir);
|
---|
[6245] | 1013 | }
|
---|
| 1014 | return josmTmpDir;
|
---|
| 1015 | }
|
---|
[6354] | 1016 |
|
---|
| 1017 | /**
|
---|
| 1018 | * Returns a simple human readable (hours, minutes, seconds) string for a given duration in milliseconds.
|
---|
| 1019 | * @param elapsedTime The duration in milliseconds
|
---|
[6661] | 1020 | * @return A human readable string for the given duration
|
---|
[6830] | 1021 | * @throws IllegalArgumentException if elapsedTime is < 0
|
---|
[6354] | 1022 | * @since 6354
|
---|
| 1023 | */
|
---|
[7867] | 1024 | public static String getDurationString(long elapsedTime) {
|
---|
[6354] | 1025 | if (elapsedTime < 0) {
|
---|
[7321] | 1026 | throw new IllegalArgumentException("elapsedTime must be >= 0");
|
---|
[6354] | 1027 | }
|
---|
| 1028 | // Is it less than 1 second ?
|
---|
[6661] | 1029 | if (elapsedTime < MILLIS_OF_SECOND) {
|
---|
[6354] | 1030 | return String.format("%d %s", elapsedTime, tr("ms"));
|
---|
| 1031 | }
|
---|
| 1032 | // Is it less than 1 minute ?
|
---|
[6661] | 1033 | if (elapsedTime < MILLIS_OF_MINUTE) {
|
---|
[8385] | 1034 | return String.format("%.1f %s", elapsedTime / (double) MILLIS_OF_SECOND, tr("s"));
|
---|
[6354] | 1035 | }
|
---|
| 1036 | // Is it less than 1 hour ?
|
---|
[6661] | 1037 | if (elapsedTime < MILLIS_OF_HOUR) {
|
---|
| 1038 | final long min = elapsedTime / MILLIS_OF_MINUTE;
|
---|
| 1039 | return String.format("%d %s %d %s", min, tr("min"), (elapsedTime - min * MILLIS_OF_MINUTE) / MILLIS_OF_SECOND, tr("s"));
|
---|
[6354] | 1040 | }
|
---|
| 1041 | // Is it less than 1 day ?
|
---|
[6661] | 1042 | if (elapsedTime < MILLIS_OF_DAY) {
|
---|
| 1043 | final long hour = elapsedTime / MILLIS_OF_HOUR;
|
---|
| 1044 | return String.format("%d %s %d %s", hour, tr("h"), (elapsedTime - hour * MILLIS_OF_HOUR) / MILLIS_OF_MINUTE, tr("min"));
|
---|
[6354] | 1045 | }
|
---|
[6661] | 1046 | long days = elapsedTime / MILLIS_OF_DAY;
|
---|
| 1047 | return String.format("%d %s %d %s", days, trn("day", "days", days), (elapsedTime - days * MILLIS_OF_DAY) / MILLIS_OF_HOUR, tr("h"));
|
---|
[6354] | 1048 | }
|
---|
[6538] | 1049 |
|
---|
| 1050 | /**
|
---|
[6652] | 1051 | * Returns a human readable representation of a list of positions.
|
---|
[6830] | 1052 | * <p>
|
---|
[6652] | 1053 | * For instance, {@code [1,5,2,6,7} yields "1-2,5-7
|
---|
| 1054 | * @param positionList a list of positions
|
---|
| 1055 | * @return a human readable representation
|
---|
| 1056 | */
|
---|
[8567] | 1057 | public static String getPositionListString(List<Integer> positionList) {
|
---|
[6652] | 1058 | Collections.sort(positionList);
|
---|
| 1059 | final StringBuilder sb = new StringBuilder(32);
|
---|
| 1060 | sb.append(positionList.get(0));
|
---|
| 1061 | int cnt = 0;
|
---|
| 1062 | int last = positionList.get(0);
|
---|
| 1063 | for (int i = 1; i < positionList.size(); ++i) {
|
---|
| 1064 | int cur = positionList.get(i);
|
---|
| 1065 | if (cur == last + 1) {
|
---|
| 1066 | ++cnt;
|
---|
| 1067 | } else if (cnt == 0) {
|
---|
[8390] | 1068 | sb.append(',').append(cur);
|
---|
[6652] | 1069 | } else {
|
---|
[8390] | 1070 | sb.append('-').append(last);
|
---|
| 1071 | sb.append(',').append(cur);
|
---|
[6652] | 1072 | cnt = 0;
|
---|
| 1073 | }
|
---|
| 1074 | last = cur;
|
---|
| 1075 | }
|
---|
| 1076 | if (cnt >= 1) {
|
---|
[8390] | 1077 | sb.append('-').append(last);
|
---|
[6652] | 1078 | }
|
---|
| 1079 | return sb.toString();
|
---|
| 1080 | }
|
---|
| 1081 |
|
---|
| 1082 | /**
|
---|
[6538] | 1083 | * Returns a list of capture groups if {@link Matcher#matches()}, or {@code null}.
|
---|
| 1084 | * The first element (index 0) is the complete match.
|
---|
| 1085 | * Further elements correspond to the parts in parentheses of the regular expression.
|
---|
| 1086 | * @param m the matcher
|
---|
| 1087 | * @return a list of capture groups if {@link Matcher#matches()}, or {@code null}.
|
---|
| 1088 | */
|
---|
| 1089 | public static List<String> getMatches(final Matcher m) {
|
---|
| 1090 | if (m.matches()) {
|
---|
[7005] | 1091 | List<String> result = new ArrayList<>(m.groupCount() + 1);
|
---|
[6538] | 1092 | for (int i = 0; i <= m.groupCount(); i++) {
|
---|
| 1093 | result.add(m.group(i));
|
---|
| 1094 | }
|
---|
| 1095 | return result;
|
---|
| 1096 | } else {
|
---|
| 1097 | return null;
|
---|
| 1098 | }
|
---|
| 1099 | }
|
---|
[6578] | 1100 |
|
---|
| 1101 | /**
|
---|
| 1102 | * Cast an object savely.
|
---|
| 1103 | * @param <T> the target type
|
---|
| 1104 | * @param o the object to cast
|
---|
| 1105 | * @param klass the target class (same as T)
|
---|
| 1106 | * @return null if <code>o</code> is null or the type <code>o</code> is not
|
---|
| 1107 | * a subclass of <code>klass</code>. The casted value otherwise.
|
---|
| 1108 | */
|
---|
[6623] | 1109 | @SuppressWarnings("unchecked")
|
---|
[6578] | 1110 | public static <T> T cast(Object o, Class<T> klass) {
|
---|
| 1111 | if (klass.isInstance(o)) {
|
---|
[6623] | 1112 | return (T) o;
|
---|
[6578] | 1113 | }
|
---|
| 1114 | return null;
|
---|
| 1115 | }
|
---|
| 1116 |
|
---|
[6642] | 1117 | /**
|
---|
| 1118 | * Returns the root cause of a throwable object.
|
---|
| 1119 | * @param t The object to get root cause for
|
---|
| 1120 | * @return the root cause of {@code t}
|
---|
| 1121 | * @since 6639
|
---|
| 1122 | */
|
---|
| 1123 | public static Throwable getRootCause(Throwable t) {
|
---|
| 1124 | Throwable result = t;
|
---|
| 1125 | if (result != null) {
|
---|
| 1126 | Throwable cause = result.getCause();
|
---|
[7867] | 1127 | while (cause != null && !cause.equals(result)) {
|
---|
[6642] | 1128 | result = cause;
|
---|
| 1129 | cause = result.getCause();
|
---|
| 1130 | }
|
---|
| 1131 | }
|
---|
| 1132 | return result;
|
---|
| 1133 | }
|
---|
[6792] | 1134 |
|
---|
[6717] | 1135 | /**
|
---|
| 1136 | * Adds the given item at the end of a new copy of given array.
|
---|
| 1137 | * @param array The source array
|
---|
| 1138 | * @param item The item to add
|
---|
| 1139 | * @return An extended copy of {@code array} containing {@code item} as additional last element
|
---|
| 1140 | * @since 6717
|
---|
| 1141 | */
|
---|
| 1142 | public static <T> T[] addInArrayCopy(T[] array, T item) {
|
---|
| 1143 | T[] biggerCopy = Arrays.copyOf(array, array.length + 1);
|
---|
| 1144 | biggerCopy[array.length] = item;
|
---|
| 1145 | return biggerCopy;
|
---|
| 1146 | }
|
---|
[6742] | 1147 |
|
---|
| 1148 | /**
|
---|
| 1149 | * If the string {@code s} is longer than {@code maxLength}, the string is cut and "..." is appended.
|
---|
[7867] | 1150 | * @param s String to shorten
|
---|
| 1151 | * @param maxLength maximum number of characters to keep (not including the "...")
|
---|
| 1152 | * @return the shortened string
|
---|
[6742] | 1153 | */
|
---|
| 1154 | public static String shortenString(String s, int maxLength) {
|
---|
| 1155 | if (s != null && s.length() > maxLength) {
|
---|
| 1156 | return s.substring(0, maxLength - 3) + "...";
|
---|
| 1157 | } else {
|
---|
| 1158 | return s;
|
---|
| 1159 | }
|
---|
| 1160 | }
|
---|
[7019] | 1161 |
|
---|
[6972] | 1162 | /**
|
---|
[7019] | 1163 | * Fixes URL with illegal characters in the query (and fragment) part by
|
---|
[6972] | 1164 | * percent encoding those characters.
|
---|
[7019] | 1165 | *
|
---|
[6972] | 1166 | * special characters like & and # are not encoded
|
---|
[7019] | 1167 | *
|
---|
[6972] | 1168 | * @param url the URL that should be fixed
|
---|
| 1169 | * @return the repaired URL
|
---|
| 1170 | */
|
---|
| 1171 | public static String fixURLQuery(String url) {
|
---|
[7019] | 1172 | if (url.indexOf('?') == -1)
|
---|
[6972] | 1173 | return url;
|
---|
[7019] | 1174 |
|
---|
[6972] | 1175 | String query = url.substring(url.indexOf('?') + 1);
|
---|
[7019] | 1176 |
|
---|
[6972] | 1177 | StringBuilder sb = new StringBuilder(url.substring(0, url.indexOf('?') + 1));
|
---|
[7019] | 1178 |
|
---|
[8510] | 1179 | for (int i = 0; i < query.length(); i++) {
|
---|
[8567] | 1180 | String c = query.substring(i, i + 1);
|
---|
[6972] | 1181 | if (URL_CHARS.contains(c)) {
|
---|
| 1182 | sb.append(c);
|
---|
| 1183 | } else {
|
---|
[8304] | 1184 | sb.append(encodeUrl(c));
|
---|
[6972] | 1185 | }
|
---|
| 1186 | }
|
---|
| 1187 | return sb.toString();
|
---|
| 1188 | }
|
---|
[7019] | 1189 |
|
---|
[7356] | 1190 | /**
|
---|
[8304] | 1191 | * Translates a string into <code>application/x-www-form-urlencoded</code>
|
---|
| 1192 | * format. This method uses UTF-8 encoding scheme to obtain the bytes for unsafe
|
---|
| 1193 | * characters.
|
---|
| 1194 | *
|
---|
| 1195 | * @param s <code>String</code> to be translated.
|
---|
| 1196 | * @return the translated <code>String</code>.
|
---|
| 1197 | * @see #decodeUrl(String)
|
---|
| 1198 | * @since 8304
|
---|
| 1199 | */
|
---|
| 1200 | public static String encodeUrl(String s) {
|
---|
| 1201 | final String enc = StandardCharsets.UTF_8.name();
|
---|
| 1202 | try {
|
---|
| 1203 | return URLEncoder.encode(s, enc);
|
---|
| 1204 | } catch (UnsupportedEncodingException e) {
|
---|
| 1205 | Main.error(e);
|
---|
| 1206 | return null;
|
---|
| 1207 | }
|
---|
| 1208 | }
|
---|
| 1209 |
|
---|
| 1210 | /**
|
---|
| 1211 | * Decodes a <code>application/x-www-form-urlencoded</code> string.
|
---|
| 1212 | * UTF-8 encoding is used to determine
|
---|
| 1213 | * what characters are represented by any consecutive sequences of the
|
---|
| 1214 | * form "<code>%<i>xy</i></code>".
|
---|
| 1215 | *
|
---|
| 1216 | * @param s the <code>String</code> to decode
|
---|
| 1217 | * @return the newly decoded <code>String</code>
|
---|
| 1218 | * @see #encodeUrl(String)
|
---|
| 1219 | * @since 8304
|
---|
| 1220 | */
|
---|
| 1221 | public static String decodeUrl(String s) {
|
---|
| 1222 | final String enc = StandardCharsets.UTF_8.name();
|
---|
| 1223 | try {
|
---|
| 1224 | return URLDecoder.decode(s, enc);
|
---|
| 1225 | } catch (UnsupportedEncodingException e) {
|
---|
| 1226 | Main.error(e);
|
---|
| 1227 | return null;
|
---|
| 1228 | }
|
---|
| 1229 | }
|
---|
| 1230 |
|
---|
| 1231 | /**
|
---|
[7356] | 1232 | * Determines if the given URL denotes a file on a local filesystem.
|
---|
| 1233 | * @param url The URL to test
|
---|
| 1234 | * @return {@code true} if the url points to a local file
|
---|
| 1235 | * @since 7356
|
---|
| 1236 | */
|
---|
| 1237 | public static boolean isLocalUrl(String url) {
|
---|
| 1238 | if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("resource://"))
|
---|
| 1239 | return false;
|
---|
| 1240 | return true;
|
---|
| 1241 | }
|
---|
[7423] | 1242 |
|
---|
| 1243 | /**
|
---|
| 1244 | * Returns a pair containing the number of threads (n), and a thread pool (if n > 1) to perform
|
---|
| 1245 | * multi-thread computation in the context of the given preference key.
|
---|
| 1246 | * @param pref The preference key
|
---|
| 1247 | * @return a pair containing the number of threads (n), and a thread pool (if n > 1, null otherwise)
|
---|
| 1248 | * @since 7423
|
---|
| 1249 | */
|
---|
| 1250 | public static Pair<Integer, ExecutorService> newThreadPool(String pref) {
|
---|
| 1251 | int noThreads = Main.pref.getInteger(pref, Runtime.getRuntime().availableProcessors());
|
---|
| 1252 | ExecutorService pool = noThreads <= 1 ? null : Executors.newFixedThreadPool(noThreads);
|
---|
| 1253 | return new Pair<>(noThreads, pool);
|
---|
| 1254 | }
|
---|
[7894] | 1255 |
|
---|
| 1256 | /**
|
---|
| 1257 | * Updates a given system property.
|
---|
| 1258 | * @param key The property key
|
---|
| 1259 | * @param value The property value
|
---|
| 1260 | * @return the previous value of the system property, or {@code null} if it did not have one.
|
---|
| 1261 | * @since 7894
|
---|
| 1262 | */
|
---|
| 1263 | public static String updateSystemProperty(String key, String value) {
|
---|
| 1264 | if (value != null) {
|
---|
| 1265 | String old = System.setProperty(key, value);
|
---|
[8404] | 1266 | if (!key.toLowerCase(Locale.ENGLISH).contains("password")) {
|
---|
[8567] | 1267 | Main.debug("System property '" + key + "' set to '" + value + "'. Old value was '" + old + "'");
|
---|
[7894] | 1268 | } else {
|
---|
[8567] | 1269 | Main.debug("System property '" + key + "' changed.");
|
---|
[7894] | 1270 | }
|
---|
| 1271 | return old;
|
---|
| 1272 | }
|
---|
| 1273 | return null;
|
---|
| 1274 | }
|
---|
[8287] | 1275 |
|
---|
| 1276 | /**
|
---|
| 1277 | * Returns a new secure SAX parser, supporting XML namespaces.
|
---|
| 1278 | * @return a new secure SAX parser, supporting XML namespaces
|
---|
| 1279 | * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
|
---|
| 1280 | * @throws SAXException for SAX errors.
|
---|
| 1281 | * @since 8287
|
---|
| 1282 | */
|
---|
| 1283 | public static SAXParser newSafeSAXParser() throws ParserConfigurationException, SAXException {
|
---|
| 1284 | SAXParserFactory parserFactory = SAXParserFactory.newInstance();
|
---|
| 1285 | parserFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
---|
| 1286 | parserFactory.setNamespaceAware(true);
|
---|
| 1287 | return parserFactory.newSAXParser();
|
---|
| 1288 | }
|
---|
[8347] | 1289 |
|
---|
| 1290 | /**
|
---|
| 1291 | * Parse the content given {@link org.xml.sax.InputSource} as XML using the specified {@link org.xml.sax.helpers.DefaultHandler}.
|
---|
| 1292 | * This method uses a secure SAX parser, supporting XML namespaces.
|
---|
| 1293 | *
|
---|
| 1294 | * @param is The InputSource containing the content to be parsed.
|
---|
| 1295 | * @param dh The SAX DefaultHandler to use.
|
---|
| 1296 | * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
|
---|
| 1297 | * @throws SAXException for SAX errors.
|
---|
| 1298 | * @throws IOException if any IO errors occur.
|
---|
| 1299 | * @since 8347
|
---|
| 1300 | */
|
---|
| 1301 | public static void parseSafeSAX(InputSource is, DefaultHandler dh) throws ParserConfigurationException, SAXException, IOException {
|
---|
| 1302 | long start = System.currentTimeMillis();
|
---|
| 1303 | if (Main.isDebugEnabled()) {
|
---|
[8567] | 1304 | Main.debug("Starting SAX parsing of " + is + " using " + dh);
|
---|
[8347] | 1305 | }
|
---|
| 1306 | newSafeSAXParser().parse(is, dh);
|
---|
| 1307 | if (Main.isDebugEnabled()) {
|
---|
[8567] | 1308 | Main.debug("SAX parsing done in " + getDurationString(System.currentTimeMillis() - start));
|
---|
[8347] | 1309 | }
|
---|
| 1310 | }
|
---|
[8404] | 1311 |
|
---|
| 1312 | /**
|
---|
| 1313 | * Determines if the filename has one of the given extensions, in a robust manner.
|
---|
| 1314 | * The comparison is case and locale insensitive.
|
---|
| 1315 | * @param filename The file name
|
---|
| 1316 | * @param extensions The list of extensions to look for (without dot)
|
---|
| 1317 | * @return {@code true} if the filename has one of the given extensions
|
---|
| 1318 | * @since 8404
|
---|
| 1319 | */
|
---|
[8567] | 1320 | public static boolean hasExtension(String filename, String... extensions) {
|
---|
[8404] | 1321 | String name = filename.toLowerCase(Locale.ENGLISH);
|
---|
[8513] | 1322 | for (String ext : extensions) {
|
---|
[8567] | 1323 | if (name.endsWith("." + ext.toLowerCase(Locale.ENGLISH)))
|
---|
[8404] | 1324 | return true;
|
---|
[8513] | 1325 | }
|
---|
[8404] | 1326 | return false;
|
---|
| 1327 | }
|
---|
| 1328 |
|
---|
| 1329 | /**
|
---|
| 1330 | * Determines if the file's name has one of the given extensions, in a robust manner.
|
---|
| 1331 | * The comparison is case and locale insensitive.
|
---|
| 1332 | * @param file The file
|
---|
| 1333 | * @param extensions The list of extensions to look for (without dot)
|
---|
| 1334 | * @return {@code true} if the file's name has one of the given extensions
|
---|
| 1335 | * @since 8404
|
---|
| 1336 | */
|
---|
[8567] | 1337 | public static boolean hasExtension(File file, String... extensions) {
|
---|
[8404] | 1338 | return hasExtension(file.getName(), extensions);
|
---|
| 1339 | }
|
---|
[8568] | 1340 |
|
---|
| 1341 | /**
|
---|
| 1342 | * Reads the input stream and closes the stream at the end of processing (regardless if an exception was thrown)
|
---|
| 1343 | *
|
---|
| 1344 | * @param stream
|
---|
| 1345 | * @return byte array of data in input stream
|
---|
| 1346 | * @throws IOException
|
---|
| 1347 | */
|
---|
| 1348 | public static byte[] readBytesFromStream(InputStream stream) throws IOException {
|
---|
| 1349 | try {
|
---|
| 1350 | ByteArrayOutputStream bout = new ByteArrayOutputStream(stream.available());
|
---|
| 1351 | byte[] buffer = new byte[2048];
|
---|
| 1352 | boolean finished = false;
|
---|
| 1353 | do {
|
---|
| 1354 | int read = stream.read(buffer);
|
---|
| 1355 | if (read >= 0) {
|
---|
| 1356 | bout.write(buffer, 0, read);
|
---|
| 1357 | } else {
|
---|
| 1358 | finished = true;
|
---|
| 1359 | }
|
---|
| 1360 | } while (!finished);
|
---|
| 1361 | if (bout.size() == 0)
|
---|
| 1362 | return null;
|
---|
| 1363 | return bout.toByteArray();
|
---|
| 1364 | } finally {
|
---|
| 1365 | stream.close();
|
---|
| 1366 | }
|
---|
| 1367 | }
|
---|
[4069] | 1368 | }
|
---|