Changeset 19048 in josm for trunk/src/org/openstreetmap/josm/tools/Utils.java
- Timestamp:
- 2024-04-19T16:21:11+02:00 (8 months ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/src/org/openstreetmap/josm/tools/Utils.java
r18811 r19048 30 30 import java.nio.file.StandardCopyOption; 31 31 import java.nio.file.attribute.BasicFileAttributes; 32 import java.nio.file.attribute.FileTime;33 32 import java.security.MessageDigest; 34 33 import java.security.NoSuchAlgorithmException; … … 153 152 */ 154 153 public static <T> int indexOf(Iterable<? extends T> collection, Predicate<? super T> predicate) { 155 inti = 0;156 for ( Titem : collection) {154 var i = 0; 155 for (var item : collection) { 157 156 if (predicate.test(item)) 158 157 return i; … … 186 185 if (n <= 0) 187 186 throw new IllegalArgumentException("n must be <= 0 but is " + n); 188 intres = a % n;187 var res = a % n; 189 188 if (res < 0) { 190 189 res += n; … … 304 303 Logging.warn("Unable to create directory "+out.getPath()); 305 304 } 306 File[]files = in.listFiles();305 var files = in.listFiles(); 307 306 if (files != null) { 308 for ( Filef : files) {309 Filetarget = new File(out, f.getName());307 for (var f : files) { 308 var target = new File(out, f.getName()); 310 309 if (f.isDirectory()) { 311 310 copyDirectory(f, target); … … 325 324 public static boolean deleteDirectory(File path) { 326 325 if (path.exists()) { 327 File[]files = path.listFiles();326 var files = path.listFiles(); 328 327 if (files != null) { 329 for ( Filefile : files) {328 for (var file : files) { 330 329 if (file.isDirectory()) { 331 330 deleteDirectory(file); … … 372 371 */ 373 372 public static boolean deleteFile(File file, String warnMsg) { 374 booleanresult = file.delete();373 var result = file.delete(); 375 374 if (!result) { 376 375 Logging.warn(tr(warnMsg, file.getPath())); … … 398 397 */ 399 398 public static boolean mkDirs(File dir, String warnMsg) { 400 booleanresult = dir.mkdirs();399 var result = dir.mkdirs(); 401 400 if (!result) { 402 401 Logging.warn(tr(warnMsg, dir.getPath())); … … 498 497 throw new JosmRuntimeException(e); 499 498 } 500 byte[]byteData = data.getBytes(StandardCharsets.UTF_8);501 byte[]byteDigest = md.digest(byteData);499 var byteData = data.getBytes(StandardCharsets.UTF_8); 500 var byteDigest = md.digest(byteData); 502 501 return toHexString(byteDigest); 503 502 } … … 518 517 } 519 518 520 final intlen = bytes.length;519 final var len = bytes.length; 521 520 if (len == 0) { 522 521 return ""; 523 522 } 524 523 525 char[]hexChars = new char[len * 2];526 intj = 0;524 var hexChars = new char[len * 2]; 525 var j = 0; 527 526 for (final int v : bytes) { 528 527 hexChars[j++] = HEX_ARRAY[(v & 0xf0) >> 4]; … … 542 541 */ 543 542 public static <T> List<T> topologicalSort(final MultiMap<T, T> dependencies) { 544 MultiMap<T, T> deps = new MultiMap<>();545 for ( Tkey : dependencies.keySet()) {543 var deps = new MultiMap<T, T>(); 544 for (var key : dependencies.keySet()) { 546 545 deps.putVoid(key); 547 for ( Tval : dependencies.get(key)) {546 for (var val : dependencies.get(key)) { 548 547 deps.putVoid(val); 549 548 deps.put(key, val); … … 551 550 } 552 551 553 intsize = deps.size();552 var size = deps.size(); 554 553 List<T> sorted = new ArrayList<>(); 555 for ( inti = 0; i < size; ++i) {556 Tparentless = deps.keySet().stream()554 for (var i = 0; i < size; ++i) { 555 var parentless = deps.keySet().stream() 557 556 .filter(key -> deps.get(key).isEmpty()) 558 557 .findFirst().orElse(null); … … 560 559 sorted.add(parentless); 561 560 deps.remove(parentless); 562 for ( Tkey : deps.keySet()) {561 for (var key : deps.keySet()) { 563 562 deps.remove(key, parentless); 564 563 } … … 680 679 return Collections.emptyMap(); 681 680 } else if (map.size() == 1) { 682 final Map.Entry<K, V>entry = map.entrySet().iterator().next();681 final var entry = map.entrySet().iterator().next(); 683 682 return Collections.singletonMap(entry.getKey(), entry.getValue()); 684 683 } else if (mapOfEntries != null) { … … 796 795 } 797 796 798 intstart = 0;799 intend = str.length();800 booleanleadingSkipChar = true;797 var start = 0; 798 var end = str.length(); 799 var leadingSkipChar = true; 801 800 while (leadingSkipChar && start < end) { 802 801 leadingSkipChar = isStrippedChar(str.charAt(start), skipChars); … … 805 804 } 806 805 } 807 booleantrailingSkipChar = true;806 var trailingSkipChar = true; 808 807 while (trailingSkipChar && end > start) { 809 808 trailingSkipChar = isStrippedChar(str.charAt(end - 1), skipChars); … … 867 866 Logging.debug(String.join(" ", command)); 868 867 } 869 Pathout = Files.createTempFile("josm_exec_" + command.get(0) + "_", ".txt");868 var out = Files.createTempFile("josm_exec_" + command.get(0) + "_", ".txt"); 870 869 try { 871 Processp = new ProcessBuilder(command).redirectErrorStream(true).redirectOutput(out.toFile()).start();870 var p = new ProcessBuilder(command).redirectErrorStream(true).redirectOutput(out.toFile()).start(); 872 871 if (!p.waitFor(timeout, unit) || p.exitValue() != 0) { 873 872 throw new ExecutionException(command.toString(), null); … … 889 888 */ 890 889 public static File getJosmTempDir() { 891 StringtmpDir = getSystemProperty("java.io.tmpdir");890 var tmpDir = getSystemProperty("java.io.tmpdir"); 892 891 if (tmpDir == null) { 893 892 return null; 894 893 } 895 FilejosmTmpDir = new File(tmpDir, "JOSM");894 final var josmTmpDir = new File(tmpDir, "JOSM"); 896 895 if (!josmTmpDir.exists() && !josmTmpDir.mkdirs()) { 897 896 Logging.warn("Unable to create temp directory " + josmTmpDir); … … 921 920 // Is it less than 1 hour ? 922 921 if (elapsedTime < MILLIS_OF_HOUR) { 923 final longmin = elapsedTime / MILLIS_OF_MINUTE;922 final var min = elapsedTime / MILLIS_OF_MINUTE; 924 923 return String.format("%d %s %d %s", min, tr("min"), (elapsedTime - min * MILLIS_OF_MINUTE) / MILLIS_OF_SECOND, tr("s")); 925 924 } 926 925 // Is it less than 1 day ? 927 926 if (elapsedTime < MILLIS_OF_DAY) { 928 final longhour = elapsedTime / MILLIS_OF_HOUR;927 final var hour = elapsedTime / MILLIS_OF_HOUR; 929 928 return String.format("%d %s %d %s", hour, tr("h"), (elapsedTime - hour * MILLIS_OF_HOUR) / MILLIS_OF_MINUTE, tr("min")); 930 929 } 931 longdays = elapsedTime / MILLIS_OF_DAY;930 var days = elapsedTime / MILLIS_OF_DAY; 932 931 return String.format("%d %s %d %s", days, trn("day", "days", days), (elapsedTime - days * MILLIS_OF_DAY) / MILLIS_OF_HOUR, tr("h")); 933 932 } … … 944 943 throw new IllegalArgumentException("bytes must be >= 0"); 945 944 } 946 intunitIndex = 0;945 var unitIndex = 0; 947 946 double value = bytes; 948 947 while (value >= 1024 && unitIndex < SIZE_UNITS.length) { … … 968 967 public static String getPositionListString(List<Integer> positionList) { 969 968 Collections.sort(positionList); 970 final StringBuilder sb = new StringBuilder(32);969 final var sb = new StringBuilder(32); 971 970 sb.append(positionList.get(0)); 972 intcnt = 0;971 var cnt = 0; 973 972 int last = positionList.get(0); 974 for ( inti = 1; i < positionList.size(); ++i) {973 for (var i = 1; i < positionList.size(); ++i) { 975 974 int cur = positionList.get(i); 976 975 if (cur == last + 1) { … … 1031 1030 */ 1032 1031 public static Throwable getRootCause(Throwable t) { 1033 Throwableresult = t;1032 var result = t; 1034 1033 if (result != null) { 1035 Throwablecause = result.getCause();1034 var cause = result.getCause(); 1036 1035 while (cause != null && !cause.equals(result)) { 1037 1036 result = cause; … … 1051 1050 */ 1052 1051 public static <T> T[] addInArrayCopy(T[] array, T item) { 1053 T[]biggerCopy = Arrays.copyOf(array, array.length + 1);1052 var biggerCopy = Arrays.copyOf(array, array.length + 1); 1054 1053 biggerCopy[array.length] = item; 1055 1054 return biggerCopy; … … 1064 1063 */ 1065 1064 public static String shortenString(String s, int maxLength) { 1066 final Stringellipses = "...";1065 final var ellipses = "..."; 1067 1066 CheckParameterUtil.ensureThat(maxLength >= ellipses.length(), "maxLength is shorter than " + ellipses.length()); 1068 1067 if (s != null && s.length() > maxLength) { … … 1102 1101 if (elements.size() > maxElements) { 1103 1102 final Collection<T> r = new ArrayList<>(maxElements); 1104 final Iterator<T>it = elements.iterator();1103 final var it = elements.iterator(); 1105 1104 while (r.size() < maxElements - 1) { 1106 1105 r.add(it.next()); … … 1127 1126 return url; 1128 1127 1129 Stringquery = url.substring(url.indexOf('?') + 1);1130 1131 StringBuilder sb = new StringBuilder(url.substring(0, url.indexOf('?') + 1));1132 1133 for ( inti = 0; i < query.length(); i++) {1134 Stringc = query.substring(i, i + 1);1128 final var query = url.substring(url.indexOf('?') + 1); 1129 1130 final var sb = new StringBuilder(url.substring(0, url.indexOf('?') + 1)); 1131 1132 for (var i = 0; i < query.length(); i++) { 1133 final var c = query.substring(i, i + 1); 1135 1134 if (URL_CHARS.contains(c)) { 1136 1135 sb.append(c); … … 1153 1152 */ 1154 1153 public static String encodeUrl(String s) { 1155 final Stringenc = StandardCharsets.UTF_8.name();1154 final var enc = StandardCharsets.UTF_8.name(); 1156 1155 try { 1157 1156 return URLEncoder.encode(s, enc); … … 1173 1172 */ 1174 1173 public static String decodeUrl(String s) { 1175 final Stringenc = StandardCharsets.UTF_8.name();1174 final var enc = StandardCharsets.UTF_8.name(); 1176 1175 try { 1177 1176 return URLDecoder.decode(s, enc); … … 1221 1220 @Override 1222 1221 public Thread newThread(final Runnable runnable) { 1223 final Threadthread = new Thread(runnable, String.format(Locale.ENGLISH, nameFormat, count.getAndIncrement()));1222 final var thread = new Thread(runnable, String.format(Locale.ENGLISH, nameFormat, count.getAndIncrement())); 1224 1223 thread.setPriority(threadPriority); 1225 1224 return thread; … … 1299 1298 public static boolean isSimilar(String string1, String string2) { 1300 1299 // check plain strings 1301 intdistance = getLevenshteinDistance(string1, string2);1300 var distance = getLevenshteinDistance(string1, string2); 1302 1301 1303 1302 // check if only the case differs, so we don't consider large distance as different strings … … 1340 1339 } 1341 1340 1342 for ( doublelength : values) {1341 for (var length : values) { 1343 1342 standardDeviation += Math.pow(length - mean, 2); 1344 1343 } … … 1361 1360 } 1362 1361 List<int[]> groups = new ArrayList<>(); 1363 int[] current ={Integer.MIN_VALUE, Integer.MIN_VALUE};1362 var current = new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE}; 1364 1363 groups.add(current); 1365 for ( introw : integers) {1364 for (var row : integers) { 1366 1365 if (current[0] == Integer.MIN_VALUE) { 1367 1366 current[0] = row; … … 1398 1397 @SuppressWarnings("ThreadPriorityCheck") 1399 1398 public static ForkJoinPool newForkJoinPool(String pref, final String nameFormat, final int threadPriority) { 1400 intnoThreads = Config.getPref().getInt(pref, Runtime.getRuntime().availableProcessors());1399 final var noThreads = Config.getPref().getInt(pref, Runtime.getRuntime().availableProcessors()); 1401 1400 return new ForkJoinPool(noThreads, new ForkJoinPool.ForkJoinWorkerThreadFactory() { 1402 1401 final AtomicLong count = new AtomicLong(0); … … 1468 1467 if (value != null) { 1469 1468 try { 1470 Stringold = System.setProperty(key, value);1469 var old = System.setProperty(key, value); 1471 1470 if (Logging.isDebugEnabled() && !value.equals(old)) { 1472 1471 if (!key.toLowerCase(Locale.ENGLISH).contains("password")) { … … 1494 1493 */ 1495 1494 public static boolean hasExtension(String filename, String... extensions) { 1496 Stringname = filename.toLowerCase(Locale.ENGLISH).replace("?format=raw", "");1495 var name = filename.toLowerCase(Locale.ENGLISH).replace("?format=raw", ""); 1497 1496 return Arrays.stream(extensions) 1498 1497 .anyMatch(ext -> name.endsWith('.' + ext.toLowerCase(Locale.ENGLISH))); … … 1523 1522 return new byte[0]; 1524 1523 } 1525 try ( ByteArrayOutputStreambout = new ByteArrayOutputStream(stream.available())) {1526 byte[]buffer = new byte[8192];1527 booleanfinished = false;1524 try (stream; var bout = new ByteArrayOutputStream(stream.available())) { 1525 final var buffer = new byte[8192]; 1526 var finished = false; 1528 1527 do { 1529 intread = stream.read(buffer);1528 var read = stream.read(buffer); 1530 1529 if (read >= 0) { 1531 1530 bout.write(buffer, 0, read); … … 1537 1536 return new byte[0]; 1538 1537 return bout.toByteArray(); 1539 } finally {1540 stream.close();1541 1538 } 1542 1539 } … … 1603 1600 */ 1604 1601 public static List<GlyphVector> getGlyphVectorsBidi(String string, Font font, FontRenderContext frc) { 1605 List<GlyphVector> gvs = new ArrayList<>();1606 Bidibidi = new Bidi(string, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);1607 byte[]levels = new byte[bidi.getRunCount()];1608 DirectionString[]dirStrings = new DirectionString[levels.length];1609 for ( inti = 0; i < levels.length; ++i) {1602 final var gvs = new ArrayList<GlyphVector>(); 1603 final var bidi = new Bidi(string, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT); 1604 final var levels = new byte[bidi.getRunCount()]; 1605 final var dirStrings = new DirectionString[levels.length]; 1606 for (var i = 0; i < levels.length; ++i) { 1610 1607 levels[i] = (byte) bidi.getRunLevel(i); 1611 Stringsubstr = string.substring(bidi.getRunStart(i), bidi.getRunLimit(i));1612 intdir = levels[i] % 2 == 0 ? Bidi.DIRECTION_LEFT_TO_RIGHT : Bidi.DIRECTION_RIGHT_TO_LEFT;1608 final var substr = string.substring(bidi.getRunStart(i), bidi.getRunLimit(i)); 1609 final var dir = levels[i] % 2 == 0 ? Bidi.DIRECTION_LEFT_TO_RIGHT : Bidi.DIRECTION_RIGHT_TO_LEFT; 1613 1610 dirStrings[i] = new DirectionString(dir, substr); 1614 1611 } 1615 1612 Bidi.reorderVisually(levels, 0, dirStrings, 0, levels.length); 1616 for ( DirectionStringdirString : dirStrings) {1617 char[]chars = dirString.str.toCharArray();1613 for (var dirString : dirStrings) { 1614 var chars = dirString.str.toCharArray(); 1618 1615 gvs.add(font.layoutGlyphVector(frc, chars, 0, chars.length, dirString.direction)); 1619 1616 } … … 1712 1709 public static int getJavaVersion() { 1713 1710 // Switch to Runtime.version() once we move past Java 8 1714 Stringversion = Objects.requireNonNull(getSystemProperty("java.version"));1711 var version = Objects.requireNonNull(getSystemProperty("java.version")); 1715 1712 if (version.startsWith("1.")) { 1716 1713 version = version.substring(2); … … 1721 1718 // 9 1722 1719 // 9.0.1 1723 intdotPos = version.indexOf('.');1724 intdashPos = version.indexOf('-');1720 var dotPos = version.indexOf('.'); 1721 var dashPos = version.indexOf('-'); 1725 1722 return Integer.parseInt(version.substring(0, 1726 1723 dotPos > -1 ? dotPos : dashPos > -1 ? dashPos : version.length())); … … 1734 1731 public static int getJavaUpdate() { 1735 1732 // Switch to Runtime.version() once we move past Java 8 1736 Stringversion = Objects.requireNonNull(getSystemProperty("java.version"));1733 var version = Objects.requireNonNull(getSystemProperty("java.version")); 1737 1734 if (version.startsWith("1.")) { 1738 1735 version = version.substring(2); … … 1745 1742 // 17.0.4.1+1-LTS 1746 1743 // $MAJOR.$MINOR.$SECURITY.$PATCH 1747 intundePos = version.indexOf('_');1748 intdashPos = version.indexOf('-');1744 var undePos = version.indexOf('_'); 1745 var dashPos = version.indexOf('-'); 1749 1746 if (undePos > -1) { 1750 1747 return Integer.parseInt(version.substring(undePos + 1, 1751 1748 dashPos > -1 ? dashPos : version.length())); 1752 1749 } 1753 intfirstDotPos = version.indexOf('.');1754 intsecondDotPos = version.indexOf('.', firstDotPos + 1);1750 var firstDotPos = version.indexOf('.'); 1751 var secondDotPos = version.indexOf('.', firstDotPos + 1); 1755 1752 if (firstDotPos == secondDotPos) { 1756 1753 return 0; … … 1767 1764 public static int getJavaBuild() { 1768 1765 // Switch to Runtime.version() once we move past Java 8 1769 Stringversion = Objects.requireNonNull(getSystemProperty("java.runtime.version"));1770 intbPos = version.indexOf('b');1771 intpPos = version.indexOf('+');1766 var version = Objects.requireNonNull(getSystemProperty("java.runtime.version")); 1767 var bPos = version.indexOf('b'); 1768 var pPos = version.indexOf('+'); 1772 1769 try { 1773 1770 return Integer.parseInt(version.substring(bPos > -1 ? bPos + 1 : pPos + 1)); … … 1786 1783 try { 1787 1784 Object value; 1788 Class<?>c = Class.forName("com.sun.deploy.config.BuiltInProperties");1785 var c = Class.forName("com.sun.deploy.config.BuiltInProperties"); 1789 1786 try { 1790 1787 value = c.getDeclaredField("JRE_EXPIRATION_DATE").get(null); … … 1810 1807 public static String getJavaLatestVersion() { 1811 1808 try { 1812 String[]versions = HttpClient.create(1809 var versions = HttpClient.create( 1813 1810 new URL(Config.getPref().get( 1814 1811 "java.baseline.version.url", … … 1816 1813 .connect().fetchContent().split("\n", -1); 1817 1814 if (getJavaVersion() <= 11 && isRunningWebStart()) { // OpenWebStart currently only has Java 11 1818 for ( Stringversion : versions) {1815 for (var version : versions) { 1819 1816 if (version.startsWith("11")) { 1820 1817 return version; … … 1822 1819 } 1823 1820 } else if (getJavaVersion() <= 17) { 1824 for ( Stringversion : versions) {1821 for (var version : versions) { 1825 1822 if (version.startsWith("17")) { // Use current Java LTS 1826 1823 return version; … … 1945 1942 return url.openStream(); 1946 1943 } catch (FileNotFoundException | InvalidPathException e) { 1947 URLbetterUrl = betterJarUrl(url);1944 final var betterUrl = betterJarUrl(url); 1948 1945 if (betterUrl != null) { 1949 1946 try { … … 1982 1979 public static URL betterJarUrl(URL jarUrl, URL defaultUrl) throws IOException { 1983 1980 // Workaround to https://bugs.openjdk.java.net/browse/JDK-4523159 1984 StringurlPath = jarUrl.getPath().replace("%20", " ");1981 var urlPath = jarUrl.getPath().replace("%20", " "); 1985 1982 if (urlPath.startsWith("file:/") && urlPath.split("!", -1).length > 2) { 1986 1983 // Locate jar file 1987 intindex = urlPath.lastIndexOf("!/");1988 PathjarFile = Paths.get(urlPath.substring("file:/".length(), index));1989 Pathfilename = jarFile.getFileName();1990 FileTimejarTime = Files.readAttributes(jarFile, BasicFileAttributes.class).lastModifiedTime();1984 var index = urlPath.lastIndexOf("!/"); 1985 final var jarFile = Paths.get(urlPath.substring("file:/".length(), index)); 1986 var filename = jarFile.getFileName(); 1987 var jarTime = Files.readAttributes(jarFile, BasicFileAttributes.class).lastModifiedTime(); 1991 1988 // Copy it to temp directory (hopefully free of exclamation mark) if needed (missing or older jar) 1992 PathjarCopy = Paths.get(getSystemProperty("java.io.tmpdir")).resolve(filename);1989 final var jarCopy = Paths.get(getSystemProperty("java.io.tmpdir")).resolve(filename); 1993 1990 if (!jarCopy.toFile().exists() || 1994 1991 Files.readAttributes(jarCopy, BasicFileAttributes.class).lastModifiedTime().compareTo(jarTime) < 0) { … … 2029 2026 Logging.trace(e); 2030 2027 try { 2031 URLbetterUrl = betterJarUrl(cl.getResource(path));2028 final var betterUrl = betterJarUrl(cl.getResource(path)); 2032 2029 if (betterUrl != null) { 2033 2030 return betterUrl.openStream();
Note:
See TracChangeset
for help on using the changeset viewer.