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