1 23 24 42 43 47 48 package com.sun.enterprise.util.io; 49 50 import java.io.*; 51 import java.text.MessageFormat ; 52 import java.util.*; 53 import com.sun.enterprise.util.OS; 56 import java.util.logging.Logger ; 58 import java.util.logging.Level ; 59 62 public class FileUtils 63 { 64 public static native int recursiveChownNative(String dirOrFile, String user); 65 public static native int recursiveChownNative(String dirOrFile); 66 public static native int recursiveChmodNative(String dirOrFile, String permissions); 67 static Logger _logger=IOLogger.getLogger(); 71 static Logger _utillogger=com.sun.logging.LogDomains.getLogger(com.sun.logging.LogDomains.UTIL_LOGGER); 72 private FileUtils() 74 { 75 } 76 77 79 public static boolean safeIsDirectory(File f) 80 { 81 if(f == null || !f.exists() || !f.isDirectory()) 82 return false; 83 84 return true; 85 } 86 87 88 90 public static boolean safeIsRealDirectory(String s) 91 { 92 return safeIsRealDirectory(new File(s)); 93 } 94 95 97 public static boolean safeIsRealDirectory(File f) 98 { 99 if(safeIsDirectory(f) == false) 100 return false; 101 102 103 104 String canonical = safeGetCanonicalPath(f); 106 String absolute = f.getAbsolutePath(); 107 108 if(canonical.equals(absolute)) 109 return true; 110 111 116 if(OS.isWindows() && canonical.equalsIgnoreCase(absolute)) 117 return true; 118 119 return false; 120 } 121 122 124 public static boolean safeIsDirectory(String s) 125 { 126 return safeIsDirectory(new File(s)); 127 } 128 129 131 public static String safeGetCanonicalPath(File f) 132 { 133 if(f == null) 134 return null; 135 136 try 137 { 138 return f.getCanonicalPath(); 139 } 140 catch(IOException e) 141 { 142 return f.getAbsolutePath(); 143 } 144 } 145 146 148 public static File safeGetCanonicalFile(File f) 149 { 150 if(f == null) 151 return null; 152 153 try 154 { 155 return f.getCanonicalFile(); 156 } 157 catch(IOException e) 158 { 159 return f.getAbsoluteFile(); 160 } 161 } 162 163 165 public static boolean isEar(String filename) 166 { 167 return hasExtension(filename, ".ear"); 168 } 169 170 172 public static boolean isJar(String filename) 173 { 174 return hasExtension(filename, ".jar"); 175 } 176 177 179 public static boolean isZip(String filename) 180 { 181 return hasExtensionIgnoreCase(filename, ".zip"); 182 } 183 184 186 public static boolean isArchive(String filename) 187 { 188 return isWar(filename) || isRar(filename) || isJar(filename) || isZip(filename) || isEar(filename); 189 } 190 191 193 public static boolean isArchive(File f) 194 { 195 return isWar(f) || isRar(f) || isJar(f) || isZip(f) || isEar(f); 196 } 197 198 200 public static boolean isWar(String filename) 201 { 202 return hasExtension(filename, ".war"); 203 } 204 205 207 public static boolean isRar(String filename) 208 { 209 return hasExtension(filename, ".rar"); 210 } 211 212 214 public static boolean isEar(File f) 215 { 216 return hasExtension(f, ".ear"); 217 } 218 219 221 public static boolean isJar(File f) 222 { 223 return hasExtension(f, ".jar"); 224 } 225 226 public static boolean isZip(File f) 228 { 229 return hasExtensionIgnoreCase(f, ".zip"); 230 } 231 232 234 public static boolean isWar(File f) 235 { 236 return hasExtension(f, ".war"); 237 } 238 239 241 public static boolean isRar(File f) 242 { 243 return hasExtension(f, ".rar"); 244 } 245 246 248 public static boolean hasExtension(String filename, String ext) 249 { 250 if(filename == null || filename.length() <= 0) 251 return false; 252 253 return filename.endsWith(ext); 254 } 255 256 258 public static boolean hasExtension(File f, String ext) 259 { 260 if(f == null || !f.exists()) 261 return false; 262 263 return f.getName().endsWith(ext); 264 } 265 266 268 public static boolean hasExtensionIgnoreCase(String filename, String ext) 269 { 270 if(filename == null || filename.length() <= 0) 271 return false; 272 273 return filename.toLowerCase().endsWith(ext.toLowerCase()); 274 } 275 276 278 public static boolean hasExtensionIgnoreCase(File f, String ext) 279 { 280 if(f == null || !f.exists()) 281 return false; 282 283 return f.getName().toLowerCase().endsWith(ext.toLowerCase()); 284 } 285 286 288 public static boolean isLegalFilename(String filename) 289 { 290 if(!isValidString(filename)) 291 return false; 292 293 for(int i = 0; i < ILLEGAL_FILENAME_CHARS.length; i++) 294 if(filename.indexOf(ILLEGAL_FILENAME_CHARS[i]) >= 0) 295 return false; 296 297 return true; 298 } 299 300 302 public static boolean isFriendlyFilename(String filename) 303 { 304 if(!isValidString(filename)) 305 return false; 306 307 if(filename.indexOf(BLANK) >= 0 || filename.indexOf(DOT) >= 0) 308 return false; 309 310 return isLegalFilename(filename); 311 } 312 313 315 public static String makeLegalFilename(String filename) 316 { 317 if(isLegalFilename(filename)) 318 return filename; 319 320 for(int i = 0; i < ILLEGAL_FILENAME_CHARS.length; i++) 321 filename = filename.replace(ILLEGAL_FILENAME_CHARS[i], REPLACEMENT_CHAR); 322 323 return filename; 324 } 325 326 328 public static String makeFriendlyFileName(String filename) 329 { 330 return makeFriendlyFilename(filename); 333 } 334 335 337 public static String makeFriendlyFilename(String filename) 338 { 339 if(isFriendlyFilename(filename)) 340 return filename; 341 342 String ret = makeLegalFilename(filename).replace(BLANK, REPLACEMENT_CHAR); 343 ret = ret.replace(DOT, REPLACEMENT_CHAR); 344 return ret; 345 } 346 347 349 public static String makeFriendlyFilenameNoExtension(String filename) 350 { 351 int index = filename.lastIndexOf('.'); 352 353 if(index > 0) 354 filename = filename.substring(0, index); 355 356 return(makeFriendlyFilename(filename)); 357 } 358 359 361 public static String revertFriendlyFilenameExtension(String filename) 362 { 363 if (filename == null || 364 !(filename.endsWith("_ear") || filename.endsWith("_war") || 365 filename.endsWith("_jar") || filename.endsWith("_rar")) ) { 366 return filename; 367 } 368 369 String extension = ""; 370 if (filename.endsWith("_ear")) { 371 filename = filename.substring(0, filename.indexOf("_ear")); 372 extension = ".ear"; 373 } else if (filename.endsWith("_war")) { 374 filename = filename.substring(0, filename.indexOf("_war")); 375 extension = ".war"; 376 } else if (filename.endsWith("_jar")) { 377 filename = filename.substring(0, filename.indexOf("_jar")); 378 extension = ".jar"; 379 } else if (filename.endsWith("_rar")) { 380 filename = filename.substring(0, filename.indexOf("_rar")); 381 extension = ".rar"; 382 } 383 return filename + extension; 384 } 385 386 public static String revertFriendlyFilename(String filename) { 387 388 String name = revertFriendlyFilenameExtension(filename); 390 391 return name.replace(REPLACEMENT_CHAR, '/'); 393 } 394 395 396 397 399 public static String makeFriendlyFileNameNoExtension(String filename) 400 { 401 return makeFriendlyFilenameNoExtension(filename); 404 } 405 406 408 public static void liquidate(File parent) 409 { 410 whack(parent); 411 } 412 413 415 425 public static boolean whack(File parent) 426 { 427 try { 428 432 return whackResolvedDirectory(parent.getCanonicalFile()); 433 } catch (IOException ioe) { 434 _utillogger.log(Level.SEVERE, "iplanet_util.io_exception", ioe); 435 return false; 436 } 437 } 438 439 452 private static boolean whackResolvedDirectory(File parent) 453 { 454 458 if (safeIsRealDirectory(parent)) 459 { 460 File[] kids = parent.listFiles(); 461 462 for(int i = 0; i < kids.length; i++) 463 { 464 File f = kids[i]; 465 466 if(f.isDirectory()) 467 whackResolvedDirectory(f); 468 else 469 deleteFile(f); 470 471 } 472 } 473 474 477 return deleteFile(parent); 478 } 479 484 public static boolean deleteFile(File f) { 485 494 if (f.delete()) { 495 return true; 496 } 497 498 boolean log = _utillogger.isLoggable(FILE_OPERATION_LOG_LEVEL); 499 String filePath = f.getAbsolutePath();; 500 501 506 if ( ! f.exists()) { 507 if (log) { 508 _utillogger.log(Level.FINE, "enterprise_util.delete_failed_absent", filePath); 509 } 510 return true; 511 } else { 512 515 if (log) { 516 _utillogger.log(FILE_OPERATION_LOG_LEVEL, "enterprise_util.error_deleting_file", filePath); 517 } 518 519 boolean deleteOK = false; 520 524 if (OS.isWindows()) { 525 if (log && (FILE_OPERATION_MAX_RETRIES > 0)) { 526 _utillogger.log(FILE_OPERATION_LOG_LEVEL, "enterprise_util.perform_gc"); 527 } 528 int retries = 0; 529 for (retries = 0; retries < FILE_OPERATION_MAX_RETRIES && ! deleteOK; retries++) { 530 try { 531 Thread.currentThread().sleep(FILE_OPERATION_SLEEP_DELAY_MS); 532 } catch (InterruptedException ie) { 533 } 534 System.gc(); 535 deleteOK = f.delete(); 536 } 537 if (log) { 538 if (deleteOK) { 539 _utillogger.log(FILE_OPERATION_LOG_LEVEL, "enterprise_util.retry_delete_success", new Object [] { 540 filePath, new Integer (retries) } ); 541 } else { 542 _utillogger.log(FILE_OPERATION_LOG_LEVEL, "enterprise_util.retry_delete_failure", new Object [] { 543 filePath, new Integer (retries) } ); 544 } 545 } 546 } 547 548 552 if ( ! deleteOK) { 553 f.deleteOnExit(); 554 _utillogger.log(FILE_OPERATION_LOG_LEVEL, "enterprise_util.delete_failed_now_deleteonexit", f.getAbsolutePath()); 555 } 556 return deleteOK; 557 } 558 } 559 560 562 public static File getDirectory(File f) 563 { 564 String filename = f.getAbsolutePath(); 565 return new File((new File(filename)).getParent()); 566 } 567 568 570 public static File createTempFile(File directory) 571 { 572 File f = null; 573 574 try 575 { 576 f = File.createTempFile(TMPFILENAME, "jar", directory); 577 } 578 catch (IOException ioe) 579 { 580 _logger.log(Level.SEVERE,"iplanet_util.io_exception",ioe); 583 } 585 586 f.deleteOnExit(); return f; 588 } 589 590 603 public static File[] listAllFiles(File dirName, String ext) 604 { 605 File[] target = null; 606 List list = searchDir(dirName, ext); 607 608 if ( (list != null) && (list.size() > 0) ) 609 { 610 target = new File[list.size()]; 611 target = (File[]) list.toArray(target); 612 } 613 614 return target; 615 } 616 617 630 public static List searchDir(File dirName, String ext) 631 { 632 List targetList = null; 633 634 if (dirName.isDirectory()) 635 { 636 targetList = new ArrayList(); 637 638 File[] list = dirName.listFiles(); 639 640 for (int i=0; i<list.length; i++) 641 { 642 if (list[i].isDirectory()) 643 { 644 targetList.addAll( searchDir(list[i], ext) ); 645 } 646 else 647 { 648 String name = list[i].toString(); 649 if ( hasExtension(name, ext) ) 650 { 651 targetList.add(list[i]); 652 } 653 } 654 } 655 } 656 657 return targetList; 658 } 659 660 667 public static void copy(String from, String to) throws IOException 668 { 669 if(from == null || to == null) 671 throw new IllegalArgumentException ("null or empty filename argument"); 672 673 File fin = new File(from); 674 File fout = new File(to); 675 676 copy(fin, fout); 677 } 678 686 public static void copy(File fin, File fout) throws IOException 687 { 688 if(safeIsDirectory(fin)) 689 { 690 copyTree(fin, fout); 691 return; 692 } 693 694 if(!fin.exists()) 695 throw new IllegalArgumentException ("File source doesn't exist"); 696 697 if(!safeIsDirectory(fout.getParentFile())) 700 fout.getParentFile().mkdirs(); 701 702 copy(new FileInputStream(fin), new FileOutputStream(fout)); 703 } 704 712 public static void copyTree(File din, File dout) 713 throws IOException 714 { 715 if(!safeIsDirectory(din)) 716 throw new IllegalArgumentException ("Source isn't a directory"); 717 718 dout.mkdirs(); 719 720 if(!safeIsDirectory(dout)) 721 throw new IllegalArgumentException ("Can't create destination directory"); 722 723 FileListerRelative flr = new FileListerRelative(din); 724 String [] files = flr.getFiles(); 725 726 for(int i = 0; i < files.length; i++) 727 { 728 File fin = new File(din, files[i]); 729 File fout = new File(dout, files[i]); 730 731 copy(fin, fout); 732 _logger.log(Level.FINE,"."); 737 } 739 } 740 741 750 public static void copy(InputStream inStream, OutputStream outStream) 751 throws IOException 752 { 753 copyWithoutClose(inStream, outStream); 754 755 inStream.close(); 757 outStream.close(); 758 } 759 760 769 public static void copyWithoutClose(InputStream inStream, 770 OutputStream outStream) throws IOException 771 { 772 BufferedInputStream bis = 773 new BufferedInputStream(inStream, BUFFER_SIZE); 774 BufferedOutputStream bos = 775 new BufferedOutputStream(outStream, BUFFER_SIZE); 776 byte[] buf = new byte[BUFFER_SIZE]; 777 778 int len = 0; 779 while (len != -1) 780 { 781 try 782 { 783 len = bis.read(buf, 0, buf.length); 784 } 785 catch (EOFException eof) 786 { 787 break; 788 } 789 790 if (len != -1) 791 { 792 bos.write(buf, 0, len); 793 } 794 } 795 bos.flush(); 796 } 797 798 806 public static String makeForwardSlashes(String inputStr) 807 { 808 if(inputStr == null) 809 throw new IllegalArgumentException ("null String FileUtils.makeForwardSlashes"); 810 return ( inputStr.replace('\\', '/') ); 811 } 812 813 815 public static String getIllegalFilenameCharacters() 816 { 817 return ILLEGAL_FILENAME_STRING; 818 } 819 820 826 public static String recursiveChown(File dirOrFile) throws NativeIOException 827 { 828 return recursiveChown(dirOrFile, null); 829 } 830 831 833 839 public static String recursiveChown(File dirOrFile, String user) throws NativeIOException 840 { 841 if(dirOrFile == null || !dirOrFile.exists()) 842 throw new NativeIOException("File doesn't exist: " + dirOrFile); 843 844 String fname = dirOrFile.getAbsolutePath(); 845 int ret = 0; 846 847 if(!isValidString(user)) 848 ret = recursiveChownNative(fname); 849 else 850 ret = recursiveChownNative(fname, user); 851 852 NativeResults nr = new NativeResults(ret); 853 NativeIOException ne = nr.getResultException(); 854 855 if(ne == null) 856 return nr.getResultString(); 857 else 858 throw ne; 859 } 860 872 public static String recursiveChmod(File dirOrFile, String permissions) throws NativeIOException 873 { 874 if(dirOrFile == null || !dirOrFile.exists()) 875 throw new NativeIOException("File doesn't exist: " + dirOrFile); 876 877 if(permissions == null) 878 throw new NativeIOException("null permissions string."); 879 880 permissions = permissions.toLowerCase(); verifyPermissions(permissions); 882 883 int ret = recursiveChmodNative(dirOrFile.getAbsolutePath(), permissions); 884 885 NativeResults nr = new NativeResults(ret); 886 NativeIOException ne = nr.getResultException(); 887 888 if(ne == null) 889 return nr.getResultString(); 890 else 891 throw ne; 892 } 893 894 896 static boolean isValidString(String s) 897 { 898 return ((s != null) && (s.length() != 0)); 899 } 900 901 903 914 915 public static File smartRename(File original) throws IOException 916 { 917 if(original == null) 918 throw new IllegalArgumentException ("null argument"); 919 920 String originalName = original.getAbsolutePath(); 921 922 if(!safeIsDirectory(original)) 923 throw new IOException("Directory doesn't exist: " + originalName); 924 925 927 String renamedName = originalName + "_old"; 928 File renamed = new File(renamedName); 929 930 if(renamed.exists()) 931 { 932 whack(renamed); 933 934 if(renamed.exists()) 936 { 937 for(int i = 0; i < 1000; i++) 938 { 939 String name = renamedName + i; 940 renamed = new File(name); 941 942 try{ whack(renamed); } 943 catch(Throwable t) { } 944 945 if(!renamed.exists()) 946 { 947 renamedName = name; 949 break; 950 } 951 } 952 if(renamed.exists()) 954 throw new IOException("Tried 1000 possible rename directory names. None worked!"); 955 } 956 } 957 958 960 962 if(original.renameTo(renamed)) 963 return renamed; 964 965 967 copyTree(original, renamed); 968 whack(original); 970 return renamed; 971 } 972 973 975 981 public static boolean renameFile(File fromFile, File toFile) { 982 boolean result = fromFile.renameTo(toFile); 983 boolean log = _utillogger.isLoggable(FILE_OPERATION_LOG_LEVEL); 984 985 if ( ! result ) { 986 String fromFilePath = null; 987 String toFilePath = null; 988 if (log) { 989 fromFilePath = fromFile.getAbsolutePath(); 990 toFilePath = toFile.getAbsolutePath(); 991 _utillogger.log(FILE_OPERATION_LOG_LEVEL, "enterprise_util.error_renaming_file", new Object [] 992 { fromFilePath, toFilePath } ); 993 } 994 995 999 if (OS.isWindows()) { 1000 if (log && (FILE_OPERATION_MAX_RETRIES > 0)) { 1001 _utillogger.log(FILE_OPERATION_LOG_LEVEL, "enterprise_util.perform_gc"); 1002 } 1003 int retries = 0; 1004 for (retries = 0; retries < FILE_OPERATION_MAX_RETRIES && ! result; retries++) { 1005 try { 1006 Thread.currentThread().sleep(FILE_OPERATION_SLEEP_DELAY_MS); 1007 } catch (InterruptedException ie) { 1008 } 1009 System.gc(); 1010 result = fromFile.renameTo(toFile); 1011 } 1012 if (log) { 1013 if (result) { 1014 _utillogger.log(FILE_OPERATION_LOG_LEVEL, "enterprise_util.retry_rename_success", new Object [] 1015 { fromFilePath, toFilePath, new Integer (retries) } ); 1016 } else { 1017 _utillogger.log(FILE_OPERATION_LOG_LEVEL, "enterprise_util.retry_rename_failure", new Object [] 1018 { fromFilePath, toFilePath, new Integer (retries) } ); 1019 } 1020 } 1021 } 1022 } else { 1023 if (_utillogger.isLoggable(Level.FINE)) { 1024 _utillogger.log(Level.FINE, "enterprise_util.rename_initial_success", new Object [] { 1025 fromFile.getAbsolutePath(), toFile.getAbsolutePath() } ); 1026 } 1027 } 1028 return result; 1029 } 1030 1031 1033 private static void verifyPermissions(String per) throws NativeIOException 1034 { 1035 1038 if(per == null) 1039 throw new NativeIOException("null permissions string."); 1040 if(per.length() != 9) 1041 throw new NativeIOException("permissions string must be exactly" + 1042 " 9 characters long. It is " + per.length() + " characters long."); 1043 1044 String err1 = "permissions string has a bad character ('"; 1046 String err2 = "') at position #"; 1047 String err3 = ". Expected '-' or '"; 1048 String err4 = "'"; 1049 1050 for(int i = 0; i < 9; i++) 1051 { 1052 1053 char c = per.charAt(i); 1054 int pos = i % 3; 1056 if(pos == 0) 1057 { 1058 if(c != 'r' && c != '-') 1059 throw new NativeIOException(err1 + c + err2 + (i + 1) + err3 + 'r' + err4); 1060 } 1061 else if(pos == 1) 1062 { 1063 if(c != 'w' && c != '-') 1064 throw new NativeIOException(err1 + c + err2 + (i + 1) + err3 + 'w' + err4); 1065 } 1066 else if(pos == 2) 1067 { 1068 if(c != 'x' && c != '-') 1069 throw new NativeIOException(err1 + c + err2 + (i + 1) + err3 + 'x' + err4); 1070 } 1071 } 1072 } 1073 1074 1085 public static void appendText(String fileName, String line) throws 1086 RuntimeException { 1087 RandomAccessFile file = null; 1088 try { 1089 final String MODE = "rw"; 1090 file = new RandomAccessFile(fileName, MODE); 1091 file.seek(file.getFilePointer() + file.length()); 1092 file.writeBytes(line); 1093 } 1094 catch(Exception e) { 1095 throw new RuntimeException ("FileUtils.appendText()", e); 1096 } 1097 finally { 1098 try { 1099 if (file != null) 1100 file.close(); 1101 } 1102 catch(Exception e) {} 1103 } 1104 } 1105 1106 public static void appendText(String fileName, StringBuffer buffer) 1107 throws IOException, FileNotFoundException { 1108 appendText(fileName, buffer.toString()); 1109 } 1110 1112 1122 public static String readSmallFile(final String fileName) throws IOException, FileNotFoundException { 1123 return (readSmallFile(new File(fileName)) ); 1124 } 1125 1126 public static String readSmallFile(final File file) throws IOException { 1127 final BufferedReader bf = new BufferedReader(new FileReader(file)); 1128 final StringBuilder sb = new StringBuilder (); String line = null; 1130 try { 1131 while ( (line = bf.readLine()) != null ) { 1132 sb.append(line); 1133 sb.append(System.getProperty("line.separator")); 1134 } 1135 } finally { 1136 try { 1137 bf.close(); 1138 } catch (Exception e) {} 1139 } 1140 return ( sb.toString() ); 1141 } 1142 1143 public static void main(String [] args) 1144 { 1145 try 1146 { 1147 System.out.println(smartRename(new File("C:/temp/test"))); 1148 } 1149 catch(Throwable t) 1150 { 1151 t.printStackTrace(); 1152 } 1153 1166 appendText("empty.txt", "text line"); 1167 } 1168 1169 1172 public static String getFileContents(String fileName) 1173 throws IOException, FileNotFoundException { 1174 1175 FileReader fr = null; 1176 fr = new FileReader(fileName); 1177 StringWriter sr = new StringWriter(); 1178 1179 try { 1180 char[] buf = new char[1024]; 1181 int len = 0; 1182 while (len != -1) { 1183 try { 1184 len = fr.read(buf, 0, buf.length); 1185 } catch (EOFException eof) { 1186 break; 1187 } 1188 if (len != -1) { 1189 sr.write(buf, 0, len); 1190 } 1191 } 1192 1193 fr.close(); 1194 sr.close(); 1195 1196 return sr.toString(); 1197 1198 } finally { 1199 if (fr != null) { 1200 try { 1201 fr.close(); 1202 } catch (IOException ioe) { 1203 } 1204 } 1205 } 1206 } 1207 1208 1213 public static void validateWindowsFilePathLength(String fullPath) throws IOException { 1214 1218 return; 1219 } 1220 1221 1226 public static void validateWindowsFilePathLength(File file) throws IOException { 1227 validateWindowsFilePathLength(file.getAbsolutePath()); 1228 } 1229 1230 1232 private static final int BUFFER_SIZE = 0x10000; private final static char[] ILLEGAL_FILENAME_CHARS = {'/', '\\', ':', '*', '?', '"', '<', '>', '|' }; 1234 private final static String ILLEGAL_FILENAME_STRING = "\\/:*?\"<>|"; 1235 private final static char REPLACEMENT_CHAR = '_'; 1236 private final static char BLANK = ' '; 1237 private final static char DOT = '.'; 1238 private static String TMPFILENAME = "scratch"; 1239 1242 private static final int FILE_OPERATION_MAX_RETRIES = Integer.getInteger("com.sun.appserv.winFileLockRetryLimit", 4).intValue(); 1243 private static final int FILE_OPERATION_SLEEP_DELAY_MS = Integer.getInteger("com.sun.appserv.winFileLockRetryDelay", 100).intValue(); 1244 private static final Level FILE_OPERATION_LOG_LEVEL = Level.INFO; 1245} 1246 | Popular Tags |