1 30 31 package com.nightlabs.util; 32 33 import java.io.DataInputStream ; 34 import java.io.File ; 35 import java.io.FileInputStream ; 36 import java.io.FileOutputStream ; 37 import java.io.IOException ; 38 import java.io.InputStream ; 39 import java.lang.reflect.Array ; 40 import java.security.MessageDigest ; 41 import java.security.NoSuchAlgorithmException ; 42 import java.util.ArrayList ; 43 import java.util.Collection ; 44 import java.util.HashSet ; 45 import java.util.Iterator ; 46 import java.util.LinkedList ; 47 import java.util.List ; 48 import java.util.StringTokenizer ; 49 50 56 public abstract class Utils 57 { 58 public static String addFinalSlash(String directory) 59 { 60 if (directory.endsWith(File.separator)) 61 return directory; 62 else 63 return directory + File.separator; 64 65 } 66 67 public static String int2StringMinDigits(int i, int minDigits) 68 { 69 String s = Integer.toString(i); 70 if (s.length() < minDigits) { 71 StringBuffer sBuf = new StringBuffer (s); 72 while (sBuf.length() < minDigits) 73 sBuf.insert(0, '0'); 74 75 s = sBuf.toString(); 76 } 77 78 return s; 79 } 80 81 public static String getRelativePath(String baseDir, String file) 82 throws IOException 83 { 84 return getRelativePath(new File (baseDir), file); 85 } 86 87 public static String getRelativePath(File baseDir, File file) 88 throws IOException 89 { 90 return getRelativePath(baseDir, file.getPath()); 91 } 92 93 105 public static String simplifyPath(File path) 106 { 107 LinkedList dirs = new LinkedList (); 108 109 String pathStr = path.getAbsolutePath(); 110 boolean startWithSeparator = pathStr.startsWith(File.separator); 111 112 StringTokenizer tk = new StringTokenizer (pathStr, File.separator, false); 113 while (tk.hasMoreTokens()) { 114 String dir = tk.nextToken(); 115 if (".".equals(dir)) 116 ; else if ("..".equals(dir)) { 118 if (!dirs.isEmpty()) 119 dirs.removeLast(); 120 } 121 else 122 dirs.addLast(dir); 123 } 124 125 StringBuffer sb = new StringBuffer (); 126 for (Iterator it = dirs.iterator(); it.hasNext(); ) { 127 String dir = (String ) it.next(); 128 if (startWithSeparator || sb.length() > 0) 129 sb.append(File.separator); 130 sb.append(dir); 131 } 132 133 return sb.toString(); 134 } 135 136 public static String getRelativePath(File baseDir, String file) 137 throws IOException 138 { 139 if (!baseDir.isAbsolute()) 140 throw new IllegalArgumentException ("baseDir \""+baseDir.getPath()+"\" is not absolute!"); 141 142 File absFile; 143 File tmpF = new File (file); 144 if (tmpF.isAbsolute()) 145 absFile = tmpF; 146 else 147 absFile = new File (baseDir, file); 148 149 String absFileStr = null; 150 String baseDirStr = null; 151 for (int mode_base = 0; mode_base < 2; ++mode_base) { 152 switch (mode_base) { 153 case 0: 154 baseDirStr = simplifyPath(baseDir); 155 break; 156 case 1: 157 baseDirStr = baseDir.getCanonicalPath(); 158 break; 159 default: 160 throw new IllegalStateException ("this should never happen!"); 161 } 162 163 for (int mode_abs = 0; mode_abs < 2; ++mode_abs) { 164 baseDirStr = addFinalSlash(baseDirStr); 165 166 switch (mode_abs) { 167 case 0: 168 absFileStr = simplifyPath(absFile); 169 break; 170 case 1: 171 absFileStr = absFile.getCanonicalPath(); 172 break; 173 default: 174 throw new IllegalStateException ("this should never happen!"); 175 } 176 177 if (!absFileStr.startsWith(baseDirStr)) { 178 if (mode_base >= 1 && mode_abs >= 1) 179 throw new IllegalArgumentException ("file \""+file+"\" is not a child of baseDir \""+baseDir.getCanonicalPath()+"\"!"); 180 } 181 else 182 break; 183 } } 186 if (baseDirStr == null) 187 throw new NullPointerException ("baseDirStr == null"); 188 189 if (absFileStr == null) 190 throw new NullPointerException ("absFileStr == null"); 191 192 return absFileStr.substring(baseDirStr.length(), absFileStr.length()); 193 } 194 195 202 public static long transferStreamData(java.io.InputStream in, java.io.OutputStream out) 203 throws java.io.IOException 204 { 205 return transferStreamData(in, out, 0, -1); 206 } 207 208 270 281 public static boolean deleteDirectoryRecursively(String dir) 282 { 283 File dirF = new File (dir); 284 return deleteDirectoryRecursively(dirF); 285 } 286 287 298 public static boolean deleteDirectoryRecursively(File dir) 299 { 300 if (!dir.exists()) 301 return true; 302 303 if (dir.isDirectory()) { 304 File [] content = dir.listFiles(); 305 for (int i = 0; i < content.length; ++i) { 306 File f = content[i]; 307 if (f.isDirectory()) 308 deleteDirectoryRecursively(f); 309 else 310 f.delete(); 311 } 312 } 313 314 return dir.delete(); 315 } 316 317 326 public static long transferStreamData(java.io.InputStream in, java.io.OutputStream out, long inputOffset, long inputLen) 327 throws java.io.IOException 328 { 329 int bytesRead; 330 int transferred = 0; 331 byte[] buf = new byte[4096]; 332 333 if(inputOffset > 0) 335 if(in.skip(inputOffset) != inputOffset) 336 throw new IOException ("Input skip failed (offset "+inputOffset+")"); 337 338 while (true) { 339 if(inputLen >= 0) 340 bytesRead = in.read(buf, 0, (int)Math.min(buf.length, inputLen-transferred)); 341 else 342 bytesRead = in.read(buf); 343 344 if (bytesRead <= 0) 345 break; 346 347 out.write(buf, 0, bytesRead); 348 349 transferred += bytesRead; 350 351 if(inputLen >= 0 && transferred >= inputLen) 352 break; 353 } 354 out.flush(); 355 return transferred; 356 } 357 358 public static void copyResource(Class sourceResClass, String sourceResName, String dest_name) 359 throws IOException 360 { 361 InputStream source = null; 362 FileOutputStream destination = null; 363 try{ 364 source = sourceResClass.getResourceAsStream(sourceResName); 365 File destination_file = new File (dest_name); 366 367 if (destination_file.exists()) { 368 if (destination_file.isFile()) { 369 DataInputStream in = new DataInputStream (System.in); 370 if (!destination_file.canWrite()) 371 throw new IOException ("FileCopy: destination " + "file is unwriteable: " + destination_file.getCanonicalPath()); 372 } else 373 throw new IOException ("FileCopy: destination is not a file: " + destination_file.getCanonicalPath()); 374 } else { 375 File parentdir = parent(destination_file); 376 if (!parentdir.exists()) 377 throw new IOException ("FileCopy: destination "+ "directory doesn't exist: " + destination_file.getCanonicalPath()); 378 if (!parentdir.canWrite()) 379 throw new IOException ("FileCopy: destination "+ "directory is unwriteable: " + destination_file.getCanonicalPath()); 380 } destination = new FileOutputStream (destination_file); 382 transferStreamData(source,destination); 383 } finally { 384 if (source != null) 385 try { source.close(); } catch (IOException e) { ; } 386 if (destination != null) 387 try { destination.close(); } catch (IOException e) { ; } 388 } 389 390 } 391 392 public static void copyFile(String source_name, String dest_name) 393 throws IOException 394 { 395 File source_file = new File (source_name); 396 File destination_file = new File (dest_name); 397 copyFile(source_file,destination_file); 398 } 399 400 public static void copyFile(File source_file, File destination_file) 401 throws IOException 402 { 403 FileInputStream source = null; 404 FileOutputStream destination = null; 405 byte[] buffer; 406 int bytes_read; 407 408 try { 409 if (!source_file.exists() || !source_file.isFile()) 412 throw new IOException ("FileCopy: no such source file: "+source_file.getCanonicalPath()); 413 if (!source_file.canRead()) 414 throw new IOException ("FileCopy: source file is unreadable: "+source_file.getCanonicalPath()); 415 416 if (destination_file.exists()) { 420 if (destination_file.isFile()) { 421 DataInputStream in = new DataInputStream (System.in); 422 if (!destination_file.canWrite()) 423 throw new IOException ("FileCopy: destination " + 424 "file is unwriteable: " + destination_file.getCanonicalPath()); 425 } else 426 throw new IOException ("FileCopy: destination is not a file: " + destination_file.getCanonicalPath()); 427 } else { 428 File parentdir = parent(destination_file); 429 if (!parentdir.exists()) 430 throw new IOException ("FileCopy: destination " 431 + "directory doesn't exist: " + 432 destination_file.getCanonicalPath()); 433 if (!parentdir.canWrite()) 434 throw new IOException ("FileCopy: destination " 435 + "directory is unwriteable: " + 436 destination_file.getCanonicalPath()); 437 } 438 source = new FileInputStream (source_file); 441 destination = new FileOutputStream (destination_file); 442 transferStreamData(source, destination); 443 } finally { 445 if (source != null) 446 try { source.close(); } catch (IOException e) { ; } 447 if (destination != null) 448 try { destination.close(); } catch (IOException e) { ; } 449 } 450 } 451 452 private static File parent(File f) { 456 String dirname = f.getParent(); 457 if (dirname == null) { 458 return new File (File.separator); 459 } 460 return new File (dirname); 461 } 462 463 public static String decodeHexStr(byte buf[], int pos, int len) { 464 StringBuffer hex = new StringBuffer (); 465 while (len-- > 0) { 466 byte ch = buf[pos++]; 467 int d = (ch >> 4) & 0xf; 468 hex.append((char)(d >= 10 ? 'a' - 10 + d : '0' + d)); 469 d = ch & 0xf; 470 hex.append((char)(d >= 10 ? 'a' - 10 + d : '0' + d)); 471 } 472 return hex.toString(); 473 } 474 475 public static String getMD5HexString(String clear) 476 throws NoSuchAlgorithmException 477 { 478 byte[] enc = MessageDigest.getInstance("MD5").digest(clear.getBytes()); 479 return decodeHexStr(enc, 0, enc.length); 480 } 481 482 483 public static String htmlEncode(String s) 484 { 485 if (s == null) 486 return ""; 487 488 StringBuffer sb = new StringBuffer (); 489 for (int i = 0; i < s.length(); i++) { 490 char ch = s.charAt(i); 491 if (ch == '\n') 492 sb.append("<br>"); 493 else if (ch == '<') 494 sb.append("<"); 495 else if (ch == '>') 496 sb.append(">"); 497 else if (ch == '\t') 498 sb.append(" "); 499 else 500 sb.append(ch); 501 } return sb.toString(); 503 } 504 505 513 public static ArrayList array2ArrayList(Object [] objects) 514 { 515 return array2ArrayList(objects, false); 516 } 517 518 527 public static ArrayList array2ArrayList(Object [] objects, boolean canReturnNull) 528 { 529 if (canReturnNull && objects == null) 530 return null; 531 532 ArrayList l = new ArrayList (objects == null ? 0 : objects.length); 533 if (objects != null) { 534 for (int i = 0; i < objects.length; ++i) 535 l.add(objects[i]); 536 } 537 return l; 538 } 539 540 548 public static HashSet array2HashSet(Object [] objects) 549 { 550 return array2HashSet(objects, false); 551 } 552 553 562 public static HashSet array2HashSet(Object [] objects, boolean canReturnNull) 563 { 564 if (canReturnNull && objects == null) 565 return null; 566 567 HashSet s = new HashSet (objects == null ? 0 : objects.length); 568 if (objects != null) { 569 for (int i = 0; i < objects.length; ++i) 570 s.add(objects[i]); 571 } 572 return s; 573 } 574 575 public static Object [] collection2TypedArray(Collection c, Class clazz) 576 { 577 Object array = Array.newInstance(clazz, c.size()); 578 int i = 0; 579 for (Iterator it = c.iterator(); it.hasNext(); ) 580 Array.set(array, i++, it.next()); 581 return (Object [])array; 582 } 583 584 590 public static void moveListElementUp(List list, Object element) { 591 int index = list.indexOf(element); 592 if (index <= 0 || index >= list.size()) 593 return; 594 list.remove(index); 595 list.add(index-1, element); 596 } 597 598 603 public static void moveListElementDown(List list, Object element) { 604 int index = list.indexOf(element); 605 if (index < 0 || index >= list.size()-1) 606 return; 607 list.remove(index); 608 list.add(index+1, element); 609 } 610 } | Popular Tags |