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

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

see #8606 - Fix user-agent used with JEditorPage.setPage() or JEditorPane(URL) + fix version number from previous commit

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