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

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

Make some defensive copies of user-supplied arrays, move QuadStateCheckBox to widgets package, javadoc

  • Property svn:eol-style set to native
File size: 23.3 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import java.awt.Color;
5import java.awt.Toolkit;
6import java.awt.datatransfer.Clipboard;
7import java.awt.datatransfer.ClipboardOwner;
8import java.awt.datatransfer.DataFlavor;
9import java.awt.datatransfer.StringSelection;
10import java.awt.datatransfer.Transferable;
11import java.awt.datatransfer.UnsupportedFlavorException;
12import java.io.BufferedReader;
13import java.io.Closeable;
14import java.io.File;
15import java.io.FileInputStream;
16import java.io.FileOutputStream;
17import java.io.IOException;
18import java.io.InputStream;
19import java.io.InputStreamReader;
20import java.io.OutputStream;
21import java.io.UnsupportedEncodingException;
22import java.net.HttpURLConnection;
23import java.net.URL;
24import java.net.URLConnection;
25import java.nio.channels.FileChannel;
26import java.security.MessageDigest;
27import java.security.NoSuchAlgorithmException;
28import java.text.MessageFormat;
29import java.util.AbstractCollection;
30import java.util.AbstractList;
31import java.util.ArrayList;
32import java.util.Arrays;
33import java.util.Collection;
34import java.util.Iterator;
35import java.util.List;
36import java.util.zip.ZipFile;
37
38import org.openstreetmap.josm.Main;
39import org.openstreetmap.josm.data.Version;
40
41/**
42 * Basic utils, that can be useful in different parts of the program.
43 */
44public class Utils {
45
46 public static <T> boolean exists(Iterable<? extends T> collection, Predicate<? super T> predicate) {
47 for (T item : collection) {
48 if (predicate.evaluate(item))
49 return true;
50 }
51 return false;
52 }
53
54 public static <T> boolean exists(Iterable<T> collection, Class<? extends T> klass) {
55 for (Object item : collection) {
56 if (klass.isInstance(item))
57 return true;
58 }
59 return false;
60 }
61
62 public static <T> T find(Iterable<? extends T> collection, Predicate<? super T> predicate) {
63 for (T item : collection) {
64 if (predicate.evaluate(item))
65 return item;
66 }
67 return null;
68 }
69
70 @SuppressWarnings("unchecked")
71 public static <T> T find(Iterable<? super T> collection, Class<? extends T> klass) {
72 for (Object item : collection) {
73 if (klass.isInstance(item))
74 return (T) item;
75 }
76 return null;
77 }
78
79 public static <T> Collection<T> filter(Collection<? extends T> collection, Predicate<? super T> predicate) {
80 return new FilteredCollection<T>(collection, predicate);
81 }
82
83 public static <T> T firstNonNull(T... items) {
84 for (T i : items) {
85 if (i != null) {
86 return i;
87 }
88 }
89 return null;
90 }
91
92 /**
93 * Filter a collection by (sub)class.
94 * This is an efficient read-only implementation.
95 */
96 public static <S, T extends S> SubclassFilteredCollection<S, T> filteredCollection(Collection<S> collection, final Class<T> klass) {
97 return new SubclassFilteredCollection<S, T>(collection, new Predicate<S>() {
98 @Override
99 public boolean evaluate(S o) {
100 return klass.isInstance(o);
101 }
102 });
103 }
104
105 public static <T> int indexOf(Iterable<? extends T> collection, Predicate<? super T> predicate) {
106 int i = 0;
107 for (T item : collection) {
108 if (predicate.evaluate(item))
109 return i;
110 i++;
111 }
112 return -1;
113 }
114
115 /**
116 * Get minimum of 3 values
117 */
118 public static int min(int a, int b, int c) {
119 if (b < c) {
120 if (a < b)
121 return a;
122 return b;
123 } else {
124 if (a < c)
125 return a;
126 return c;
127 }
128 }
129
130 public static int max(int a, int b, int c, int d) {
131 return Math.max(Math.max(a, b), Math.max(c, d));
132 }
133
134 /**
135 * for convenience: test whether 2 objects are either both null or a.equals(b)
136 */
137 public static <T> boolean equal(T a, T b) {
138 if (a == b)
139 return true;
140 return (a != null && a.equals(b));
141 }
142
143 public static void ensure(boolean condition, String message, Object...data) {
144 if (!condition)
145 throw new AssertionError(
146 MessageFormat.format(message,data)
147 );
148 }
149
150 /**
151 * return the modulus in the range [0, n)
152 */
153 public static int mod(int a, int n) {
154 if (n <= 0)
155 throw new IllegalArgumentException();
156 int res = a % n;
157 if (res < 0) {
158 res += n;
159 }
160 return res;
161 }
162
163 /**
164 * Joins a list of strings (or objects that can be converted to string via
165 * Object.toString()) into a single string with fields separated by sep.
166 * @param sep the separator
167 * @param values collection of objects, null is converted to the
168 * empty string
169 * @return null if values is null. The joined string otherwise.
170 */
171 public static String join(String sep, Collection<?> values) {
172 if (sep == null)
173 throw new IllegalArgumentException();
174 if (values == null)
175 return null;
176 if (values.isEmpty())
177 return "";
178 StringBuilder s = null;
179 for (Object a : values) {
180 if (a == null) {
181 a = "";
182 }
183 if (s != null) {
184 s.append(sep).append(a.toString());
185 } else {
186 s = new StringBuilder(a.toString());
187 }
188 }
189 return s.toString();
190 }
191
192 public static String joinAsHtmlUnorderedList(Collection<?> values) {
193 StringBuilder sb = new StringBuilder(1024);
194 sb.append("<ul>");
195 for (Object i : values) {
196 sb.append("<li>").append(i).append("</li>");
197 }
198 sb.append("</ul>");
199 return sb.toString();
200 }
201
202 /**
203 * convert Color to String
204 * (Color.toString() omits alpha value)
205 */
206 public static String toString(Color c) {
207 if (c == null)
208 return "null";
209 if (c.getAlpha() == 255)
210 return String.format("#%06x", c.getRGB() & 0x00ffffff);
211 else
212 return String.format("#%06x(alpha=%d)", c.getRGB() & 0x00ffffff, c.getAlpha());
213 }
214
215 /**
216 * convert float range 0 <= x <= 1 to integer range 0..255
217 * when dealing with colors and color alpha value
218 * @return null if val is null, the corresponding int if val is in the
219 * range 0...1. If val is outside that range, return 255
220 */
221 public static Integer color_float2int(Float val) {
222 if (val == null)
223 return null;
224 if (val < 0 || val > 1)
225 return 255;
226 return (int) (255f * val + 0.5f);
227 }
228
229 /**
230 * convert back
231 */
232 public static Float color_int2float(Integer val) {
233 if (val == null)
234 return null;
235 if (val < 0 || val > 255)
236 return 1f;
237 return ((float) val) / 255f;
238 }
239
240 public static Color complement(Color clr) {
241 return new Color(255 - clr.getRed(), 255 - clr.getGreen(), 255 - clr.getBlue(), clr.getAlpha());
242 }
243
244 /**
245 * Copies the given array. Unlike {@link Arrays#copyOf}, this method is null-safe.
246 * @param array The array to copy
247 * @return A copy of the original array, or {@code null} if {@code array} is null
248 * @since 6221
249 */
250 public static <T> T[] copyArray(T[] array) {
251 if (array != null) {
252 return Arrays.copyOf(array, array.length);
253 }
254 return null;
255 }
256
257 /**
258 * Simple file copy function that will overwrite the target file.<br/>
259 * Taken from <a href="http://www.rgagnon.com/javadetails/java-0064.html">this article</a> (CC-NC-BY-SA)
260 * @param in The source file
261 * @param out The destination file
262 * @throws IOException If any I/O error occurs
263 */
264 public static void copyFile(File in, File out) throws IOException {
265 // TODO: remove this function when we move to Java 7 (use Files.copy instead)
266 FileInputStream inStream = null;
267 FileOutputStream outStream = null;
268 try {
269 inStream = new FileInputStream(in);
270 outStream = new FileOutputStream(out);
271 FileChannel inChannel = inStream.getChannel();
272 inChannel.transferTo(0, inChannel.size(), outStream.getChannel());
273 }
274 catch (IOException e) {
275 throw e;
276 }
277 finally {
278 close(outStream);
279 close(inStream);
280 }
281 }
282
283 public static int copyStream(InputStream source, OutputStream destination) throws IOException {
284 int count = 0;
285 byte[] b = new byte[512];
286 int read;
287 while ((read = source.read(b)) != -1) {
288 count += read;
289 destination.write(b, 0, read);
290 }
291 return count;
292 }
293
294 public static boolean deleteDirectory(File path) {
295 if( path.exists() ) {
296 File[] files = path.listFiles();
297 for (File file : files) {
298 if (file.isDirectory()) {
299 deleteDirectory(file);
300 } else {
301 file.delete();
302 }
303 }
304 }
305 return( path.delete() );
306 }
307
308 /**
309 * <p>Utility method for closing a {@link Closeable} object.</p>
310 *
311 * @param c the closeable object. May be null.
312 */
313 public static void close(Closeable c) {
314 if (c == null) return;
315 try {
316 c.close();
317 } catch(IOException e) {
318 // ignore
319 }
320 }
321
322 /**
323 * <p>Utility method for closing a {@link ZipFile}.</p>
324 *
325 * @param zip the zip file. May be null.
326 */
327 public static void close(ZipFile zip) {
328 if (zip == null) return;
329 try {
330 zip.close();
331 } catch(IOException e) {
332 // ignore
333 }
334 }
335
336 private final static double EPSILION = 1e-11;
337
338 public static boolean equalsEpsilon(double a, double b) {
339 return Math.abs(a - b) <= EPSILION;
340 }
341
342 /**
343 * Copies the string {@code s} to system clipboard.
344 * @param s string to be copied to clipboard.
345 * @return true if succeeded, false otherwise.
346 */
347 public static boolean copyToClipboard(String s) {
348 try {
349 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(s), new ClipboardOwner() {
350
351 @Override
352 public void lostOwnership(Clipboard clpbrd, Transferable t) {
353 }
354 });
355 return true;
356 } catch (IllegalStateException ex) {
357 ex.printStackTrace();
358 return false;
359 }
360 }
361
362 /**
363 * Extracts clipboard content as string.
364 * @return string clipboard contents if available, {@code null} otherwise.
365 */
366 public static String getClipboardContent() {
367 Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
368 Transferable t = null;
369 for (int tries = 0; t == null && tries < 10; tries++) {
370 try {
371 t = clipboard.getContents(null);
372 } catch (IllegalStateException e) {
373 // Clipboard currently unavailable. On some platforms, the system clipboard is unavailable while it is accessed by another application.
374 try {
375 Thread.sleep(1);
376 } catch (InterruptedException ex) {
377 }
378 }
379 }
380 try {
381 if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
382 String text = (String) t.getTransferData(DataFlavor.stringFlavor);
383 return text;
384 }
385 } catch (UnsupportedFlavorException ex) {
386 ex.printStackTrace();
387 return null;
388 } catch (IOException ex) {
389 ex.printStackTrace();
390 return null;
391 }
392 return null;
393 }
394
395 /**
396 * Calculate MD5 hash of a string and output in hexadecimal format.
397 * @param data arbitrary String
398 * @return MD5 hash of data, string of length 32 with characters in range [0-9a-f]
399 */
400 public static String md5Hex(String data) {
401 byte[] byteData = null;
402 try {
403 byteData = data.getBytes("UTF-8");
404 } catch (UnsupportedEncodingException e) {
405 throw new RuntimeException();
406 }
407 MessageDigest md = null;
408 try {
409 md = MessageDigest.getInstance("MD5");
410 } catch (NoSuchAlgorithmException e) {
411 throw new RuntimeException();
412 }
413 byte[] byteDigest = md.digest(byteData);
414 return toHexString(byteDigest);
415 }
416
417 private static final char[] HEX_ARRAY = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
418
419 /**
420 * Converts a byte array to a string of hexadecimal characters.
421 * Preserves leading zeros, so the size of the output string is always twice
422 * the number of input bytes.
423 * @param bytes the byte array
424 * @return hexadecimal representation
425 */
426 public static String toHexString(byte[] bytes) {
427
428 if (bytes == null) {
429 return "";
430 }
431
432 final int len = bytes.length;
433 if (len == 0) {
434 return "";
435 }
436
437 char[] hexChars = new char[len * 2];
438 for (int i = 0, j = 0; i < len; i++) {
439 final int v = bytes[i];
440 hexChars[j++] = HEX_ARRAY[(v & 0xf0) >> 4];
441 hexChars[j++] = HEX_ARRAY[v & 0xf];
442 }
443 return new String(hexChars);
444 }
445
446 /**
447 * Topological sort.
448 *
449 * @param dependencies contains mappings (key -> value). In the final list of sorted objects, the key will come
450 * after the value. (In other words, the key depends on the value(s).)
451 * There must not be cyclic dependencies.
452 * @return the list of sorted objects
453 */
454 public static <T> List<T> topologicalSort(final MultiMap<T,T> dependencies) {
455 MultiMap<T,T> deps = new MultiMap<T,T>();
456 for (T key : dependencies.keySet()) {
457 deps.putVoid(key);
458 for (T val : dependencies.get(key)) {
459 deps.putVoid(val);
460 deps.put(key, val);
461 }
462 }
463
464 int size = deps.size();
465 List<T> sorted = new ArrayList<T>();
466 for (int i=0; i<size; ++i) {
467 T parentless = null;
468 for (T key : deps.keySet()) {
469 if (deps.get(key).isEmpty()) {
470 parentless = key;
471 break;
472 }
473 }
474 if (parentless == null) throw new RuntimeException();
475 sorted.add(parentless);
476 deps.remove(parentless);
477 for (T key : deps.keySet()) {
478 deps.remove(key, parentless);
479 }
480 }
481 if (sorted.size() != size) throw new RuntimeException();
482 return sorted;
483 }
484
485 /**
486 * Represents a function that can be applied to objects of {@code A} and
487 * returns objects of {@code B}.
488 * @param <A> class of input objects
489 * @param <B> class of transformed objects
490 */
491 public static interface Function<A, B> {
492
493 /**
494 * Applies the function on {@code x}.
495 * @param x an object of
496 * @return the transformed object
497 */
498 B apply(A x);
499 }
500
501 /**
502 * Transforms the collection {@code c} into an unmodifiable collection and
503 * applies the {@link Function} {@code f} on each element upon access.
504 * @param <A> class of input collection
505 * @param <B> class of transformed collection
506 * @param c a collection
507 * @param f a function that transforms objects of {@code A} to objects of {@code B}
508 * @return the transformed unmodifiable collection
509 */
510 public static <A, B> Collection<B> transform(final Collection<? extends A> c, final Function<A, B> f) {
511 return new AbstractCollection<B>() {
512
513 @Override
514 public int size() {
515 return c.size();
516 }
517
518 @Override
519 public Iterator<B> iterator() {
520 return new Iterator<B>() {
521
522 private Iterator<? extends A> it = c.iterator();
523
524 @Override
525 public boolean hasNext() {
526 return it.hasNext();
527 }
528
529 @Override
530 public B next() {
531 return f.apply(it.next());
532 }
533
534 @Override
535 public void remove() {
536 throw new UnsupportedOperationException();
537 }
538 };
539 }
540 };
541 }
542
543 /**
544 * Transforms the list {@code l} into an unmodifiable list and
545 * applies the {@link Function} {@code f} on each element upon access.
546 * @param <A> class of input collection
547 * @param <B> class of transformed collection
548 * @param l a collection
549 * @param f a function that transforms objects of {@code A} to objects of {@code B}
550 * @return the transformed unmodifiable list
551 */
552 public static <A, B> List<B> transform(final List<? extends A> l, final Function<A, B> f) {
553 return new AbstractList<B>() {
554
555
556 @Override
557 public int size() {
558 return l.size();
559 }
560
561 @Override
562 public B get(int index) {
563 return f.apply(l.get(index));
564 }
565
566
567 };
568 }
569
570 /**
571 * Convert Hex String to Color.
572 * @param s Must be of the form "#34a300" or "#3f2", otherwise throws Exception.
573 * Upper/lower case does not matter.
574 * @return The corresponding color.
575 */
576 static public Color hexToColor(String s) {
577 String clr = s.substring(1);
578 if (clr.length() == 3) {
579 clr = new String(new char[] {
580 clr.charAt(0), clr.charAt(0), clr.charAt(1), clr.charAt(1), clr.charAt(2), clr.charAt(2)
581 });
582 }
583 if (clr.length() != 6)
584 throw new IllegalArgumentException();
585 return new Color(Integer.parseInt(clr, 16));
586 }
587
588 /**
589 * Opens a HTTP connection to the given URL and sets the User-Agent property to JOSM's one.
590 * @param httpURL The HTTP url to open (must use http:// or https://)
591 * @return An open HTTP connection to the given URL
592 * @throws IOException if an I/O exception occurs.
593 * @since 5587
594 */
595 public static HttpURLConnection openHttpConnection(URL httpURL) throws IOException {
596 if (httpURL == null || !httpURL.getProtocol().matches("https?")) {
597 throw new IllegalArgumentException("Invalid HTTP url");
598 }
599 HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection();
600 connection.setRequestProperty("User-Agent", Version.getInstance().getFullAgentString());
601 connection.setUseCaches(false);
602 return connection;
603 }
604
605 /**
606 * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
607 * @param url The url to open
608 * @return An stream for the given URL
609 * @throws IOException if an I/O exception occurs.
610 * @since 5867
611 */
612 public static InputStream openURL(URL url) throws IOException {
613 return setupURLConnection(url.openConnection()).getInputStream();
614 }
615
616 /***
617 * Setups the given URL connection to match JOSM needs by setting its User-Agent and timeout properties.
618 * @param connection The connection to setup
619 * @return {@code connection}, with updated properties
620 * @since 5887
621 */
622 public static URLConnection setupURLConnection(URLConnection connection) {
623 if (connection != null) {
624 connection.setRequestProperty("User-Agent", Version.getInstance().getFullAgentString());
625 connection.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect",15)*1000);
626 connection.setReadTimeout(Main.pref.getInteger("socket.timeout.read",30)*1000);
627 }
628 return connection;
629 }
630
631 /**
632 * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
633 * @param url The url to open
634 * @return An buffered stream reader for the given URL (using UTF-8)
635 * @throws IOException if an I/O exception occurs.
636 * @since 5868
637 */
638 public static BufferedReader openURLReader(URL url) throws IOException {
639 return new BufferedReader(new InputStreamReader(openURL(url), "utf-8"));
640 }
641
642 /**
643 * Opens a HTTP connection to the given URL, sets the User-Agent property to JOSM's one and optionnaly disables Keep-Alive.
644 * @param httpURL The HTTP url to open (must use http:// or https://)
645 * @param keepAlive
646 * @return An open HTTP connection to the given URL
647 * @throws IOException if an I/O exception occurs.
648 * @since 5587
649 */
650 public static HttpURLConnection openHttpConnection(URL httpURL, boolean keepAlive) throws IOException {
651 HttpURLConnection connection = openHttpConnection(httpURL);
652 if (!keepAlive) {
653 connection.setRequestProperty("Connection", "close");
654 }
655 return connection;
656 }
657
658 /**
659 * An alternative to {@link String#trim()} to effectively remove all leading and trailing white characters, including Unicode ones.
660 * @see <a href="http://closingbraces.net/2008/11/11/javastringtrim/">Java’s String.trim has a strange idea of whitespace</a>
661 * @see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4080617">JDK bug 4080617</a>
662 * @param str The string to strip
663 * @return <code>str</code>, without leading and trailing characters, according to
664 * {@link Character#isWhitespace(char)} and {@link Character#isSpaceChar(char)}.
665 * @since 5772
666 */
667 public static String strip(String str) {
668 if (str == null || str.isEmpty()) {
669 return str;
670 }
671 int start = 0, end = str.length();
672 boolean leadingWhite = true;
673 while (leadingWhite && start < end) {
674 char c = str.charAt(start);
675 // '\u200B' (ZERO WIDTH SPACE character) needs to be handled manually because of change in Unicode 6.0 (Java 7, see #8918)
676 leadingWhite = (Character.isWhitespace(c) || Character.isSpaceChar(c) || c == '\u200B');
677 if (leadingWhite) {
678 start++;
679 }
680 }
681 boolean trailingWhite = true;
682 while (trailingWhite && end > start+1) {
683 char c = str.charAt(end-1);
684 trailingWhite = (Character.isWhitespace(c) || Character.isSpaceChar(c) || c == '\u200B');
685 if (trailingWhite) {
686 end--;
687 }
688 }
689 return str.substring(start, end);
690 }
691
692 /**
693 * Runs an external command and returns the standard output.
694 *
695 * The program is expected to execute fast.
696 *
697 * @param command the command with arguments
698 * @return the output
699 * @throws IOException when there was an error, e.g. command does not exist
700 */
701 public static String execOutput(List<String> command) throws IOException {
702 Process p = new ProcessBuilder(command).start();
703 BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
704 StringBuilder all = null;
705 String line;
706 while ((line = input.readLine()) != null) {
707 if (all == null) {
708 all = new StringBuilder(line);
709 } else {
710 all.append("\n");
711 all.append(line);
712 }
713 }
714 Utils.close(input);
715 return all.toString();
716 }
717
718}
Note: See TracBrowser for help on using the repository browser.