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

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

see #8902 - Small performance enhancements / coding style (patches by shinigami):

  • bytestohexstring.diff: byte[] to hex string change + small test
  • collfix.diff : problem in generic collection definition
  • styleiteration.diff: useless iteration to do end of list
  • environment.diff: Environment - merge chained ops (each created copy of env.) to one
  • Property svn:eol-style set to native
File size: 22.8 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 private static final char[] HEX_ARRAY = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
404
405 /**
406 * Converts a byte array to a string of hexadecimal characters.
407 * Preserves leading zeros, so the size of the output string is always twice
408 * the number of input bytes.
409 * @param bytes the byte array
410 * @return hexadecimal representation
411 */
412 public static String toHexString(byte[] bytes) {
413
414 if (bytes == null) {
415 return "";
416 }
417
418 final int len = bytes.length;
419 if (len == 0) {
420 return "";
421 }
422
423 char[] hexChars = new char[len * 2];
424 for (int i = 0, j = 0; i < len; i++) {
425 final int v = bytes[i];
426 hexChars[j++] = HEX_ARRAY[(v & 0xf0) >> 4];
427 hexChars[j++] = HEX_ARRAY[v & 0xf];
428 }
429 return new String(hexChars);
430 }
431
432 /**
433 * Topological sort.
434 *
435 * @param dependencies contains mappings (key -> value). In the final list of sorted objects, the key will come
436 * after the value. (In other words, the key depends on the value(s).)
437 * There must not be cyclic dependencies.
438 * @return the list of sorted objects
439 */
440 public static <T> List<T> topologicalSort(final MultiMap<T,T> dependencies) {
441 MultiMap<T,T> deps = new MultiMap<T,T>();
442 for (T key : dependencies.keySet()) {
443 deps.putVoid(key);
444 for (T val : dependencies.get(key)) {
445 deps.putVoid(val);
446 deps.put(key, val);
447 }
448 }
449
450 int size = deps.size();
451 List<T> sorted = new ArrayList<T>();
452 for (int i=0; i<size; ++i) {
453 T parentless = null;
454 for (T key : deps.keySet()) {
455 if (deps.get(key).isEmpty()) {
456 parentless = key;
457 break;
458 }
459 }
460 if (parentless == null) throw new RuntimeException();
461 sorted.add(parentless);
462 deps.remove(parentless);
463 for (T key : deps.keySet()) {
464 deps.remove(key, parentless);
465 }
466 }
467 if (sorted.size() != size) throw new RuntimeException();
468 return sorted;
469 }
470
471 /**
472 * Represents a function that can be applied to objects of {@code A} and
473 * returns objects of {@code B}.
474 * @param <A> class of input objects
475 * @param <B> class of transformed objects
476 */
477 public static interface Function<A, B> {
478
479 /**
480 * Applies the function on {@code x}.
481 * @param x an object of
482 * @return the transformed object
483 */
484 B apply(A x);
485 }
486
487 /**
488 * Transforms the collection {@code c} into an unmodifiable collection and
489 * applies the {@link Function} {@code f} on each element upon access.
490 * @param <A> class of input collection
491 * @param <B> class of transformed collection
492 * @param c a collection
493 * @param f a function that transforms objects of {@code A} to objects of {@code B}
494 * @return the transformed unmodifiable collection
495 */
496 public static <A, B> Collection<B> transform(final Collection<? extends A> c, final Function<A, B> f) {
497 return new AbstractCollection<B>() {
498
499 @Override
500 public int size() {
501 return c.size();
502 }
503
504 @Override
505 public Iterator<B> iterator() {
506 return new Iterator<B>() {
507
508 private Iterator<? extends A> it = c.iterator();
509
510 @Override
511 public boolean hasNext() {
512 return it.hasNext();
513 }
514
515 @Override
516 public B next() {
517 return f.apply(it.next());
518 }
519
520 @Override
521 public void remove() {
522 throw new UnsupportedOperationException();
523 }
524 };
525 }
526 };
527 }
528
529 /**
530 * Transforms the list {@code l} into an unmodifiable list and
531 * applies the {@link Function} {@code f} on each element upon access.
532 * @param <A> class of input collection
533 * @param <B> class of transformed collection
534 * @param l a collection
535 * @param f a function that transforms objects of {@code A} to objects of {@code B}
536 * @return the transformed unmodifiable list
537 */
538 public static <A, B> List<B> transform(final List<? extends A> l, final Function<A, B> f) {
539 return new AbstractList<B>() {
540
541
542 @Override
543 public int size() {
544 return l.size();
545 }
546
547 @Override
548 public B get(int index) {
549 return f.apply(l.get(index));
550 }
551
552
553 };
554 }
555
556 /**
557 * Convert Hex String to Color.
558 * @param s Must be of the form "#34a300" or "#3f2", otherwise throws Exception.
559 * Upper/lower case does not matter.
560 * @return The corresponding color.
561 */
562 static public Color hexToColor(String s) {
563 String clr = s.substring(1);
564 if (clr.length() == 3) {
565 clr = new String(new char[] {
566 clr.charAt(0), clr.charAt(0), clr.charAt(1), clr.charAt(1), clr.charAt(2), clr.charAt(2)
567 });
568 }
569 if (clr.length() != 6)
570 throw new IllegalArgumentException();
571 return new Color(Integer.parseInt(clr, 16));
572 }
573
574 /**
575 * Opens a HTTP connection to the given URL and sets the User-Agent property to JOSM's one.
576 * @param httpURL The HTTP url to open (must use http:// or https://)
577 * @return An open HTTP connection to the given URL
578 * @throws IOException if an I/O exception occurs.
579 * @since 5587
580 */
581 public static HttpURLConnection openHttpConnection(URL httpURL) throws IOException {
582 if (httpURL == null || !httpURL.getProtocol().matches("https?")) {
583 throw new IllegalArgumentException("Invalid HTTP url");
584 }
585 HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection();
586 connection.setRequestProperty("User-Agent", Version.getInstance().getFullAgentString());
587 connection.setUseCaches(false);
588 return connection;
589 }
590
591 /**
592 * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
593 * @param url The url to open
594 * @return An stream for the given URL
595 * @throws IOException if an I/O exception occurs.
596 * @since 5867
597 */
598 public static InputStream openURL(URL url) throws IOException {
599 return setupURLConnection(url.openConnection()).getInputStream();
600 }
601
602 /***
603 * Setups the given URL connection to match JOSM needs by setting its User-Agent and timeout properties.
604 * @param connection The connection to setup
605 * @return {@code connection}, with updated properties
606 * @since 5887
607 */
608 public static URLConnection setupURLConnection(URLConnection connection) {
609 if (connection != null) {
610 connection.setRequestProperty("User-Agent", Version.getInstance().getFullAgentString());
611 connection.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect",15)*1000);
612 connection.setReadTimeout(Main.pref.getInteger("socket.timeout.read",30)*1000);
613 }
614 return connection;
615 }
616
617 /**
618 * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
619 * @param url The url to open
620 * @return An buffered stream reader for the given URL (using UTF-8)
621 * @throws IOException if an I/O exception occurs.
622 * @since 5868
623 */
624 public static BufferedReader openURLReader(URL url) throws IOException {
625 return new BufferedReader(new InputStreamReader(openURL(url), "utf-8"));
626 }
627
628 /**
629 * Opens a HTTP connection to the given URL, sets the User-Agent property to JOSM's one and optionnaly disables Keep-Alive.
630 * @param httpURL The HTTP url to open (must use http:// or https://)
631 * @param keepAlive
632 * @return An open HTTP connection to the given URL
633 * @throws IOException if an I/O exception occurs.
634 * @since 5587
635 */
636 public static HttpURLConnection openHttpConnection(URL httpURL, boolean keepAlive) throws IOException {
637 HttpURLConnection connection = openHttpConnection(httpURL);
638 if (!keepAlive) {
639 connection.setRequestProperty("Connection", "close");
640 }
641 return connection;
642 }
643
644 /**
645 * An alternative to {@link String#trim()} to effectively remove all leading and trailing white characters, including Unicode ones.
646 * @see <a href="http://closingbraces.net/2008/11/11/javastringtrim/">Java’s String.trim has a strange idea of whitespace</a>
647 * @see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4080617">JDK bug 4080617</a>
648 * @param str The string to strip
649 * @return <code>str</code>, without leading and trailing characters, according to
650 * {@link Character#isWhitespace(char)} and {@link Character#isSpaceChar(char)}.
651 * @since 5772
652 */
653 public static String strip(String str) {
654 if (str == null || str.isEmpty()) {
655 return str;
656 }
657 int start = 0, end = str.length();
658 boolean leadingWhite = true;
659 while (leadingWhite && start < end) {
660 char c = str.charAt(start);
661 // '\u200B' (ZERO WIDTH SPACE character) needs to be handled manually because of change in Unicode 6.0 (Java 7, see #8918)
662 leadingWhite = (Character.isWhitespace(c) || Character.isSpaceChar(c) || c == '\u200B');
663 if (leadingWhite) {
664 start++;
665 }
666 }
667 boolean trailingWhite = true;
668 while (trailingWhite && end > start+1) {
669 char c = str.charAt(end-1);
670 trailingWhite = (Character.isWhitespace(c) || Character.isSpaceChar(c) || c == '\u200B');
671 if (trailingWhite) {
672 end--;
673 }
674 }
675 return str.substring(start, end);
676 }
677
678 /**
679 * Runs an external command and returns the standard output.
680 *
681 * The program is expected to execute fast.
682 *
683 * @param command the command with arguments
684 * @return the output
685 * @throws IOException when there was an error, e.g. command does not exist
686 */
687 public static String execOutput(List<String> command) throws IOException {
688 Process p = new ProcessBuilder(command).start();
689 BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
690 StringBuilder all = null;
691 String line;
692 while ((line = input.readLine()) != null) {
693 if (all == null) {
694 all = new StringBuilder(line);
695 } else {
696 all.append("\n");
697 all.append(line);
698 }
699 }
700 Utils.close(input);
701 return all.toString();
702 }
703
704}
Note: See TracBrowser for help on using the repository browser.