1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.tools;
|
---|
3 |
|
---|
4 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
5 | import static org.openstreetmap.josm.tools.I18n.trn;
|
---|
6 |
|
---|
7 | import java.awt.Color;
|
---|
8 | import java.awt.Toolkit;
|
---|
9 | import java.awt.datatransfer.Clipboard;
|
---|
10 | import java.awt.datatransfer.ClipboardOwner;
|
---|
11 | import java.awt.datatransfer.DataFlavor;
|
---|
12 | import java.awt.datatransfer.StringSelection;
|
---|
13 | import java.awt.datatransfer.Transferable;
|
---|
14 | import java.awt.datatransfer.UnsupportedFlavorException;
|
---|
15 | import java.io.BufferedInputStream;
|
---|
16 | import java.io.BufferedReader;
|
---|
17 | import java.io.Closeable;
|
---|
18 | import java.io.File;
|
---|
19 | import java.io.FileInputStream;
|
---|
20 | import java.io.FileOutputStream;
|
---|
21 | import java.io.IOException;
|
---|
22 | import java.io.InputStream;
|
---|
23 | import java.io.InputStreamReader;
|
---|
24 | import java.io.OutputStream;
|
---|
25 | import java.net.HttpURLConnection;
|
---|
26 | import java.net.MalformedURLException;
|
---|
27 | import java.net.URL;
|
---|
28 | import java.net.URLConnection;
|
---|
29 | import java.nio.channels.FileChannel;
|
---|
30 | import java.nio.charset.Charset;
|
---|
31 | import java.security.MessageDigest;
|
---|
32 | import java.security.NoSuchAlgorithmException;
|
---|
33 | import java.text.MessageFormat;
|
---|
34 | import java.util.AbstractCollection;
|
---|
35 | import java.util.AbstractList;
|
---|
36 | import java.util.ArrayList;
|
---|
37 | import java.util.Arrays;
|
---|
38 | import java.util.Collection;
|
---|
39 | import java.util.Collections;
|
---|
40 | import java.util.Iterator;
|
---|
41 | import java.util.List;
|
---|
42 | import java.util.regex.Matcher;
|
---|
43 | import java.util.zip.GZIPInputStream;
|
---|
44 | import java.util.zip.ZipFile;
|
---|
45 |
|
---|
46 | import org.apache.tools.bzip2.CBZip2InputStream;
|
---|
47 | import org.openstreetmap.josm.Main;
|
---|
48 | import org.openstreetmap.josm.data.Version;
|
---|
49 | import org.openstreetmap.josm.io.FileImporter;
|
---|
50 |
|
---|
51 | /**
|
---|
52 | * Basic utils, that can be useful in different parts of the program.
|
---|
53 | */
|
---|
54 | public final class Utils {
|
---|
55 |
|
---|
56 | private Utils() {
|
---|
57 | // Hide default constructor for utils classes
|
---|
58 | }
|
---|
59 |
|
---|
60 | /**
|
---|
61 | * UTF-8 (UCS Transformation Format—8-bit).
|
---|
62 | *
|
---|
63 | * <p>Every implementation of the Java platform is required to support UTF-8 (see {@link Charset}).</p>
|
---|
64 | */
|
---|
65 | public static final Charset UTF_8 = Charset.forName("UTF-8");
|
---|
66 |
|
---|
67 | public static <T> boolean exists(Iterable<? extends T> collection, Predicate<? super T> predicate) {
|
---|
68 | for (T item : collection) {
|
---|
69 | if (predicate.evaluate(item))
|
---|
70 | return true;
|
---|
71 | }
|
---|
72 | return false;
|
---|
73 | }
|
---|
74 |
|
---|
75 | public static <T> boolean exists(Iterable<T> collection, Class<? extends T> klass) {
|
---|
76 | for (Object item : collection) {
|
---|
77 | if (klass.isInstance(item))
|
---|
78 | return true;
|
---|
79 | }
|
---|
80 | return false;
|
---|
81 | }
|
---|
82 |
|
---|
83 | public static <T> T find(Iterable<? extends T> collection, Predicate<? super T> predicate) {
|
---|
84 | for (T item : collection) {
|
---|
85 | if (predicate.evaluate(item))
|
---|
86 | return item;
|
---|
87 | }
|
---|
88 | return null;
|
---|
89 | }
|
---|
90 |
|
---|
91 | @SuppressWarnings("unchecked")
|
---|
92 | public static <T> T find(Iterable<? super T> collection, Class<? extends T> klass) {
|
---|
93 | for (Object item : collection) {
|
---|
94 | if (klass.isInstance(item))
|
---|
95 | return (T) item;
|
---|
96 | }
|
---|
97 | return null;
|
---|
98 | }
|
---|
99 |
|
---|
100 | public static <T> Collection<T> filter(Collection<? extends T> collection, Predicate<? super T> predicate) {
|
---|
101 | return new FilteredCollection<T>(collection, predicate);
|
---|
102 | }
|
---|
103 |
|
---|
104 | /**
|
---|
105 | * Returns the first element from {@code items} which is non-null, or null if all elements are null.
|
---|
106 | */
|
---|
107 | public static <T> T firstNonNull(T... items) {
|
---|
108 | for (T i : items) {
|
---|
109 | if (i != null) {
|
---|
110 | return i;
|
---|
111 | }
|
---|
112 | }
|
---|
113 | return null;
|
---|
114 | }
|
---|
115 |
|
---|
116 | /**
|
---|
117 | * Filter a collection by (sub)class.
|
---|
118 | * This is an efficient read-only implementation.
|
---|
119 | */
|
---|
120 | public static <S, T extends S> SubclassFilteredCollection<S, T> filteredCollection(Collection<S> collection, final Class<T> klass) {
|
---|
121 | return new SubclassFilteredCollection<S, T>(collection, new Predicate<S>() {
|
---|
122 | @Override
|
---|
123 | public boolean evaluate(S o) {
|
---|
124 | return klass.isInstance(o);
|
---|
125 | }
|
---|
126 | });
|
---|
127 | }
|
---|
128 |
|
---|
129 | public static <T> int indexOf(Iterable<? extends T> collection, Predicate<? super T> predicate) {
|
---|
130 | int i = 0;
|
---|
131 | for (T item : collection) {
|
---|
132 | if (predicate.evaluate(item))
|
---|
133 | return i;
|
---|
134 | i++;
|
---|
135 | }
|
---|
136 | return -1;
|
---|
137 | }
|
---|
138 |
|
---|
139 | /**
|
---|
140 | * Get minimum of 3 values
|
---|
141 | */
|
---|
142 | public static int min(int a, int b, int c) {
|
---|
143 | if (b < c) {
|
---|
144 | if (a < b)
|
---|
145 | return a;
|
---|
146 | return b;
|
---|
147 | } else {
|
---|
148 | if (a < c)
|
---|
149 | return a;
|
---|
150 | return c;
|
---|
151 | }
|
---|
152 | }
|
---|
153 |
|
---|
154 | public static int max(int a, int b, int c, int d) {
|
---|
155 | return Math.max(Math.max(a, b), Math.max(c, d));
|
---|
156 | }
|
---|
157 |
|
---|
158 | /**
|
---|
159 | * for convenience: test whether 2 objects are either both null or a.equals(b)
|
---|
160 | */
|
---|
161 | public static <T> boolean equal(T a, T b) {
|
---|
162 | if (a == b)
|
---|
163 | return true;
|
---|
164 | return (a != null && a.equals(b));
|
---|
165 | }
|
---|
166 |
|
---|
167 | public static void ensure(boolean condition, String message, Object...data) {
|
---|
168 | if (!condition)
|
---|
169 | throw new AssertionError(
|
---|
170 | MessageFormat.format(message,data)
|
---|
171 | );
|
---|
172 | }
|
---|
173 |
|
---|
174 | /**
|
---|
175 | * return the modulus in the range [0, n)
|
---|
176 | */
|
---|
177 | public static int mod(int a, int n) {
|
---|
178 | if (n <= 0)
|
---|
179 | throw new IllegalArgumentException();
|
---|
180 | int res = a % n;
|
---|
181 | if (res < 0) {
|
---|
182 | res += n;
|
---|
183 | }
|
---|
184 | return res;
|
---|
185 | }
|
---|
186 |
|
---|
187 | /**
|
---|
188 | * Joins a list of strings (or objects that can be converted to string via
|
---|
189 | * Object.toString()) into a single string with fields separated by sep.
|
---|
190 | * @param sep the separator
|
---|
191 | * @param values collection of objects, null is converted to the
|
---|
192 | * empty string
|
---|
193 | * @return null if values is null. The joined string otherwise.
|
---|
194 | */
|
---|
195 | public static String join(String sep, Collection<?> values) {
|
---|
196 | if (sep == null)
|
---|
197 | throw new IllegalArgumentException();
|
---|
198 | if (values == null)
|
---|
199 | return null;
|
---|
200 | if (values.isEmpty())
|
---|
201 | return "";
|
---|
202 | StringBuilder s = null;
|
---|
203 | for (Object a : values) {
|
---|
204 | if (a == null) {
|
---|
205 | a = "";
|
---|
206 | }
|
---|
207 | if (s != null) {
|
---|
208 | s.append(sep).append(a.toString());
|
---|
209 | } else {
|
---|
210 | s = new StringBuilder(a.toString());
|
---|
211 | }
|
---|
212 | }
|
---|
213 | return s.toString();
|
---|
214 | }
|
---|
215 |
|
---|
216 | /**
|
---|
217 | * Converts the given iterable collection as an unordered HTML list.
|
---|
218 | * @param values The iterable collection
|
---|
219 | * @return An unordered HTML list
|
---|
220 | */
|
---|
221 | public static String joinAsHtmlUnorderedList(Iterable<?> values) {
|
---|
222 | StringBuilder sb = new StringBuilder(1024);
|
---|
223 | sb.append("<ul>");
|
---|
224 | for (Object i : values) {
|
---|
225 | sb.append("<li>").append(i).append("</li>");
|
---|
226 | }
|
---|
227 | sb.append("</ul>");
|
---|
228 | return sb.toString();
|
---|
229 | }
|
---|
230 |
|
---|
231 | /**
|
---|
232 | * convert Color to String
|
---|
233 | * (Color.toString() omits alpha value)
|
---|
234 | */
|
---|
235 | public static String toString(Color c) {
|
---|
236 | if (c == null)
|
---|
237 | return "null";
|
---|
238 | if (c.getAlpha() == 255)
|
---|
239 | return String.format("#%06x", c.getRGB() & 0x00ffffff);
|
---|
240 | else
|
---|
241 | return String.format("#%06x(alpha=%d)", c.getRGB() & 0x00ffffff, c.getAlpha());
|
---|
242 | }
|
---|
243 |
|
---|
244 | /**
|
---|
245 | * convert float range 0 <= x <= 1 to integer range 0..255
|
---|
246 | * when dealing with colors and color alpha value
|
---|
247 | * @return null if val is null, the corresponding int if val is in the
|
---|
248 | * range 0...1. If val is outside that range, return 255
|
---|
249 | */
|
---|
250 | public static Integer color_float2int(Float val) {
|
---|
251 | if (val == null)
|
---|
252 | return null;
|
---|
253 | if (val < 0 || val > 1)
|
---|
254 | return 255;
|
---|
255 | return (int) (255f * val + 0.5f);
|
---|
256 | }
|
---|
257 |
|
---|
258 | /**
|
---|
259 | * convert back
|
---|
260 | */
|
---|
261 | public static Float color_int2float(Integer val) {
|
---|
262 | if (val == null)
|
---|
263 | return null;
|
---|
264 | if (val < 0 || val > 255)
|
---|
265 | return 1f;
|
---|
266 | return ((float) val) / 255f;
|
---|
267 | }
|
---|
268 |
|
---|
269 | public static Color complement(Color clr) {
|
---|
270 | return new Color(255 - clr.getRed(), 255 - clr.getGreen(), 255 - clr.getBlue(), clr.getAlpha());
|
---|
271 | }
|
---|
272 |
|
---|
273 | /**
|
---|
274 | * Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe.
|
---|
275 | * @param array The array to copy
|
---|
276 | * @return A copy of the original array, or {@code null} if {@code array} is null
|
---|
277 | * @since 6221
|
---|
278 | */
|
---|
279 | public static <T> T[] copyArray(T[] array) {
|
---|
280 | if (array != null) {
|
---|
281 | return Arrays.copyOf(array, array.length);
|
---|
282 | }
|
---|
283 | return null;
|
---|
284 | }
|
---|
285 |
|
---|
286 | /**
|
---|
287 | * Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe.
|
---|
288 | * @param array The array to copy
|
---|
289 | * @return A copy of the original array, or {@code null} if {@code array} is null
|
---|
290 | * @since 6222
|
---|
291 | */
|
---|
292 | public static char[] copyArray(char[] array) {
|
---|
293 | if (array != null) {
|
---|
294 | return Arrays.copyOf(array, array.length);
|
---|
295 | }
|
---|
296 | return null;
|
---|
297 | }
|
---|
298 |
|
---|
299 | /**
|
---|
300 | * Simple file copy function that will overwrite the target file.<br/>
|
---|
301 | * Taken from <a href="http://www.rgagnon.com/javadetails/java-0064.html">this article</a> (CC-NC-BY-SA)
|
---|
302 | * @param in The source file
|
---|
303 | * @param out The destination file
|
---|
304 | * @throws IOException If any I/O error occurs
|
---|
305 | */
|
---|
306 | public static void copyFile(File in, File out) throws IOException {
|
---|
307 | // TODO: remove this function when we move to Java 7 (use Files.copy instead)
|
---|
308 | FileInputStream inStream = null;
|
---|
309 | FileOutputStream outStream = null;
|
---|
310 | try {
|
---|
311 | inStream = new FileInputStream(in);
|
---|
312 | outStream = new FileOutputStream(out);
|
---|
313 | FileChannel inChannel = inStream.getChannel();
|
---|
314 | inChannel.transferTo(0, inChannel.size(), outStream.getChannel());
|
---|
315 | }
|
---|
316 | catch (IOException e) {
|
---|
317 | throw e;
|
---|
318 | }
|
---|
319 | finally {
|
---|
320 | close(outStream);
|
---|
321 | close(inStream);
|
---|
322 | }
|
---|
323 | }
|
---|
324 |
|
---|
325 | public static int copyStream(InputStream source, OutputStream destination) throws IOException {
|
---|
326 | int count = 0;
|
---|
327 | byte[] b = new byte[512];
|
---|
328 | int read;
|
---|
329 | while ((read = source.read(b)) != -1) {
|
---|
330 | count += read;
|
---|
331 | destination.write(b, 0, read);
|
---|
332 | }
|
---|
333 | return count;
|
---|
334 | }
|
---|
335 |
|
---|
336 | public static boolean deleteDirectory(File path) {
|
---|
337 | if( path.exists() ) {
|
---|
338 | File[] files = path.listFiles();
|
---|
339 | for (File file : files) {
|
---|
340 | if (file.isDirectory()) {
|
---|
341 | deleteDirectory(file);
|
---|
342 | } else {
|
---|
343 | file.delete();
|
---|
344 | }
|
---|
345 | }
|
---|
346 | }
|
---|
347 | return( path.delete() );
|
---|
348 | }
|
---|
349 |
|
---|
350 | /**
|
---|
351 | * <p>Utility method for closing a {@link Closeable} object.</p>
|
---|
352 | *
|
---|
353 | * @param c the closeable object. May be null.
|
---|
354 | */
|
---|
355 | public static void close(Closeable c) {
|
---|
356 | if (c == null) return;
|
---|
357 | try {
|
---|
358 | c.close();
|
---|
359 | } catch (IOException e) {
|
---|
360 | Main.warn(e);
|
---|
361 | }
|
---|
362 | }
|
---|
363 |
|
---|
364 | /**
|
---|
365 | * <p>Utility method for closing a {@link ZipFile}.</p>
|
---|
366 | *
|
---|
367 | * @param zip the zip file. May be null.
|
---|
368 | */
|
---|
369 | public static void close(ZipFile zip) {
|
---|
370 | if (zip == null) return;
|
---|
371 | try {
|
---|
372 | zip.close();
|
---|
373 | } catch (IOException e) {
|
---|
374 | Main.warn(e);
|
---|
375 | }
|
---|
376 | }
|
---|
377 |
|
---|
378 | /**
|
---|
379 | * Converts the given file to its URL.
|
---|
380 | * @param f The file to get URL from
|
---|
381 | * @return The URL of the given file, or {@code null} if not possible.
|
---|
382 | * @since 6615
|
---|
383 | */
|
---|
384 | public static URL fileToURL(File f) {
|
---|
385 | if (f != null) {
|
---|
386 | try {
|
---|
387 | return f.toURI().toURL();
|
---|
388 | } catch (MalformedURLException ex) {
|
---|
389 | Main.error("Unable to convert filename " + f.getAbsolutePath() + " to URL");
|
---|
390 | }
|
---|
391 | }
|
---|
392 | return null;
|
---|
393 | }
|
---|
394 |
|
---|
395 | private final static double EPSILON = 1e-11;
|
---|
396 |
|
---|
397 | /**
|
---|
398 | * Determines if the two given double values are equal (their delta being smaller than a fixed epsilon)
|
---|
399 | * @param a The first double value to compare
|
---|
400 | * @param b The second double value to compare
|
---|
401 | * @return {@code true} if {@code abs(a - b) <= 1e-11}, {@code false} otherwise
|
---|
402 | */
|
---|
403 | public static boolean equalsEpsilon(double a, double b) {
|
---|
404 | return Math.abs(a - b) <= EPSILON;
|
---|
405 | }
|
---|
406 |
|
---|
407 | /**
|
---|
408 | * Copies the string {@code s} to system clipboard.
|
---|
409 | * @param s string to be copied to clipboard.
|
---|
410 | * @return true if succeeded, false otherwise.
|
---|
411 | */
|
---|
412 | public static boolean copyToClipboard(String s) {
|
---|
413 | try {
|
---|
414 | Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(s), new ClipboardOwner() {
|
---|
415 |
|
---|
416 | @Override
|
---|
417 | public void lostOwnership(Clipboard clpbrd, Transferable t) {
|
---|
418 | }
|
---|
419 | });
|
---|
420 | return true;
|
---|
421 | } catch (IllegalStateException ex) {
|
---|
422 | Main.error(ex);
|
---|
423 | return false;
|
---|
424 | }
|
---|
425 | }
|
---|
426 |
|
---|
427 | /**
|
---|
428 | * Extracts clipboard content as string.
|
---|
429 | * @return string clipboard contents if available, {@code null} otherwise.
|
---|
430 | */
|
---|
431 | public static String getClipboardContent() {
|
---|
432 | Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
|
---|
433 | Transferable t = null;
|
---|
434 | for (int tries = 0; t == null && tries < 10; tries++) {
|
---|
435 | try {
|
---|
436 | t = clipboard.getContents(null);
|
---|
437 | } catch (IllegalStateException e) {
|
---|
438 | // Clipboard currently unavailable. On some platforms, the system clipboard is unavailable while it is accessed by another application.
|
---|
439 | try {
|
---|
440 | Thread.sleep(1);
|
---|
441 | } catch (InterruptedException ex) {
|
---|
442 | Main.warn("InterruptedException in "+Utils.class.getSimpleName()+" while getting clipboard content");
|
---|
443 | }
|
---|
444 | }
|
---|
445 | }
|
---|
446 | try {
|
---|
447 | if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
|
---|
448 | String text = (String) t.getTransferData(DataFlavor.stringFlavor);
|
---|
449 | return text;
|
---|
450 | }
|
---|
451 | } catch (UnsupportedFlavorException ex) {
|
---|
452 | Main.error(ex);
|
---|
453 | return null;
|
---|
454 | } catch (IOException ex) {
|
---|
455 | Main.error(ex);
|
---|
456 | return null;
|
---|
457 | }
|
---|
458 | return null;
|
---|
459 | }
|
---|
460 |
|
---|
461 | /**
|
---|
462 | * Calculate MD5 hash of a string and output in hexadecimal format.
|
---|
463 | * @param data arbitrary String
|
---|
464 | * @return MD5 hash of data, string of length 32 with characters in range [0-9a-f]
|
---|
465 | */
|
---|
466 | public static String md5Hex(String data) {
|
---|
467 | byte[] byteData = data.getBytes(UTF_8);
|
---|
468 | MessageDigest md = null;
|
---|
469 | try {
|
---|
470 | md = MessageDigest.getInstance("MD5");
|
---|
471 | } catch (NoSuchAlgorithmException e) {
|
---|
472 | throw new RuntimeException();
|
---|
473 | }
|
---|
474 | byte[] byteDigest = md.digest(byteData);
|
---|
475 | return toHexString(byteDigest);
|
---|
476 | }
|
---|
477 |
|
---|
478 | private static final char[] HEX_ARRAY = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
|
---|
479 |
|
---|
480 | /**
|
---|
481 | * Converts a byte array to a string of hexadecimal characters.
|
---|
482 | * Preserves leading zeros, so the size of the output string is always twice
|
---|
483 | * the number of input bytes.
|
---|
484 | * @param bytes the byte array
|
---|
485 | * @return hexadecimal representation
|
---|
486 | */
|
---|
487 | public static String toHexString(byte[] bytes) {
|
---|
488 |
|
---|
489 | if (bytes == null) {
|
---|
490 | return "";
|
---|
491 | }
|
---|
492 |
|
---|
493 | final int len = bytes.length;
|
---|
494 | if (len == 0) {
|
---|
495 | return "";
|
---|
496 | }
|
---|
497 |
|
---|
498 | char[] hexChars = new char[len * 2];
|
---|
499 | for (int i = 0, j = 0; i < len; i++) {
|
---|
500 | final int v = bytes[i];
|
---|
501 | hexChars[j++] = HEX_ARRAY[(v & 0xf0) >> 4];
|
---|
502 | hexChars[j++] = HEX_ARRAY[v & 0xf];
|
---|
503 | }
|
---|
504 | return new String(hexChars);
|
---|
505 | }
|
---|
506 |
|
---|
507 | /**
|
---|
508 | * Topological sort.
|
---|
509 | *
|
---|
510 | * @param dependencies contains mappings (key -> value). In the final list of sorted objects, the key will come
|
---|
511 | * after the value. (In other words, the key depends on the value(s).)
|
---|
512 | * There must not be cyclic dependencies.
|
---|
513 | * @return the list of sorted objects
|
---|
514 | */
|
---|
515 | public static <T> List<T> topologicalSort(final MultiMap<T,T> dependencies) {
|
---|
516 | MultiMap<T,T> deps = new MultiMap<T,T>();
|
---|
517 | for (T key : dependencies.keySet()) {
|
---|
518 | deps.putVoid(key);
|
---|
519 | for (T val : dependencies.get(key)) {
|
---|
520 | deps.putVoid(val);
|
---|
521 | deps.put(key, val);
|
---|
522 | }
|
---|
523 | }
|
---|
524 |
|
---|
525 | int size = deps.size();
|
---|
526 | List<T> sorted = new ArrayList<T>();
|
---|
527 | for (int i=0; i<size; ++i) {
|
---|
528 | T parentless = null;
|
---|
529 | for (T key : deps.keySet()) {
|
---|
530 | if (deps.get(key).isEmpty()) {
|
---|
531 | parentless = key;
|
---|
532 | break;
|
---|
533 | }
|
---|
534 | }
|
---|
535 | if (parentless == null) throw new RuntimeException();
|
---|
536 | sorted.add(parentless);
|
---|
537 | deps.remove(parentless);
|
---|
538 | for (T key : deps.keySet()) {
|
---|
539 | deps.remove(key, parentless);
|
---|
540 | }
|
---|
541 | }
|
---|
542 | if (sorted.size() != size) throw new RuntimeException();
|
---|
543 | return sorted;
|
---|
544 | }
|
---|
545 |
|
---|
546 | /**
|
---|
547 | * Represents a function that can be applied to objects of {@code A} and
|
---|
548 | * returns objects of {@code B}.
|
---|
549 | * @param <A> class of input objects
|
---|
550 | * @param <B> class of transformed objects
|
---|
551 | */
|
---|
552 | public static interface Function<A, B> {
|
---|
553 |
|
---|
554 | /**
|
---|
555 | * Applies the function on {@code x}.
|
---|
556 | * @param x an object of
|
---|
557 | * @return the transformed object
|
---|
558 | */
|
---|
559 | B apply(A x);
|
---|
560 | }
|
---|
561 |
|
---|
562 | /**
|
---|
563 | * Transforms the collection {@code c} into an unmodifiable collection and
|
---|
564 | * applies the {@link Function} {@code f} on each element upon access.
|
---|
565 | * @param <A> class of input collection
|
---|
566 | * @param <B> class of transformed collection
|
---|
567 | * @param c a collection
|
---|
568 | * @param f a function that transforms objects of {@code A} to objects of {@code B}
|
---|
569 | * @return the transformed unmodifiable collection
|
---|
570 | */
|
---|
571 | public static <A, B> Collection<B> transform(final Collection<? extends A> c, final Function<A, B> f) {
|
---|
572 | return new AbstractCollection<B>() {
|
---|
573 |
|
---|
574 | @Override
|
---|
575 | public int size() {
|
---|
576 | return c.size();
|
---|
577 | }
|
---|
578 |
|
---|
579 | @Override
|
---|
580 | public Iterator<B> iterator() {
|
---|
581 | return new Iterator<B>() {
|
---|
582 |
|
---|
583 | private Iterator<? extends A> it = c.iterator();
|
---|
584 |
|
---|
585 | @Override
|
---|
586 | public boolean hasNext() {
|
---|
587 | return it.hasNext();
|
---|
588 | }
|
---|
589 |
|
---|
590 | @Override
|
---|
591 | public B next() {
|
---|
592 | return f.apply(it.next());
|
---|
593 | }
|
---|
594 |
|
---|
595 | @Override
|
---|
596 | public void remove() {
|
---|
597 | throw new UnsupportedOperationException();
|
---|
598 | }
|
---|
599 | };
|
---|
600 | }
|
---|
601 | };
|
---|
602 | }
|
---|
603 |
|
---|
604 | /**
|
---|
605 | * Transforms the list {@code l} into an unmodifiable list and
|
---|
606 | * applies the {@link Function} {@code f} on each element upon access.
|
---|
607 | * @param <A> class of input collection
|
---|
608 | * @param <B> class of transformed collection
|
---|
609 | * @param l a collection
|
---|
610 | * @param f a function that transforms objects of {@code A} to objects of {@code B}
|
---|
611 | * @return the transformed unmodifiable list
|
---|
612 | */
|
---|
613 | public static <A, B> List<B> transform(final List<? extends A> l, final Function<A, B> f) {
|
---|
614 | return new AbstractList<B>() {
|
---|
615 |
|
---|
616 |
|
---|
617 | @Override
|
---|
618 | public int size() {
|
---|
619 | return l.size();
|
---|
620 | }
|
---|
621 |
|
---|
622 | @Override
|
---|
623 | public B get(int index) {
|
---|
624 | return f.apply(l.get(index));
|
---|
625 | }
|
---|
626 |
|
---|
627 |
|
---|
628 | };
|
---|
629 | }
|
---|
630 |
|
---|
631 | /**
|
---|
632 | * Convert Hex String to Color.
|
---|
633 | * @param s Must be of the form "#34a300" or "#3f2", otherwise throws Exception.
|
---|
634 | * Upper/lower case does not matter.
|
---|
635 | * @return The corresponding color.
|
---|
636 | */
|
---|
637 | static public Color hexToColor(String s) {
|
---|
638 | String clr = s.substring(1);
|
---|
639 | if (clr.length() == 3) {
|
---|
640 | clr = new String(new char[] {
|
---|
641 | clr.charAt(0), clr.charAt(0), clr.charAt(1), clr.charAt(1), clr.charAt(2), clr.charAt(2)
|
---|
642 | });
|
---|
643 | }
|
---|
644 | if (clr.length() != 6)
|
---|
645 | throw new IllegalArgumentException();
|
---|
646 | return new Color(Integer.parseInt(clr, 16));
|
---|
647 | }
|
---|
648 |
|
---|
649 | /**
|
---|
650 | * Opens a HTTP connection to the given URL and sets the User-Agent property to JOSM's one.
|
---|
651 | * @param httpURL The HTTP url to open (must use http:// or https://)
|
---|
652 | * @return An open HTTP connection to the given URL
|
---|
653 | * @throws IOException if an I/O exception occurs.
|
---|
654 | * @since 5587
|
---|
655 | */
|
---|
656 | public static HttpURLConnection openHttpConnection(URL httpURL) throws IOException {
|
---|
657 | if (httpURL == null || !httpURL.getProtocol().matches("https?")) {
|
---|
658 | throw new IllegalArgumentException("Invalid HTTP url");
|
---|
659 | }
|
---|
660 | HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection();
|
---|
661 | connection.setRequestProperty("User-Agent", Version.getInstance().getFullAgentString());
|
---|
662 | connection.setUseCaches(false);
|
---|
663 | return connection;
|
---|
664 | }
|
---|
665 |
|
---|
666 | /**
|
---|
667 | * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
|
---|
668 | * @param url The url to open
|
---|
669 | * @return An stream for the given URL
|
---|
670 | * @throws IOException if an I/O exception occurs.
|
---|
671 | * @since 5867
|
---|
672 | */
|
---|
673 | public static InputStream openURL(URL url) throws IOException {
|
---|
674 | return openURLAndDecompress(url, false);
|
---|
675 | }
|
---|
676 |
|
---|
677 | /**
|
---|
678 | * Opens a connection to the given URL, sets the User-Agent property to JOSM's one, and decompresses stream if necessary.
|
---|
679 | * @param url The url to open
|
---|
680 | * @param decompress whether to wrap steam in a {@link GZIPInputStream} or {@link CBZip2InputStream}
|
---|
681 | * if the {@code Content-Type} header is set accordingly.
|
---|
682 | * @return An stream for the given URL
|
---|
683 | * @throws IOException if an I/O exception occurs.
|
---|
684 | * @since 6421
|
---|
685 | */
|
---|
686 | public static InputStream openURLAndDecompress(final URL url, final boolean decompress) throws IOException {
|
---|
687 | final URLConnection connection = setupURLConnection(url.openConnection());
|
---|
688 | if (decompress && "application/x-gzip".equals(connection.getHeaderField("Content-Type"))) {
|
---|
689 | return new GZIPInputStream(connection.getInputStream());
|
---|
690 | } else if (decompress && "application/x-bzip2".equals(connection.getHeaderField("Content-Type"))) {
|
---|
691 | return FileImporter.getBZip2InputStream(new BufferedInputStream(connection.getInputStream()));
|
---|
692 | } else {
|
---|
693 | return connection.getInputStream();
|
---|
694 | }
|
---|
695 | }
|
---|
696 |
|
---|
697 | /***
|
---|
698 | * Setups the given URL connection to match JOSM needs by setting its User-Agent and timeout properties.
|
---|
699 | * @param connection The connection to setup
|
---|
700 | * @return {@code connection}, with updated properties
|
---|
701 | * @since 5887
|
---|
702 | */
|
---|
703 | public static URLConnection setupURLConnection(URLConnection connection) {
|
---|
704 | if (connection != null) {
|
---|
705 | connection.setRequestProperty("User-Agent", Version.getInstance().getFullAgentString());
|
---|
706 | connection.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect",15)*1000);
|
---|
707 | connection.setReadTimeout(Main.pref.getInteger("socket.timeout.read",30)*1000);
|
---|
708 | }
|
---|
709 | return connection;
|
---|
710 | }
|
---|
711 |
|
---|
712 | /**
|
---|
713 | * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
|
---|
714 | * @param url The url to open
|
---|
715 | * @return An buffered stream reader for the given URL (using UTF-8)
|
---|
716 | * @throws IOException if an I/O exception occurs.
|
---|
717 | * @since 5868
|
---|
718 | */
|
---|
719 | public static BufferedReader openURLReader(URL url) throws IOException {
|
---|
720 | return openURLReaderAndDecompress(url, false);
|
---|
721 | }
|
---|
722 |
|
---|
723 | /**
|
---|
724 | * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
|
---|
725 | * @param url The url to open
|
---|
726 | * @param decompress whether to wrap steam in a {@link GZIPInputStream} or {@link CBZip2InputStream}
|
---|
727 | * if the {@code Content-Type} header is set accordingly.
|
---|
728 | * @return An buffered stream reader for the given URL (using UTF-8)
|
---|
729 | * @throws IOException if an I/O exception occurs.
|
---|
730 | * @since 6421
|
---|
731 | */
|
---|
732 | public static BufferedReader openURLReaderAndDecompress(final URL url, final boolean decompress) throws IOException {
|
---|
733 | return new BufferedReader(new InputStreamReader(openURLAndDecompress(url, decompress), UTF_8));
|
---|
734 | }
|
---|
735 |
|
---|
736 | /**
|
---|
737 | * Opens a HTTP connection to the given URL, sets the User-Agent property to JOSM's one and optionnaly disables Keep-Alive.
|
---|
738 | * @param httpURL The HTTP url to open (must use http:// or https://)
|
---|
739 | * @param keepAlive whether not to set header {@code Connection=close}
|
---|
740 | * @return An open HTTP connection to the given URL
|
---|
741 | * @throws IOException if an I/O exception occurs.
|
---|
742 | * @since 5587
|
---|
743 | */
|
---|
744 | public static HttpURLConnection openHttpConnection(URL httpURL, boolean keepAlive) throws IOException {
|
---|
745 | HttpURLConnection connection = openHttpConnection(httpURL);
|
---|
746 | if (!keepAlive) {
|
---|
747 | connection.setRequestProperty("Connection", "close");
|
---|
748 | }
|
---|
749 | return connection;
|
---|
750 | }
|
---|
751 |
|
---|
752 | /**
|
---|
753 | * An alternative to {@link String#trim()} to effectively remove all leading and trailing white characters, including Unicode ones.
|
---|
754 | * @see <a href="http://closingbraces.net/2008/11/11/javastringtrim/">Java’s String.trim has a strange idea of whitespace</a>
|
---|
755 | * @see <a href="https://bugs.openjdk.java.net/browse/JDK-4080617">JDK bug 4080617</a>
|
---|
756 | * @param str The string to strip
|
---|
757 | * @return <code>str</code>, without leading and trailing characters, according to
|
---|
758 | * {@link Character#isWhitespace(char)} and {@link Character#isSpaceChar(char)}.
|
---|
759 | * @since 5772
|
---|
760 | */
|
---|
761 | public static String strip(String str) {
|
---|
762 | if (str == null || str.isEmpty()) {
|
---|
763 | return str;
|
---|
764 | }
|
---|
765 | int start = 0, end = str.length();
|
---|
766 | boolean leadingWhite = true;
|
---|
767 | while (leadingWhite && start < end) {
|
---|
768 | char c = str.charAt(start);
|
---|
769 | // '\u200B' (ZERO WIDTH SPACE character) needs to be handled manually because of change in Unicode 6.0 (Java 7, see #8918)
|
---|
770 | // same for '\uFEFF' (ZERO WIDTH NO-BREAK SPACE)
|
---|
771 | leadingWhite = (Character.isWhitespace(c) || Character.isSpaceChar(c) || c == '\u200B' || c == '\uFEFF');
|
---|
772 | if (leadingWhite) {
|
---|
773 | start++;
|
---|
774 | }
|
---|
775 | }
|
---|
776 | boolean trailingWhite = true;
|
---|
777 | while (trailingWhite && end > start+1) {
|
---|
778 | char c = str.charAt(end-1);
|
---|
779 | trailingWhite = (Character.isWhitespace(c) || Character.isSpaceChar(c) || c == '\u200B' || c == '\uFEFF');
|
---|
780 | if (trailingWhite) {
|
---|
781 | end--;
|
---|
782 | }
|
---|
783 | }
|
---|
784 | return str.substring(start, end);
|
---|
785 | }
|
---|
786 |
|
---|
787 | /**
|
---|
788 | * Runs an external command and returns the standard output.
|
---|
789 | *
|
---|
790 | * The program is expected to execute fast.
|
---|
791 | *
|
---|
792 | * @param command the command with arguments
|
---|
793 | * @return the output
|
---|
794 | * @throws IOException when there was an error, e.g. command does not exist
|
---|
795 | */
|
---|
796 | public static String execOutput(List<String> command) throws IOException {
|
---|
797 | Process p = new ProcessBuilder(command).start();
|
---|
798 | BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
|
---|
799 | StringBuilder all = null;
|
---|
800 | String line;
|
---|
801 | while ((line = input.readLine()) != null) {
|
---|
802 | if (all == null) {
|
---|
803 | all = new StringBuilder(line);
|
---|
804 | } else {
|
---|
805 | all.append("\n");
|
---|
806 | all.append(line);
|
---|
807 | }
|
---|
808 | }
|
---|
809 | Utils.close(input);
|
---|
810 | return all.toString();
|
---|
811 | }
|
---|
812 |
|
---|
813 | /**
|
---|
814 | * Returns the JOSM temp directory.
|
---|
815 | * @return The JOSM temp directory ({@code <java.io.tmpdir>/JOSM}), or {@code null} if {@code java.io.tmpdir} is not defined
|
---|
816 | * @since 6245
|
---|
817 | */
|
---|
818 | public static File getJosmTempDir() {
|
---|
819 | String tmpDir = System.getProperty("java.io.tmpdir");
|
---|
820 | if (tmpDir == null) {
|
---|
821 | return null;
|
---|
822 | }
|
---|
823 | File josmTmpDir = new File(tmpDir, "JOSM");
|
---|
824 | if (!josmTmpDir.exists()) {
|
---|
825 | if (!josmTmpDir.mkdirs()) {
|
---|
826 | Main.warn("Unable to create temp directory "+josmTmpDir);
|
---|
827 | }
|
---|
828 | }
|
---|
829 | return josmTmpDir;
|
---|
830 | }
|
---|
831 |
|
---|
832 | /**
|
---|
833 | * Returns a simple human readable (hours, minutes, seconds) string for a given duration in milliseconds.
|
---|
834 | * @param elapsedTime The duration in milliseconds
|
---|
835 | * @return A human readable string for the given duration
|
---|
836 | * @throws IllegalArgumentException if elapsedTime is < 0
|
---|
837 | * @since 6354
|
---|
838 | */
|
---|
839 | public static String getDurationString(long elapsedTime) throws IllegalArgumentException {
|
---|
840 | final int MILLIS_OF_SECOND = 1000;
|
---|
841 | final int MILLIS_OF_MINUTE = 60000;
|
---|
842 | final int MILLIS_OF_HOUR = 3600000;
|
---|
843 | final int MILLIS_OF_DAY = 86400000;
|
---|
844 | if (elapsedTime < 0) {
|
---|
845 | throw new IllegalArgumentException("elapsedTime must be > 0");
|
---|
846 | }
|
---|
847 | // Is it less than 1 second ?
|
---|
848 | if (elapsedTime < MILLIS_OF_SECOND) {
|
---|
849 | return String.format("%d %s", elapsedTime, tr("ms"));
|
---|
850 | }
|
---|
851 | // Is it less than 1 minute ?
|
---|
852 | if (elapsedTime < MILLIS_OF_MINUTE) {
|
---|
853 | return String.format("%.1f %s", elapsedTime / (float) MILLIS_OF_SECOND, tr("s"));
|
---|
854 | }
|
---|
855 | // Is it less than 1 hour ?
|
---|
856 | if (elapsedTime < MILLIS_OF_HOUR) {
|
---|
857 | final long min = elapsedTime / MILLIS_OF_MINUTE;
|
---|
858 | return String.format("%d %s %d %s", min, tr("min"), (elapsedTime - min * MILLIS_OF_MINUTE) / MILLIS_OF_SECOND, tr("s"));
|
---|
859 | }
|
---|
860 | // Is it less than 1 day ?
|
---|
861 | if (elapsedTime < MILLIS_OF_DAY) {
|
---|
862 | final long hour = elapsedTime / MILLIS_OF_HOUR;
|
---|
863 | return String.format("%d %s %d %s", hour, tr("h"), (elapsedTime - hour * MILLIS_OF_HOUR) / MILLIS_OF_MINUTE, tr("min"));
|
---|
864 | }
|
---|
865 | long days = elapsedTime / MILLIS_OF_DAY;
|
---|
866 | return String.format("%d %s %d %s", days, trn("day", "days", days), (elapsedTime - days * MILLIS_OF_DAY) / MILLIS_OF_HOUR, tr("h"));
|
---|
867 | }
|
---|
868 |
|
---|
869 | /**
|
---|
870 | * Returns a human readable representation of a list of positions.
|
---|
871 | * <p/>
|
---|
872 | * For instance, {@code [1,5,2,6,7} yields "1-2,5-7
|
---|
873 | * @param positionList a list of positions
|
---|
874 | * @return a human readable representation
|
---|
875 | */
|
---|
876 | public static String getPositionListString(List<Integer> positionList) {
|
---|
877 | Collections.sort(positionList);
|
---|
878 | final StringBuilder sb = new StringBuilder(32);
|
---|
879 | sb.append(positionList.get(0));
|
---|
880 | int cnt = 0;
|
---|
881 | int last = positionList.get(0);
|
---|
882 | for (int i = 1; i < positionList.size(); ++i) {
|
---|
883 | int cur = positionList.get(i);
|
---|
884 | if (cur == last + 1) {
|
---|
885 | ++cnt;
|
---|
886 | } else if (cnt == 0) {
|
---|
887 | sb.append(",").append(cur);
|
---|
888 | } else {
|
---|
889 | sb.append("-").append(last);
|
---|
890 | sb.append(",").append(cur);
|
---|
891 | cnt = 0;
|
---|
892 | }
|
---|
893 | last = cur;
|
---|
894 | }
|
---|
895 | if (cnt >= 1) {
|
---|
896 | sb.append("-").append(last);
|
---|
897 | }
|
---|
898 | return sb.toString();
|
---|
899 | }
|
---|
900 |
|
---|
901 |
|
---|
902 | /**
|
---|
903 | * Returns a list of capture groups if {@link Matcher#matches()}, or {@code null}.
|
---|
904 | * The first element (index 0) is the complete match.
|
---|
905 | * Further elements correspond to the parts in parentheses of the regular expression.
|
---|
906 | * @param m the matcher
|
---|
907 | * @return a list of capture groups if {@link Matcher#matches()}, or {@code null}.
|
---|
908 | */
|
---|
909 | public static List<String> getMatches(final Matcher m) {
|
---|
910 | if (m.matches()) {
|
---|
911 | List<String> result = new ArrayList<String>(m.groupCount() + 1);
|
---|
912 | for (int i = 0; i <= m.groupCount(); i++) {
|
---|
913 | result.add(m.group(i));
|
---|
914 | }
|
---|
915 | return result;
|
---|
916 | } else {
|
---|
917 | return null;
|
---|
918 | }
|
---|
919 | }
|
---|
920 |
|
---|
921 | /**
|
---|
922 | * Cast an object savely.
|
---|
923 | * @param <T> the target type
|
---|
924 | * @param o the object to cast
|
---|
925 | * @param klass the target class (same as T)
|
---|
926 | * @return null if <code>o</code> is null or the type <code>o</code> is not
|
---|
927 | * a subclass of <code>klass</code>. The casted value otherwise.
|
---|
928 | */
|
---|
929 | @SuppressWarnings("unchecked")
|
---|
930 | public static <T> T cast(Object o, Class<T> klass) {
|
---|
931 | if (klass.isInstance(o)) {
|
---|
932 | return (T) o;
|
---|
933 | }
|
---|
934 | return null;
|
---|
935 | }
|
---|
936 |
|
---|
937 | /**
|
---|
938 | * Returns the root cause of a throwable object.
|
---|
939 | * @param t The object to get root cause for
|
---|
940 | * @return the root cause of {@code t}
|
---|
941 | * @since 6639
|
---|
942 | */
|
---|
943 | public static Throwable getRootCause(Throwable t) {
|
---|
944 | Throwable result = t;
|
---|
945 | if (result != null) {
|
---|
946 | Throwable cause = result.getCause();
|
---|
947 | while (cause != null && cause != result) {
|
---|
948 | result = cause;
|
---|
949 | cause = result.getCause();
|
---|
950 | }
|
---|
951 | }
|
---|
952 | return result;
|
---|
953 | }
|
---|
954 | }
|
---|