source: josm/trunk/src/org/openstreetmap/josm/tools/Utils.java@ 8795

Last change on this file since 8795 was 8795, checked in by Don-vip, 9 years ago

fix javadoc errors/warnings seen with JDK9

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