1 22 23 package org.meshcms.util; 24 25 import java.io.*; 26 import java.net.*; 27 import java.text.*; 28 import java.util.*; 29 import java.util.zip.*; 30 31 36 public final class Utils { 37 private Utils() { 38 } 39 40 43 public static final String VALID_CHARS = "abcdefghijkmnpqrstuvwxyz23456789"; 44 45 48 public static final String INVALID_FILENAME_CHARS = "\"\\/:*?<>| ,\t\n\r"; 49 50 53 public static final String VALID_FILENAME_CHARS = 54 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'._-"; 55 56 59 public static final int BUFFER_SIZE = 2048; 60 61 64 public static final int KBYTE = 1024; 65 66 69 public static final int MBYTE = KBYTE * KBYTE; 70 71 74 public static final int GBYTE = MBYTE * KBYTE; 75 76 80 public static String addDigits(int num, char space, int len) { 81 return addDigits(Integer.toString(num), space, len); 82 } 83 84 88 public static String addDigits(String s, char space, int len) { 89 if (s == null) { 90 s = ""; 91 } 92 93 while (s.length() < len) { 94 s = space + s; 95 } 96 97 return s; 98 } 99 100 106 public static boolean isNullOrEmpty(String s) { 107 return s == null || s.equals(""); 108 } 109 110 116 public static boolean isNullOrWhitespace(String s) { 117 if (s == null) { 118 return true; 119 } 120 121 for (int i = 0; i < s.length(); i++) { 122 if (!Character.isWhitespace(s.charAt(i))) { 123 return false; 124 } 125 } 126 127 return true; 128 } 129 130 139 public static String trim(String s) { 140 return (s == null) ? null : s.trim(); 141 } 142 143 150 public static String noNull(String s) { 151 return s == null ? "" : s; 152 } 153 154 162 public static String noNull(String s, String def) { 163 return s == null ? def : s; 164 } 165 166 177 public static boolean compareStrings(String s1, String s2, boolean ignoreCase) { 178 if (s1 == null && s2 == null) { 179 return true; 180 } 181 182 if (s1 != null && s2 != null) { 183 return ignoreCase ? s1.equalsIgnoreCase(s2) : s1.equals(s2); 184 } 185 186 return false; 187 } 188 189 199 public static boolean isTrue(String s) { 200 return isTrue(s, false); 201 } 202 203 public static boolean isTrue(String s, boolean checkFalse) { 204 boolean result = false; 205 206 if (s == null) { 207 if (checkFalse) { 208 throw new IllegalArgumentException (); 209 } 210 } else { 211 s = s.trim().toLowerCase(); 212 213 if (s.equals("true") || s.equals("1") || s.equals("yes") || 214 s.equals("ok") || s.equals("checked") || s.equals("selected") || 215 s.equals("on")) { 216 result = true; 217 } else if (checkFalse) { 218 if (!(s.equals("false") || s.equals("0") || s.equals("no") || 219 s.equals("off"))) { 220 throw new IllegalArgumentException (); 221 } 222 } 223 } 224 225 return result; 226 } 227 228 237 public static String limitedLength(String s, int len) { 238 String s1; 239 240 if (isNullOrEmpty(s)) { 241 s1 = ""; 242 } else if (s.length() <= len) { 243 s1 = s; 244 } else if (len < 5) { 245 s1 = "..."; 246 } else { 247 s1 = s.substring(0, len - 4) + " ..."; 248 } 249 250 return s1; 251 } 252 253 260 public static String escapeSingleQuotes(String s) { 261 return replace(s, '\'', "\\'"); 262 } 263 264 273 public static String replace(String s, char c, String n) { 274 StringBuffer sb = new StringBuffer (); 275 276 for (int i = 0; i < s.length(); i++) { 277 if (s.charAt(i) == c) { 278 sb.append(n); 279 } else { 280 sb.append(s.charAt(i)); 281 } 282 } 283 284 return sb.toString(); 285 } 286 287 297 public static String encodeHTML(String s) { 298 return encodeHTML(s, false); 299 } 300 301 316 public static String encodeHTML(String s, boolean encodeAmpersands) { 317 if (isNullOrEmpty(s)) { 318 return ""; 319 } 320 321 StringBuffer sb = new StringBuffer (s.length()); 322 323 for (int i = 0; i < s.length(); i++) { 324 char c = s.charAt(i); 325 326 switch (c) { 327 case '\"': 328 sb.append("""); 329 break; 330 case '&': 331 if (encodeAmpersands) { 332 sb.append("&"); 333 } else { 334 sb.append(c); 335 } 336 337 break; 338 case '\'': 339 sb.append("'"); 340 break; 341 case '<': 342 sb.append("<"); 343 break; 344 case '>': 345 sb.append(">"); 346 break; 347 default: 348 sb.append(c); 349 } 350 } 351 352 return sb.toString(); 353 } 354 355 363 public static String decodeHTML(String s) { 364 if (isNullOrEmpty(s)) { 365 return ""; 366 } 367 368 int sl = s.length(); 369 StringBuffer sb = new StringBuffer (sl); 370 int i = 0; 371 String s0; 372 373 while (i < sl - 3) { 374 s0 = s.substring(i, i + 4); 375 376 if (s0.equals(">")) { 377 sb.append('>'); 378 i += 4; 379 } else if (s0.equals("<")) { 380 sb.append('<'); 381 i += 4; 382 } else if (s0.equals("&")) { 383 if (i < sl - 4 && s.charAt(i + 4) == ';') { 384 sb.append('&'); 385 i += 5; 386 } 387 } else if (s0.equals("'")) { 388 if (i < sl - 4 && s.charAt(i + 4) == ';') { 389 sb.append('\''); 390 i += 5; 391 } 392 } else if (s0.equals("&quo")) { 393 if (i < sl - 5 && s.charAt(i + 4) == 't' && s.charAt(i + 5) == ';') { 394 sb.append('\"'); 395 i += 6; 396 } 397 } else { 398 sb.append(s.charAt(i++)); 399 } 400 } 401 402 return sb.append(s.substring(i)).toString(); 403 } 404 405 412 public static String stripHTMLTags(String s) { 413 return (s!=null) ? s.replaceAll("</?\\S+?[\\s\\S+]*?>", " ") : null; 414 } 415 416 427 public static boolean copyFile(File file, File newFile, boolean overwrite, 428 boolean setLastModified) throws IOException { 429 if (newFile.exists() && !overwrite) { 430 return false; 431 } 432 433 FileInputStream fis = null; 434 435 try { 436 fis = new FileInputStream(file); 437 copyStream(fis, new FileOutputStream(newFile), true); 438 439 if (setLastModified) { 440 newFile.setLastModified(file.lastModified()); 441 } 442 } finally { 443 if (fis != null) { 444 fis.close(); 445 } 446 } 447 448 return true; 449 } 450 451 455 public static boolean copyDirectory(File dir, File newDir, 456 boolean overwriteDir, boolean overwriteFiles, boolean setLastModified) { 457 DirectoryCopier dc = new DirectoryCopier(dir, newDir, overwriteDir, 458 overwriteFiles, setLastModified); 459 dc.process(); 460 return dc.getResult(); 461 } 462 463 473 public static void copyStream(InputStream in, OutputStream out, 474 boolean closeOut) throws IOException { 475 byte b[] = new byte[BUFFER_SIZE]; 476 int n; 477 478 try { 479 while ((n = in.read(b)) != -1) { 480 out.write(b, 0, n); 481 } 482 } finally { 483 try { 484 in.close(); 485 } finally { 486 if (closeOut) { 487 out.close(); 488 } 489 } 490 } 491 } 492 493 502 public static void copyReaderToWriter(Reader reader, Writer writer, 503 boolean closeWriter) throws IOException { 504 char c[] = new char[BUFFER_SIZE]; 505 int n; 506 507 while ((n = reader.read(c)) != -1) { 508 writer.write(c, 0, n); 509 } 510 511 reader.close(); 512 writer.flush(); 513 514 if (closeWriter) { 515 writer.close(); 516 } 517 } 518 519 527 public static void writeFully(File file, String s) throws IOException { 528 Writer writer = new BufferedWriter(new FileWriter(file)); 529 writer.write(s); 530 writer.close(); 531 } 532 533 541 public static void writeFully(File file, byte[] b) throws IOException { 542 FileOutputStream fos = new FileOutputStream(file); 543 fos.write(b); 544 fos.close(); 545 } 546 547 556 public static String readFully(File file) throws IOException { 557 Reader reader = new BufferedReader(new FileReader(file)); 558 String s = readFully(reader); 559 reader.close(); 560 return s; 561 } 562 563 572 public static String readFully(Reader reader) throws IOException { 573 CharArrayWriter caw = new CharArrayWriter(); 574 char[] cbuf = new char[BUFFER_SIZE]; 575 int n; 576 577 while ((n = reader.read(cbuf)) != -1) { 578 caw.write(cbuf, 0, n); 579 } 580 581 return caw.toString(); 582 } 583 584 593 public static char[] readAllChars(Reader reader) throws IOException { 594 CharArrayWriter caw = new CharArrayWriter(); 595 char[] cbuf = new char[BUFFER_SIZE]; 596 int n; 597 598 while ((n = reader.read(cbuf)) != -1) { 599 caw.write(cbuf, 0, n); 600 } 601 602 return caw.toCharArray(); 603 } 604 605 615 public static byte[] readFully(InputStream in) throws IOException { 616 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 617 byte[] buf = new byte[BUFFER_SIZE]; 618 int n; 619 620 while ((n = in.read(buf)) != -1) { 621 baos.write(buf, 0, n); 622 } 623 624 return baos.toByteArray(); 625 } 626 627 636 public static String [] readAllLines(File file) 637 throws FileNotFoundException, IOException { 638 BufferedReader reader = new BufferedReader(new FileReader(file)); 639 List list = new ArrayList(); 640 String line; 641 642 while ((line = reader.readLine()) != null) { 643 list.add(line); 644 } 645 646 reader.close(); 647 return (String []) list.toArray(new String [list.size()]); 648 } 649 650 658 public static void unzip(File zip, File dir) throws IOException { 659 dir.mkdirs(); 660 InputStream in = new BufferedInputStream(new FileInputStream(zip)); 661 ZipInputStream zin = new ZipInputStream(in); 662 ZipEntry e; 663 664 while ((e = zin.getNextEntry()) != null) { 665 File f = new File(dir, e.getName()); 666 667 if (e.isDirectory()) { 668 f.mkdirs(); 669 } else { 670 f.getParentFile().mkdirs(); 671 FileOutputStream out = new FileOutputStream(f); 672 byte[] b = new byte[BUFFER_SIZE]; 673 int len; 674 675 while ((len = zin.read(b)) != -1) { 676 out.write(b, 0, len); 677 } 678 679 out.close(); 680 } 681 } 682 683 zin.close(); 684 } 685 686 690 public static String generateRandomString(int len) { 691 StringBuffer sb = new StringBuffer (len); 692 693 for (int i = 0; i < len; i++) { 694 sb.append(Utils.VALID_CHARS.charAt((int) (Math.random() * 695 Utils.VALID_CHARS.length()))); 696 } 697 698 return sb.toString(); 699 } 700 701 706 public static String generateList(Object [] list, String sep) { 707 if (list == null) { 708 return null; 709 } 710 711 if (list.length == 0) { 712 return ""; 713 } 714 715 StringBuffer sb = new StringBuffer (); 716 sb.append(list[0]); 717 718 for (int i = 1; i < list.length; i++) { 719 sb.append(sep).append(list[i]); 720 } 721 722 return sb.toString(); 723 } 724 725 728 public static String listProperties(Properties p, String sep) { 729 if (p == null) { 730 return null; 731 } 732 733 Enumeration names = p.propertyNames(); 734 StringBuffer sb = new StringBuffer (); 735 736 if (names.hasMoreElements()) { 737 String name = (String ) names.nextElement(); 738 sb.append(name).append('=').append(p.getProperty(name)); 739 } 740 741 while (names.hasMoreElements()) { 742 String name = (String ) names.nextElement(); 743 sb.append(sep).append(name).append('=').append(p.getProperty(name)); 744 } 745 746 return sb.toString(); 747 } 748 749 754 public static String generateList(Collection c, String sep) { 755 if (c == null) { 756 return null; 757 } 758 759 if (c.size() == 0) { 760 return ""; 761 } 762 763 Iterator iter = c.iterator(); 764 StringBuffer sb = new StringBuffer (); 765 766 if (iter.hasNext()) { 767 sb.append(iter.next().toString()); 768 } 769 770 while (iter.hasNext()) { 771 sb.append(sep).append(iter.next()); 772 } 773 774 return sb.toString(); 775 } 776 777 782 public static String generateList(Enumeration e, String sep) { 783 if (e == null) { 784 return null; 785 } 786 787 if (!e.hasMoreElements()) { 788 return ""; 789 } 790 791 StringBuffer sb = new StringBuffer (); 792 793 if (e.hasMoreElements()) { 794 sb.append(e.nextElement().toString()); 795 } 796 797 while (e.hasMoreElements()) { 798 sb.append(sep).append(e.nextElement()); 799 } 800 801 return sb.toString(); 802 } 803 804 809 public static String generateList(int[] list, String sep) { 810 if (list == null) { 811 return null; 812 } 813 814 if (list.length == 0) { 815 return ""; 816 } 817 818 StringBuffer sb = new StringBuffer (Integer.toString(list[0])); 819 820 for (int i = 1; i < list.length; i++) { 821 sb.append(sep).append(list[i]); 822 } 823 824 return sb.toString(); 825 } 826 827 830 public static int sum(int[] ints) { 831 int s = 0; 832 833 for (int i = 0; i < ints.length; i++) { 834 s += ints[i]; 835 } 836 837 return s; 838 } 839 840 844 public static String generateUniqueName(String fileName, File directory) { 845 if (directory.isDirectory()) { 846 return generateUniqueName(fileName, directory.list()); 847 } 848 849 return null; 850 } 851 852 858 public static String generateUniqueDosName(String fileName, String [] files) { 859 fileName = fileName.toLowerCase(); 860 String ext = ""; 861 int idx = fileName.lastIndexOf('.'); 862 863 if (idx != -1) { 864 ext = fileName.substring(idx); 865 866 if (ext.length() > 4) { 867 ext = ext.substring(0, 4); 868 } 869 870 fileName = fileName.substring(0, idx); 871 } 872 873 String name = ""; 874 875 for (int i = 0; i < fileName.length(); i++) { 876 char c = fileName.charAt(i); 877 878 if (Character.isLetterOrDigit(c)) { 879 name += c; 880 881 if (name.length() == 8) { 882 break; 883 } 884 } 885 } 886 887 if (name.length() == 0) { 888 name = "file"; 889 } 890 891 if (searchString(files, name + ext, true) < 0) { 892 return name + ext; 893 } 894 895 int limit = 1; 896 897 for (int i = 1; i <= 8; i++) { 898 int first = limit; 899 limit *= 10; 900 901 String base = (name.length() <= 7 - i) ? name : name.substring(0, 7 - i); 902 base += "_"; 903 904 for (int j = first; j < limit; j++) { 905 String temp = base + j + ext; 906 907 if (searchString(files, temp, true) < 0) { 908 return temp; 909 } 910 } 911 } 912 913 return null; 914 } 915 916 927 public static String generateUniqueName(String fileName, String [] files) { 928 fileName = fileName.toLowerCase(); 929 String ext = ""; 930 int idx = fileName.lastIndexOf('.'); 931 932 if (idx != -1) { 933 ext = fileName.substring(idx); 934 fileName = fileName.substring(0, idx); 935 } 936 937 if (searchString(files, fileName + ext, true) == -1) { 938 return fileName + ext; 939 } 940 941 int d = 0; 942 943 for (int i = fileName.length() - 1; i >= 0; i--) { 944 if (!Character.isDigit(fileName.charAt(i))) { 945 d = i + 1; 946 break; 947 } 948 } 949 950 int number = parseInt(fileName.substring(d), 1); 951 fileName = fileName.substring(0, d); 952 String temp; 953 954 do { 955 temp = fileName + ++number + ext; 956 } while (searchString(files, temp, true) != -1); 957 958 return temp; 959 } 960 961 972 public static int parseInt(String s, int def) { 973 try { 974 def = Integer.parseInt(s); 975 } catch (Exception ex) {} 976 977 return def; 978 } 979 980 991 public static long parseLong(String s, long def) { 992 try { 993 def = Long.parseLong(s); 994 } catch (Exception ex) {} 995 996 return def; 997 } 998 999 1008 public static String [] tokenize(String s) { 1009 return tokenize(s, null); 1010 } 1011 1012 1020 public static String [] tokenize(String s, String delim) { 1021 if (s == null) { 1022 return null; 1023 } 1024 1025 StringTokenizer st; 1026 1027 if (isNullOrEmpty(delim)) { 1028 st = new StringTokenizer(s); 1029 } else { 1030 st = new StringTokenizer(s, delim); 1031 } 1032 1033 String [] res = new String [st.countTokens()]; 1034 1035 for (int i = 0; i < res.length; i++) { 1036 res[i] = st.nextToken(); 1037 } 1038 1039 return res; 1040 } 1041 1042 1051 public static int searchString(String [] array, String s, boolean ignoreCase) { 1052 if (array == null || array.length == 0 || s == null) { 1053 return -1; 1054 } 1055 1056 if (ignoreCase) { 1057 for (int i = 0; i < array.length; i++) { 1058 if (s.equalsIgnoreCase(array[i])) { 1059 return i; 1060 } 1061 } 1062 } else { 1063 for (int i = 0; i < array.length; i++) { 1064 if (s.equals(array[i])) { 1065 return i; 1066 } 1067 } 1068 } 1069 1070 return -1; 1071 } 1072 1073 1080 public static boolean checkAddress(String email) { 1081 if (isNullOrEmpty(email) || email.indexOf(' ') >= 0) { 1082 return false; 1083 } 1084 1085 int dot = email.lastIndexOf('.'); 1086 int at = email.lastIndexOf('@'); 1087 return !(dot < 0 || at < 0 || at > dot); 1088 } 1089 1090 1097 public static int getRandomInt(int max) { 1098 return (int) (Math.random() * max); 1099 } 1100 1101 1108 public static Object getRandomElement(Object [] array) { 1109 if (array == null || array.length == 0) { 1110 return null; 1111 } 1112 1113 return array[getRandomInt(array.length)]; 1114 } 1115 1116 1123 public static float decimalPart(float f) { 1124 return f - (int) f; 1125 } 1126 1127 1134 public static double decimalPart(double d) { 1135 return d - (long) d; 1136 } 1137 1138 1145 public static int sign(int n) { 1146 if (n < 0) { 1147 return -1; 1148 } 1149 if (n > 0) { 1150 return 1; 1151 } 1152 return 0; 1153 } 1154 1155 1165 public static int constrain(int min, int max, int n) { 1166 if (n < min) { 1167 return min; 1168 } 1169 if (n > max) { 1170 return max; 1171 } 1172 return n; 1173 } 1174 1175 1185 public static String addAtEnd(String base, String what) { 1186 if (base == null) { 1187 base = what; 1188 } else if (!base.endsWith(what)) { 1189 base += what; 1190 } 1191 1192 return base; 1193 } 1194 1195 1204 public static String removeAtEnd(String base, String what) { 1205 if (base != null && base.endsWith(what)) { 1206 base = base.substring(0, base.length() - what.length()); 1207 } 1208 1209 return base; 1210 } 1211 1212 1221 public static String addAtBeginning(String base, String what) { 1222 if (base == null) { 1223 base = what; 1224 } else if (!base.startsWith(what)) { 1225 base = what + base; 1226 } 1227 1228 return base; 1229 } 1230 1231 1240 public static String removeAtBeginning(String base, String what) { 1241 if (base != null && base.startsWith(what)) { 1242 base = base.substring(what.length()); 1243 } 1244 1245 return base; 1246 } 1247 1248 1259 public static String getRelativePath(File folder, File file, String separator) { 1260 return getRelativePath(getFilePath(folder), getFilePath(file), separator); 1261 } 1262 1263 1274 public static String getRelativePath(String folder, String file, 1275 String separator) { 1276 String [] a0 = Utils.tokenize(folder, "/\\"); 1277 String [] a1 = Utils.tokenize(file, "/\\"); 1278 1279 int i0 = 0; 1280 int i1 = 0; 1281 1282 String result = ""; 1283 1284 while (i0 < a0.length && i1 < a1.length && a0[i0].equals(a1[i1])) { 1285 i0++; 1286 i1++; 1287 } 1288 1289 while (i0++ < a0.length) { 1290 result += ".." + separator; 1291 } 1292 1293 while (i1 < a1.length - 1) { 1294 result += a1[i1++] + separator; 1295 } 1296 1297 if (i1 == a1.length - 1) { 1298 result += a1[i1]; 1299 } 1300 1301 return result; 1302 } 1303 1304 1316 public static String getCombinedPath(String folder, String file, 1317 String separator) { 1318 String [] a0 = Utils.tokenize(folder, "/\\"); 1319 String [] a1 = Utils.tokenize(file, "/\\"); 1320 1321 int i0 = a0.length; 1322 int i1 = 0; 1323 1324 while (i1 < a1.length && a1[i1].equals("..")) { 1325 i0--; 1326 i1++; 1327 } 1328 1329 if (i0 < 0) { 1330 throw new IllegalArgumentException ("Not enough levels"); 1331 } 1332 1333 String result = null; 1334 1335 for (int i = 0; i < i0; i++) { 1336 if (!a0[i].equals(".")) { 1337 result = (result == null) ? a0[i] : result + separator + a0[i]; 1338 } 1339 } 1340 1341 for (int i = i1; i < a1.length; i++) { 1342 if (!a1[i].equals(".")) { 1343 result = (result == null) ? a1[i] : result + separator + a1[i]; 1344 } 1345 } 1346 1347 return noNull(result); 1348 } 1349 1350 1359 public static String getFilePath(File f) { 1360 try { 1361 return f.getCanonicalPath(); 1362 } catch (IOException ex) {} 1363 1364 return f.getAbsolutePath(); 1365 } 1366 1367 public static String getExtension(File file, boolean includeDot) { 1368 return getExtension(file.getName(), includeDot); 1369 } 1370 1371 public static String getExtension(Path path, boolean includeDot) { 1372 return getExtension(path.getLastElement(), includeDot); 1373 } 1374 1375 1383 public static String getExtension(String fileName, boolean includeDot) { 1384 if (fileName == null) { 1385 return null; 1386 } 1387 1388 int dot = fileName.lastIndexOf('.'); 1389 return (dot == -1) ? "" : 1390 fileName.substring(includeDot ? dot : dot + 1).toLowerCase(); 1391 } 1392 1393 1400 public static String removeExtension(Object o) { 1401 String fileName = null; 1402 1403 if (o instanceof File) { 1404 fileName = ((File) o).getName(); 1405 } else if (o instanceof Path) { 1406 fileName = ((Path) o).getLastElement(); 1407 } else if (o != null) { 1408 fileName = o.toString(); 1409 } 1410 1411 if (fileName == null) { 1412 return null; 1413 } 1414 1415 int dot = fileName.lastIndexOf('.'); 1416 return (dot == -1) ? fileName : fileName.substring(0, dot); 1417 } 1418 1419 1428 public static String getCommonPart(String s1, String s2) { 1429 if (s1 == null || s2 == null) { 1430 return null; 1431 } 1432 1433 int len = Math.min(s1.length(), s2.length()); 1434 1435 for (int i = 0; i < len; i++) { 1436 if (s1.charAt(i) != s2.charAt(i)) { 1437 return s1.substring(0, i); 1438 } 1439 } 1440 1441 return s1.length() < s2.length() ? s1 : s2; 1442 } 1443 1444 1453 public static String beautify(String s, boolean titleCase) { 1454 StringBuffer sb = new StringBuffer (s.length()); 1455 boolean nextUpper = true; 1456 1457 for (int i = 0; i < s.length(); i++) { 1458 char c = s.charAt(i); 1459 1460 if (c == '_') { 1461 c = ' '; 1462 } 1463 1464 if (c == ' ') { 1465 nextUpper = true; 1466 } else { 1467 if (titleCase && nextUpper) { 1468 c = Character.toTitleCase(c); 1469 nextUpper = false; 1470 } 1471 } 1472 1473 sb.append(c); 1474 } 1475 1476 return sb.toString(); 1477 } 1478 1479 1488 public static boolean forceDelete(File file) { 1489 if (!file.exists()) { 1490 return true; 1491 } 1492 1493 1494 if (file.isDirectory()) { 1495 return file.delete(); 1496 } 1497 1498 for (int i = 1; i < 20; i++) { 1499 if (file.delete()) { 1500 return true; 1501 } 1502 1503 try { 1504 Thread.sleep(i * 100L); 1505 } catch (InterruptedException ex) {} 1506 } 1507 1508 return false; 1509 } 1510 1511 1522 public static boolean forceRenameTo(File oldFile, File newFile, 1523 boolean overwrite) { 1524 if (newFile.exists()) { 1525 if (overwrite) { 1526 if (!forceDelete(newFile)) { 1527 return false; 1528 } 1529 } else { 1530 return false; 1531 } 1532 } 1533 1534 for (int i = 0; i < 20; i++) { 1535 if (oldFile.renameTo(newFile)) { 1536 return true; 1537 } 1538 1539 try { 1540 Thread.sleep(i * 100L); 1541 } catch (InterruptedException ex) {} 1542 } 1543 1544 return false; 1545 } 1546 1547 1556 public static String formatFileLength(File file) { 1557 return formatFileLength(file.length()); 1558 } 1559 1560 1568 public static String formatFileLength(long length) { 1569 DecimalFormat format = new DecimalFormat("###0.##"); 1570 double num = length; 1571 String unit; 1572 1573 if (length < KBYTE) { 1574 unit = "B"; 1575 } else if (length < MBYTE) { 1576 num /= KBYTE; 1577 unit = "KB"; 1578 } else if (length < GBYTE) { 1579 num /= MBYTE; 1580 unit = "MB"; 1581 } else { 1582 num /= GBYTE; 1583 unit = "GB"; 1584 } 1585 1586 return format.format(num) + unit; 1587 } 1588 1589 1597 public static String encodeURL(Path path) { 1598 return encodeURL(path.toString()); 1599 } 1600 1601 1609 public static String encodeURL(String url) { 1610 try { 1611 url = URLEncoder.encode(url, "UTF-8"); 1612 } catch (UnsupportedEncodingException ex) { 1613 ex.printStackTrace(); 1614 } 1615 1616 return url; 1617 } 1618 1619 1627 public static String decodeURL(String url) { 1628 try { 1629 url = URLDecoder.decode(url, "UTF-8"); 1630 } catch (UnsupportedEncodingException ex) { 1631 ex.printStackTrace(); 1632 } 1633 1634 return url; 1635 } 1636 1637 1645 public static Locale getLocale(String localeName) { 1646 if (!isNullOrEmpty(localeName)) { 1647 Locale[] locales = Locale.getAvailableLocales(); 1648 1649 for (int i = 0; i < locales.length; i++) { 1650 if (localeName.equals(locales[i].toString())) { 1651 return locales[i]; 1652 } 1653 } 1654 } 1655 1656 return null; 1657 } 1658 1659 1664 public static Locale[] getLanguageLocales() { 1665 Locale[] all = Locale.getAvailableLocales(); 1666 List list = new ArrayList(); 1667 1668 for (int i = 0; i < all.length; i++) { 1669 if (all[i].toString().length() == 2) { 1670 list.add(all[i]); 1671 } 1672 } 1673 1674 return (Locale[]) list.toArray(new Locale[list.size()]); 1675 } 1676 1677 public static String toTitleCase(String s) { 1678 char[] chars = s.trim().toLowerCase().toCharArray(); 1679 boolean found = false; 1680 1681 for (int i = 0; i < chars.length; i++) { 1682 if (!found && Character.isLetter(chars[i])) { 1683 chars[i] = Character.toUpperCase(chars[i]); 1684 found = true; 1685 } else if (Character.isWhitespace(chars[i])) { 1686 found = false; 1687 } 1688 } 1689 1690 return String.valueOf(chars); 1691 } 1692 1693 public static String [] commonPart(String [] sa1, String [] sa2, boolean fromEnd) { 1694 int len1 = sa1.length; 1695 int len2 = sa2.length; 1696 int cnt = Math.min(len1, len2); 1697 1698 if (fromEnd) { 1699 for (int i = 1; i <= cnt; i++) { 1700 if (!sa1[len1 - i].equals(sa2[len2 - i])) { 1701 cnt = i - 1; 1702 } 1703 } 1704 } else { 1705 for (int i = 0; i < cnt; i++) { 1706 if (!sa1[i].equals(sa2[i])) { 1707 cnt = i; 1708 } 1709 } 1710 } 1711 1712 String [] result = new String [cnt]; 1713 System.arraycopy(sa1, fromEnd ? len1 - cnt : 0, result, 0, cnt); 1714 return result; 1715 } 1716} 1717 | Popular Tags |