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

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

Properly handle file based tile sources.

  • move getThreadFactory(String name) to Utils class, so it's easily usable across JOSM
  • rollback changes in [8485]
  • detect that we are working with filesystem TileSource in AbstractTileSourceLayer and if so, do not use JCS as caching mechanism, as tiles are already local
  • change return value of getTileSourceInfo in AbstractTileSourceLayer to AbstractTMSTileSource, as this is anyway - lowest we can work with
  • add test data for testing file base tile sources

closes: #11548

  • Property svn:eol-style set to native
File size: 50.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.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 * An alternative to {@link String#trim()} to effectively remove all leading and trailing white characters, including Unicode ones.
898 * @param str The string to strip
899 * @return <code>str</code>, without leading and trailing characters, according to
900 * {@link Character#isWhitespace(char)} and {@link Character#isSpaceChar(char)}.
901 * @see <a href="http://closingbraces.net/2008/11/11/javastringtrim/">Java’s String.trim has a strange idea of whitespace</a>
902 * @see <a href="https://bugs.openjdk.java.net/browse/JDK-4080617">JDK bug 4080617</a>
903 * @since 5772
904 */
905 public static String strip(final String str) {
906 if (str == null || str.isEmpty()) {
907 return str;
908 }
909 return strip(str, DEFAULT_STRIP);
910 }
911
912 /**
913 * An alternative to {@link String#trim()} to effectively remove all leading and trailing white characters, including Unicode ones.
914 * @param str The string to strip
915 * @param skipChars additional characters to skip
916 * @return <code>str</code>, without leading and trailing characters, according to
917 * {@link Character#isWhitespace(char)}, {@link Character#isSpaceChar(char)} and skipChars.
918 * @since 8435
919 */
920 public static String strip(final String str, final String skipChars) {
921 if (str == null || str.isEmpty()) {
922 return str;
923 }
924 return strip(str, stripChars(skipChars));
925 }
926
927 private static String strip(final String str, final char[] skipChars) {
928
929 int start = 0;
930 int end = str.length();
931 boolean leadingSkipChar = true;
932 while (leadingSkipChar && start < end) {
933 char c = str.charAt(start);
934 leadingSkipChar = Character.isWhitespace(c) || Character.isSpaceChar(c) || stripChar(skipChars, c);
935 if (leadingSkipChar) {
936 start++;
937 }
938 }
939 boolean trailingSkipChar = true;
940 while (trailingSkipChar && end > start + 1) {
941 char c = str.charAt(end - 1);
942 trailingSkipChar = Character.isWhitespace(c) || Character.isSpaceChar(c) || stripChar(skipChars, c);
943 if (trailingSkipChar) {
944 end--;
945 }
946 }
947
948 return str.substring(start, end);
949 }
950
951 private static char[] stripChars(final String skipChars) {
952 if (skipChars == null || skipChars.isEmpty()) {
953 return DEFAULT_STRIP;
954 }
955
956 char[] chars = new char[DEFAULT_STRIP.length + skipChars.length()];
957 System.arraycopy(DEFAULT_STRIP, 0, chars, 0, DEFAULT_STRIP.length);
958 skipChars.getChars(0, skipChars.length(), chars, DEFAULT_STRIP.length);
959
960 return chars;
961 }
962
963 private static boolean stripChar(final char[] strip, char c) {
964 for (char s : strip) {
965 if (c == s) {
966 return true;
967 }
968 }
969 return false;
970 }
971
972 /**
973 * Runs an external command and returns the standard output.
974 *
975 * The program is expected to execute fast.
976 *
977 * @param command the command with arguments
978 * @return the output
979 * @throws IOException when there was an error, e.g. command does not exist
980 */
981 public static String execOutput(List<String> command) throws IOException {
982 if (Main.isDebugEnabled()) {
983 Main.debug(join(" ", command));
984 }
985 Process p = new ProcessBuilder(command).start();
986 try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
987 StringBuilder all = null;
988 String line;
989 while ((line = input.readLine()) != null) {
990 if (all == null) {
991 all = new StringBuilder(line);
992 } else {
993 all.append('\n');
994 all.append(line);
995 }
996 }
997 return all != null ? all.toString() : null;
998 }
999 }
1000
1001 /**
1002 * Returns the JOSM temp directory.
1003 * @return The JOSM temp directory ({@code <java.io.tmpdir>/JOSM}), or {@code null} if {@code java.io.tmpdir} is not defined
1004 * @since 6245
1005 */
1006 public static File getJosmTempDir() {
1007 String tmpDir = System.getProperty("java.io.tmpdir");
1008 if (tmpDir == null) {
1009 return null;
1010 }
1011 File josmTmpDir = new File(tmpDir, "JOSM");
1012 if (!josmTmpDir.exists() && !josmTmpDir.mkdirs()) {
1013 Main.warn("Unable to create temp directory " + josmTmpDir);
1014 }
1015 return josmTmpDir;
1016 }
1017
1018 /**
1019 * Returns a simple human readable (hours, minutes, seconds) string for a given duration in milliseconds.
1020 * @param elapsedTime The duration in milliseconds
1021 * @return A human readable string for the given duration
1022 * @throws IllegalArgumentException if elapsedTime is &lt; 0
1023 * @since 6354
1024 */
1025 public static String getDurationString(long elapsedTime) {
1026 if (elapsedTime < 0) {
1027 throw new IllegalArgumentException("elapsedTime must be >= 0");
1028 }
1029 // Is it less than 1 second ?
1030 if (elapsedTime < MILLIS_OF_SECOND) {
1031 return String.format("%d %s", elapsedTime, tr("ms"));
1032 }
1033 // Is it less than 1 minute ?
1034 if (elapsedTime < MILLIS_OF_MINUTE) {
1035 return String.format("%.1f %s", elapsedTime / (double) MILLIS_OF_SECOND, tr("s"));
1036 }
1037 // Is it less than 1 hour ?
1038 if (elapsedTime < MILLIS_OF_HOUR) {
1039 final long min = elapsedTime / MILLIS_OF_MINUTE;
1040 return String.format("%d %s %d %s", min, tr("min"), (elapsedTime - min * MILLIS_OF_MINUTE) / MILLIS_OF_SECOND, tr("s"));
1041 }
1042 // Is it less than 1 day ?
1043 if (elapsedTime < MILLIS_OF_DAY) {
1044 final long hour = elapsedTime / MILLIS_OF_HOUR;
1045 return String.format("%d %s %d %s", hour, tr("h"), (elapsedTime - hour * MILLIS_OF_HOUR) / MILLIS_OF_MINUTE, tr("min"));
1046 }
1047 long days = elapsedTime / MILLIS_OF_DAY;
1048 return String.format("%d %s %d %s", days, trn("day", "days", days), (elapsedTime - days * MILLIS_OF_DAY) / MILLIS_OF_HOUR, tr("h"));
1049 }
1050
1051 /**
1052 * Returns a human readable representation of a list of positions.
1053 * <p>
1054 * For instance, {@code [1,5,2,6,7} yields "1-2,5-7
1055 * @param positionList a list of positions
1056 * @return a human readable representation
1057 */
1058 public static String getPositionListString(List<Integer> positionList) {
1059 Collections.sort(positionList);
1060 final StringBuilder sb = new StringBuilder(32);
1061 sb.append(positionList.get(0));
1062 int cnt = 0;
1063 int last = positionList.get(0);
1064 for (int i = 1; i < positionList.size(); ++i) {
1065 int cur = positionList.get(i);
1066 if (cur == last + 1) {
1067 ++cnt;
1068 } else if (cnt == 0) {
1069 sb.append(',').append(cur);
1070 } else {
1071 sb.append('-').append(last);
1072 sb.append(',').append(cur);
1073 cnt = 0;
1074 }
1075 last = cur;
1076 }
1077 if (cnt >= 1) {
1078 sb.append('-').append(last);
1079 }
1080 return sb.toString();
1081 }
1082
1083 /**
1084 * Returns a list of capture groups if {@link Matcher#matches()}, or {@code null}.
1085 * The first element (index 0) is the complete match.
1086 * Further elements correspond to the parts in parentheses of the regular expression.
1087 * @param m the matcher
1088 * @return a list of capture groups if {@link Matcher#matches()}, or {@code null}.
1089 */
1090 public static List<String> getMatches(final Matcher m) {
1091 if (m.matches()) {
1092 List<String> result = new ArrayList<>(m.groupCount() + 1);
1093 for (int i = 0; i <= m.groupCount(); i++) {
1094 result.add(m.group(i));
1095 }
1096 return result;
1097 } else {
1098 return null;
1099 }
1100 }
1101
1102 /**
1103 * Cast an object savely.
1104 * @param <T> the target type
1105 * @param o the object to cast
1106 * @param klass the target class (same as T)
1107 * @return null if <code>o</code> is null or the type <code>o</code> is not
1108 * a subclass of <code>klass</code>. The casted value otherwise.
1109 */
1110 @SuppressWarnings("unchecked")
1111 public static <T> T cast(Object o, Class<T> klass) {
1112 if (klass.isInstance(o)) {
1113 return (T) o;
1114 }
1115 return null;
1116 }
1117
1118 /**
1119 * Returns the root cause of a throwable object.
1120 * @param t The object to get root cause for
1121 * @return the root cause of {@code t}
1122 * @since 6639
1123 */
1124 public static Throwable getRootCause(Throwable t) {
1125 Throwable result = t;
1126 if (result != null) {
1127 Throwable cause = result.getCause();
1128 while (cause != null && !cause.equals(result)) {
1129 result = cause;
1130 cause = result.getCause();
1131 }
1132 }
1133 return result;
1134 }
1135
1136 /**
1137 * Adds the given item at the end of a new copy of given array.
1138 * @param array The source array
1139 * @param item The item to add
1140 * @return An extended copy of {@code array} containing {@code item} as additional last element
1141 * @since 6717
1142 */
1143 public static <T> T[] addInArrayCopy(T[] array, T item) {
1144 T[] biggerCopy = Arrays.copyOf(array, array.length + 1);
1145 biggerCopy[array.length] = item;
1146 return biggerCopy;
1147 }
1148
1149 /**
1150 * If the string {@code s} is longer than {@code maxLength}, the string is cut and "..." is appended.
1151 * @param s String to shorten
1152 * @param maxLength maximum number of characters to keep (not including the "...")
1153 * @return the shortened string
1154 */
1155 public static String shortenString(String s, int maxLength) {
1156 if (s != null && s.length() > maxLength) {
1157 return s.substring(0, maxLength - 3) + "...";
1158 } else {
1159 return s;
1160 }
1161 }
1162
1163 /**
1164 * Fixes URL with illegal characters in the query (and fragment) part by
1165 * percent encoding those characters.
1166 *
1167 * special characters like &amp; and # are not encoded
1168 *
1169 * @param url the URL that should be fixed
1170 * @return the repaired URL
1171 */
1172 public static String fixURLQuery(String url) {
1173 if (url.indexOf('?') == -1)
1174 return url;
1175
1176 String query = url.substring(url.indexOf('?') + 1);
1177
1178 StringBuilder sb = new StringBuilder(url.substring(0, url.indexOf('?') + 1));
1179
1180 for (int i = 0; i < query.length(); i++) {
1181 String c = query.substring(i, i + 1);
1182 if (URL_CHARS.contains(c)) {
1183 sb.append(c);
1184 } else {
1185 sb.append(encodeUrl(c));
1186 }
1187 }
1188 return sb.toString();
1189 }
1190
1191 /**
1192 * Translates a string into <code>application/x-www-form-urlencoded</code>
1193 * format. This method uses UTF-8 encoding scheme to obtain the bytes for unsafe
1194 * characters.
1195 *
1196 * @param s <code>String</code> to be translated.
1197 * @return the translated <code>String</code>.
1198 * @see #decodeUrl(String)
1199 * @since 8304
1200 */
1201 public static String encodeUrl(String s) {
1202 final String enc = StandardCharsets.UTF_8.name();
1203 try {
1204 return URLEncoder.encode(s, enc);
1205 } catch (UnsupportedEncodingException e) {
1206 Main.error(e);
1207 return null;
1208 }
1209 }
1210
1211 /**
1212 * Decodes a <code>application/x-www-form-urlencoded</code> string.
1213 * UTF-8 encoding is used to determine
1214 * what characters are represented by any consecutive sequences of the
1215 * form "<code>%<i>xy</i></code>".
1216 *
1217 * @param s the <code>String</code> to decode
1218 * @return the newly decoded <code>String</code>
1219 * @see #encodeUrl(String)
1220 * @since 8304
1221 */
1222 public static String decodeUrl(String s) {
1223 final String enc = StandardCharsets.UTF_8.name();
1224 try {
1225 return URLDecoder.decode(s, enc);
1226 } catch (UnsupportedEncodingException e) {
1227 Main.error(e);
1228 return null;
1229 }
1230 }
1231
1232 /**
1233 * Determines if the given URL denotes a file on a local filesystem.
1234 * @param url The URL to test
1235 * @return {@code true} if the url points to a local file
1236 * @since 7356
1237 */
1238 public static boolean isLocalUrl(String url) {
1239 if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("resource://"))
1240 return false;
1241 return true;
1242 }
1243
1244 /**
1245 * Returns a pair containing the number of threads (n), and a thread pool (if n > 1) to perform
1246 * multi-thread computation in the context of the given preference key.
1247 * @param pref The preference key
1248 * @return a pair containing the number of threads (n), and a thread pool (if n > 1, null otherwise)
1249 * @since 7423
1250 */
1251 public static Pair<Integer, ExecutorService> newThreadPool(String pref) {
1252 int noThreads = Main.pref.getInteger(pref, Runtime.getRuntime().availableProcessors());
1253 ExecutorService pool = noThreads <= 1 ? null : Executors.newFixedThreadPool(noThreads);
1254 return new Pair<>(noThreads, pool);
1255 }
1256
1257 /**
1258 * Updates a given system property.
1259 * @param key The property key
1260 * @param value The property value
1261 * @return the previous value of the system property, or {@code null} if it did not have one.
1262 * @since 7894
1263 */
1264 public static String updateSystemProperty(String key, String value) {
1265 if (value != null) {
1266 String old = System.setProperty(key, value);
1267 if (!key.toLowerCase(Locale.ENGLISH).contains("password")) {
1268 Main.debug("System property '" + key + "' set to '" + value + "'. Old value was '" + old + "'");
1269 } else {
1270 Main.debug("System property '" + key + "' changed.");
1271 }
1272 return old;
1273 }
1274 return null;
1275 }
1276
1277 /**
1278 * Returns a new secure SAX parser, supporting XML namespaces.
1279 * @return a new secure SAX parser, supporting XML namespaces
1280 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1281 * @throws SAXException for SAX errors.
1282 * @since 8287
1283 */
1284 public static SAXParser newSafeSAXParser() throws ParserConfigurationException, SAXException {
1285 SAXParserFactory parserFactory = SAXParserFactory.newInstance();
1286 parserFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
1287 parserFactory.setNamespaceAware(true);
1288 return parserFactory.newSAXParser();
1289 }
1290
1291 /**
1292 * Parse the content given {@link org.xml.sax.InputSource} as XML using the specified {@link org.xml.sax.helpers.DefaultHandler}.
1293 * This method uses a secure SAX parser, supporting XML namespaces.
1294 *
1295 * @param is The InputSource containing the content to be parsed.
1296 * @param dh The SAX DefaultHandler to use.
1297 * @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
1298 * @throws SAXException for SAX errors.
1299 * @throws IOException if any IO errors occur.
1300 * @since 8347
1301 */
1302 public static void parseSafeSAX(InputSource is, DefaultHandler dh) throws ParserConfigurationException, SAXException, IOException {
1303 long start = System.currentTimeMillis();
1304 if (Main.isDebugEnabled()) {
1305 Main.debug("Starting SAX parsing of " + is + " using " + dh);
1306 }
1307 newSafeSAXParser().parse(is, dh);
1308 if (Main.isDebugEnabled()) {
1309 Main.debug("SAX parsing done in " + getDurationString(System.currentTimeMillis() - start));
1310 }
1311 }
1312
1313 /**
1314 * Determines if the filename has one of the given extensions, in a robust manner.
1315 * The comparison is case and locale insensitive.
1316 * @param filename The file name
1317 * @param extensions The list of extensions to look for (without dot)
1318 * @return {@code true} if the filename has one of the given extensions
1319 * @since 8404
1320 */
1321 public static boolean hasExtension(String filename, String... extensions) {
1322 String name = filename.toLowerCase(Locale.ENGLISH);
1323 for (String ext : extensions) {
1324 if (name.endsWith("." + ext.toLowerCase(Locale.ENGLISH)))
1325 return true;
1326 }
1327 return false;
1328 }
1329
1330 /**
1331 * Determines if the file's name has one of the given extensions, in a robust manner.
1332 * The comparison is case and locale insensitive.
1333 * @param file The file
1334 * @param extensions The list of extensions to look for (without dot)
1335 * @return {@code true} if the file's name has one of the given extensions
1336 * @since 8404
1337 */
1338 public static boolean hasExtension(File file, String... extensions) {
1339 return hasExtension(file.getName(), extensions);
1340 }
1341
1342 /**
1343 * Reads the input stream and closes the stream at the end of processing (regardless if an exception was thrown)
1344 *
1345 * @param stream input stream
1346 * @return byte array of data in input stream
1347 * @throws IOException if any I/O error occurs
1348 */
1349 public static byte[] readBytesFromStream(InputStream stream) throws IOException {
1350 try {
1351 ByteArrayOutputStream bout = new ByteArrayOutputStream(stream.available());
1352 byte[] buffer = new byte[2048];
1353 boolean finished = false;
1354 do {
1355 int read = stream.read(buffer);
1356 if (read >= 0) {
1357 bout.write(buffer, 0, read);
1358 } else {
1359 finished = true;
1360 }
1361 } while (!finished);
1362 if (bout.size() == 0)
1363 return null;
1364 return bout.toByteArray();
1365 } finally {
1366 stream.close();
1367 }
1368 }
1369
1370 /**
1371 * Returns the initial capacity to pass to the HashMap / HashSet constructor
1372 * when it is initialized with a known number of entries.
1373 *
1374 * When a HashMap is filled with entries, the underlying array is copied over
1375 * to a larger one multiple times. To avoid this process when the number of
1376 * entries is known in advance, the initial capacity of the array can be
1377 * given to the HashMap constructor. This method returns a suitable value
1378 * that avoids rehashing but doesn't waste memory.
1379 * @param nEntries the number of entries expected
1380 * @param loadFactor the load factor
1381 * @return the initial capacity for the HashMap constructor
1382 */
1383 public static int hashMapInitialCapacity(int nEntries, float loadFactor) {
1384 return (int) Math.ceil(nEntries / loadFactor);
1385 }
1386
1387 /**
1388 * Returns the initial capacity to pass to the HashMap / HashSet constructor
1389 * when it is initialized with a known number of entries.
1390 *
1391 * When a HashMap is filled with entries, the underlying array is copied over
1392 * to a larger one multiple times. To avoid this process when the number of
1393 * entries is known in advance, the initial capacity of the array can be
1394 * given to the HashMap constructor. This method returns a suitable value
1395 * that avoids rehashing but doesn't waste memory.
1396 *
1397 * Assumes default load factor (0.75).
1398 * @param nEntries the number of entries expected
1399 * @return the initial capacity for the HashMap constructor
1400 */
1401 public static int hashMapInitialCapacity(int nEntries) {
1402 return hashMapInitialCapacity(nEntries, 0.75f);
1403 }
1404
1405 /**
1406 * @param name to be set for the threads
1407 * @return Thread Factory returning named threads
1408 */
1409 public static ThreadFactory getNamedThreadFactory(final String name) {
1410 return new ThreadFactory() {
1411 @Override
1412 public Thread newThread(Runnable r) {
1413 Thread t = Executors.defaultThreadFactory().newThread(r);
1414 t.setName(name);
1415 return t;
1416 }
1417 };
1418 }
1419}
Note: See TracBrowser for help on using the repository browser.