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