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

Last change on this file since 8722 was 8650, checked in by wiktorn, 9 years ago

Follow HTTP(S) redirects in Add WMS wizzard / GetLayers. Closes: #11770

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