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

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

fix #8904 - Disable Java HTTP caching, enabled by default with Java Web Start in 7u2 and later

  • Property svn:eol-style set to native
File size: 22.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 (File file : files) {
284 if (file.isDirectory()) {
285 deleteDirectory(file);
286 } else {
287 file.delete();
288 }
289 }
290 }
291 return( path.delete() );
292 }
293
294 /**
295 * <p>Utility method for closing a {@link Closeable} object.</p>
296 *
297 * @param c the closeable object. May be null.
298 */
299 public static void close(Closeable c) {
300 if (c == null) return;
301 try {
302 c.close();
303 } catch(IOException e) {
304 // ignore
305 }
306 }
307
308 /**
309 * <p>Utility method for closing a {@link ZipFile}.</p>
310 *
311 * @param zip the zip file. May be null.
312 */
313 public static void close(ZipFile zip) {
314 if (zip == null) return;
315 try {
316 zip.close();
317 } catch(IOException e) {
318 // ignore
319 }
320 }
321
322 private final static double EPSILION = 1e-11;
323
324 public static boolean equalsEpsilon(double a, double b) {
325 return Math.abs(a - b) <= EPSILION;
326 }
327
328 /**
329 * Copies the string {@code s} to system clipboard.
330 * @param s string to be copied to clipboard.
331 * @return true if succeeded, false otherwise.
332 */
333 public static boolean copyToClipboard(String s) {
334 try {
335 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(s), new ClipboardOwner() {
336
337 @Override
338 public void lostOwnership(Clipboard clpbrd, Transferable t) {
339 }
340 });
341 return true;
342 } catch (IllegalStateException ex) {
343 ex.printStackTrace();
344 return false;
345 }
346 }
347
348 /**
349 * Extracts clipboard content as string.
350 * @return string clipboard contents if available, {@code null} otherwise.
351 */
352 public static String getClipboardContent() {
353 Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
354 Transferable t = null;
355 for (int tries = 0; t == null && tries < 10; tries++) {
356 try {
357 t = clipboard.getContents(null);
358 } catch (IllegalStateException e) {
359 // Clipboard currently unavailable. On some platforms, the system clipboard is unavailable while it is accessed by another application.
360 try {
361 Thread.sleep(1);
362 } catch (InterruptedException ex) {
363 }
364 }
365 }
366 try {
367 if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
368 String text = (String) t.getTransferData(DataFlavor.stringFlavor);
369 return text;
370 }
371 } catch (UnsupportedFlavorException ex) {
372 ex.printStackTrace();
373 return null;
374 } catch (IOException ex) {
375 ex.printStackTrace();
376 return null;
377 }
378 return null;
379 }
380
381 /**
382 * Calculate MD5 hash of a string and output in hexadecimal format.
383 * @param data arbitrary String
384 * @return MD5 hash of data, string of length 32 with characters in range [0-9a-f]
385 */
386 public static String md5Hex(String data) {
387 byte[] byteData = null;
388 try {
389 byteData = data.getBytes("UTF-8");
390 } catch (UnsupportedEncodingException e) {
391 throw new RuntimeException();
392 }
393 MessageDigest md = null;
394 try {
395 md = MessageDigest.getInstance("MD5");
396 } catch (NoSuchAlgorithmException e) {
397 throw new RuntimeException();
398 }
399 byte[] byteDigest = md.digest(byteData);
400 return toHexString(byteDigest);
401 }
402
403 /**
404 * Converts a byte array to a string of hexadecimal characters.
405 * Preserves leading zeros, so the size of the output string is always twice
406 * the number of input bytes.
407 * @param bytes the byte array
408 * @return hexadecimal representation
409 */
410 public static String toHexString(byte[] bytes) {
411 char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
412 char[] hexChars = new char[bytes.length * 2];
413 for (int j=0; j<bytes.length; j++) {
414 int v = bytes[j] & 0xFF;
415 hexChars[j*2] = hexArray[v/16];
416 hexChars[j*2 + 1] = hexArray[v%16];
417 }
418 return new String(hexChars);
419 }
420
421 /**
422 * Topological sort.
423 *
424 * @param dependencies contains mappings (key -> value). In the final list of sorted objects, the key will come
425 * after the value. (In other words, the key depends on the value(s).)
426 * There must not be cyclic dependencies.
427 * @return the list of sorted objects
428 */
429 public static <T> List<T> topologicalSort(final MultiMap<T,T> dependencies) {
430 MultiMap<T,T> deps = new MultiMap<T,T>();
431 for (T key : dependencies.keySet()) {
432 deps.putVoid(key);
433 for (T val : dependencies.get(key)) {
434 deps.putVoid(val);
435 deps.put(key, val);
436 }
437 }
438
439 int size = deps.size();
440 List<T> sorted = new ArrayList<T>();
441 for (int i=0; i<size; ++i) {
442 T parentless = null;
443 for (T key : deps.keySet()) {
444 if (deps.get(key).isEmpty()) {
445 parentless = key;
446 break;
447 }
448 }
449 if (parentless == null) throw new RuntimeException();
450 sorted.add(parentless);
451 deps.remove(parentless);
452 for (T key : deps.keySet()) {
453 deps.remove(key, parentless);
454 }
455 }
456 if (sorted.size() != size) throw new RuntimeException();
457 return sorted;
458 }
459
460 /**
461 * Represents a function that can be applied to objects of {@code A} and
462 * returns objects of {@code B}.
463 * @param <A> class of input objects
464 * @param <B> class of transformed objects
465 */
466 public static interface Function<A, B> {
467
468 /**
469 * Applies the function on {@code x}.
470 * @param x an object of
471 * @return the transformed object
472 */
473 B apply(A x);
474 }
475
476 /**
477 * Transforms the collection {@code c} into an unmodifiable collection and
478 * applies the {@link Function} {@code f} on each element upon access.
479 * @param <A> class of input collection
480 * @param <B> class of transformed collection
481 * @param c a collection
482 * @param f a function that transforms objects of {@code A} to objects of {@code B}
483 * @return the transformed unmodifiable collection
484 */
485 public static <A, B> Collection<B> transform(final Collection<? extends A> c, final Function<A, B> f) {
486 return new AbstractCollection<B>() {
487
488 @Override
489 public int size() {
490 return c.size();
491 }
492
493 @Override
494 public Iterator<B> iterator() {
495 return new Iterator<B>() {
496
497 private Iterator<? extends A> it = c.iterator();
498
499 @Override
500 public boolean hasNext() {
501 return it.hasNext();
502 }
503
504 @Override
505 public B next() {
506 return f.apply(it.next());
507 }
508
509 @Override
510 public void remove() {
511 throw new UnsupportedOperationException();
512 }
513 };
514 }
515 };
516 }
517
518 /**
519 * Transforms the list {@code l} into an unmodifiable list and
520 * applies the {@link Function} {@code f} on each element upon access.
521 * @param <A> class of input collection
522 * @param <B> class of transformed collection
523 * @param l a collection
524 * @param f a function that transforms objects of {@code A} to objects of {@code B}
525 * @return the transformed unmodifiable list
526 */
527 public static <A, B> List<B> transform(final List<? extends A> l, final Function<A, B> f) {
528 return new AbstractList<B>() {
529
530
531 @Override
532 public int size() {
533 return l.size();
534 }
535
536 @Override
537 public B get(int index) {
538 return f.apply(l.get(index));
539 }
540
541
542 };
543 }
544
545 /**
546 * Convert Hex String to Color.
547 * @param s Must be of the form "#34a300" or "#3f2", otherwise throws Exception.
548 * Upper/lower case does not matter.
549 * @return The corresponding color.
550 */
551 static public Color hexToColor(String s) {
552 String clr = s.substring(1);
553 if (clr.length() == 3) {
554 clr = new String(new char[] {
555 clr.charAt(0), clr.charAt(0), clr.charAt(1), clr.charAt(1), clr.charAt(2), clr.charAt(2)
556 });
557 }
558 if (clr.length() != 6)
559 throw new IllegalArgumentException();
560 return new Color(Integer.parseInt(clr, 16));
561 }
562
563 /**
564 * Opens a HTTP connection to the given URL and sets the User-Agent property to JOSM's one.
565 * @param httpURL The HTTP url to open (must use http:// or https://)
566 * @return An open HTTP connection to the given URL
567 * @throws IOException if an I/O exception occurs.
568 * @since 5587
569 */
570 public static HttpURLConnection openHttpConnection(URL httpURL) throws IOException {
571 if (httpURL == null || !httpURL.getProtocol().matches("https?")) {
572 throw new IllegalArgumentException("Invalid HTTP url");
573 }
574 HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection();
575 connection.setRequestProperty("User-Agent", Version.getInstance().getFullAgentString());
576 connection.setUseCaches(false);
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 // '\u200B' (ZERO WIDTH SPACE character) needs to be handled manually because of change in Unicode 6.0 (Java 7, see #8918)
651 leadingWhite = (Character.isWhitespace(c) || Character.isSpaceChar(c) || c == '\u200B');
652 if (leadingWhite) {
653 start++;
654 }
655 }
656 boolean trailingWhite = true;
657 while (trailingWhite && end > start+1) {
658 char c = str.charAt(end-1);
659 trailingWhite = (Character.isWhitespace(c) || Character.isSpaceChar(c) || c == '\u200B');
660 if (trailingWhite) {
661 end--;
662 }
663 }
664 return str.substring(start, end);
665 }
666
667 /**
668 * Runs an external command and returns the standard output.
669 *
670 * The program is expected to execute fast.
671 *
672 * @param command the command with arguments
673 * @return the output
674 * @throws IOException when there was an error, e.g. command does not exist
675 */
676 public static String execOutput(List<String> command) throws IOException {
677 Process p = new ProcessBuilder(command).start();
678 BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
679 StringBuilder all = null;
680 String line;
681 while ((line = input.readLine()) != null) {
682 if (all == null) {
683 all = new StringBuilder(line);
684 } else {
685 all.append("\n");
686 all.append(line);
687 }
688 }
689 Utils.close(input);
690 return all.toString();
691 }
692
693}
Note: See TracBrowser for help on using the repository browser.