1 19 20 package org.apache.cayenne.util; 21 22 import java.io.BufferedInputStream ; 23 import java.io.BufferedOutputStream ; 24 import java.io.BufferedReader ; 25 import java.io.ByteArrayInputStream ; 26 import java.io.ByteArrayOutputStream ; 27 import java.io.File ; 28 import java.io.FileInputStream ; 29 import java.io.FileOutputStream ; 30 import java.io.FileReader ; 31 import java.io.IOException ; 32 import java.io.InputStream ; 33 import java.io.ObjectInputStream ; 34 import java.io.ObjectOutputStream ; 35 import java.io.OutputStream ; 36 import java.io.Serializable ; 37 import java.lang.reflect.Member ; 38 import java.lang.reflect.Modifier ; 39 import java.net.URL ; 40 import java.sql.SQLException ; 41 import java.util.ArrayList ; 42 import java.util.Collection ; 43 import java.util.Collections ; 44 import java.util.Comparator ; 45 import java.util.HashMap ; 46 import java.util.Iterator ; 47 import java.util.List ; 48 import java.util.Map ; 49 import java.util.regex.Pattern ; 50 51 import javax.xml.parsers.ParserConfigurationException ; 52 import javax.xml.parsers.SAXParser ; 53 import javax.xml.parsers.SAXParserFactory ; 54 55 import org.apache.commons.lang.builder.EqualsBuilder; 56 import org.apache.commons.lang.builder.HashCodeBuilder; 57 import org.xml.sax.SAXException ; 58 import org.xml.sax.XMLReader ; 59 60 65 public class Util { 66 67 70 public static String stringFromFile(File file) throws IOException { 71 return stringFromFile(file, System.getProperty("line.separator")); 72 } 73 74 78 public static String stringFromFile(File file, String joinWith) throws IOException { 79 StringBuffer buf = new StringBuffer (); 80 BufferedReader in = new BufferedReader (new FileReader (file)); 81 82 try { 83 String line = null; 84 while ((line = in.readLine()) != null) { 85 buf.append(line).append(joinWith); 86 } 87 } 88 finally { 89 in.close(); 90 } 91 return buf.toString(); 92 } 93 94 98 public static boolean copy(File source, File destination) { 99 BufferedInputStream fin = null; 100 BufferedOutputStream fout = null; 101 try { 102 int bufSize = 8 * 1024; 103 fin = new BufferedInputStream (new FileInputStream (source), bufSize); 104 fout = new BufferedOutputStream (new FileOutputStream (destination), bufSize); 105 copyPipe(fin, fout, bufSize); 106 } 107 catch (IOException ioex) { 108 return false; 109 } 110 catch (SecurityException sx) { 111 return false; 112 } 113 finally { 114 if (fin != null) { 115 try { 116 fin.close(); 117 } 118 catch (IOException cioex) { 119 } 120 } 121 if (fout != null) { 122 try { 123 fout.close(); 124 } 125 catch (IOException cioex) { 126 } 127 } 128 } 129 return true; 130 } 131 132 135 public static boolean copy(URL from, File to) { 136 BufferedInputStream urlin = null; 137 BufferedOutputStream fout = null; 138 try { 139 int bufSize = 8 * 1024; 140 urlin = new BufferedInputStream ( 141 from.openConnection().getInputStream(), 142 bufSize); 143 fout = new BufferedOutputStream (new FileOutputStream (to), bufSize); 144 copyPipe(urlin, fout, bufSize); 145 } 146 catch (IOException ioex) { 147 return false; 148 } 149 catch (SecurityException sx) { 150 return false; 151 } 152 finally { 153 if (urlin != null) { 154 try { 155 urlin.close(); 156 } 157 catch (IOException cioex) { 158 } 159 } 160 if (fout != null) { 161 try { 162 fout.close(); 163 } 164 catch (IOException cioex) { 165 } 166 } 167 } 168 return true; 169 } 170 171 180 public static void copyPipe(InputStream in, OutputStream out, int bufSizeHint) 181 throws IOException { 182 int read = -1; 183 byte[] buf = new byte[bufSizeHint]; 184 while ((read = in.read(buf, 0, bufSizeHint)) >= 0) { 185 out.write(buf, 0, read); 186 } 187 out.flush(); 188 } 189 190 194 public static boolean delete(String filePath, boolean recursive) { 195 File file = new File (filePath); 196 if (!file.exists()) { 197 return true; 198 } 199 200 if (!recursive || !file.isDirectory()) 201 return file.delete(); 202 203 String [] list = file.list(); 204 for (int i = 0; i < list.length; i++) { 205 if (!delete(filePath + File.separator + list[i], true)) 206 return false; 207 } 208 209 return file.delete(); 210 } 211 212 216 public static String substBackslashes(String string) { 217 return RegexUtil.substBackslashes(string); 218 } 219 220 225 public static Throwable unwindException(Throwable th) { 226 if (th instanceof SAXException ) { 227 SAXException sax = (SAXException ) th; 228 if (sax.getException() != null) { 229 return unwindException(sax.getException()); 230 } 231 } 232 else if (th instanceof SQLException ) { 233 SQLException sql = (SQLException ) th; 234 if (sql.getNextException() != null) { 235 return unwindException(sql.getNextException()); 236 } 237 } 238 else if (th.getCause() != null) { 239 return unwindException(th.getCause()); 240 } 241 242 return th; 243 } 244 245 249 public static boolean nullSafeEquals(Object o1, Object o2) { 250 251 if (o1 == null) { 252 return o2 == null; 253 } 254 255 if (o1.getClass().isArray()) { 260 EqualsBuilder builder = new EqualsBuilder(); 261 builder.append(o1, o2); 262 return builder.isEquals(); 263 } 264 else { return o1.equals(o2); 266 } 267 } 268 269 276 public static int nullSafeCompare(boolean nullsFirst, Comparable o1, Object o2) { 277 if (o1 == null && o2 == null) { 278 return 0; 279 } 280 else if (o1 == null) { 281 return nullsFirst ? -1 : 1; 282 } 283 else if (o2 == null) { 284 return nullsFirst ? 1 : -1; 285 } 286 else { 287 return o1.compareTo(o2); 288 } 289 } 290 291 294 public static boolean isEmptyString(String string) { 295 return string == null || string.length() == 0; 296 } 297 298 301 public static Object cloneViaSerialization(Serializable obj) throws Exception { 302 ByteArrayOutputStream bytes = new ByteArrayOutputStream () { 303 304 public synchronized byte[] toByteArray() { 305 return buf; 306 } 307 }; 308 309 ObjectOutputStream out = new ObjectOutputStream (bytes); 310 out.writeObject(obj); 311 out.close(); 312 313 ObjectInputStream in = new ObjectInputStream (new ByteArrayInputStream (bytes 314 .toByteArray())); 315 Object objCopy = in.readObject(); 316 317 320 return objCopy; 321 } 322 323 328 public static XMLReader createXmlReader() throws SAXException , 329 ParserConfigurationException { 330 SAXParserFactory spf = SAXParserFactory.newInstance(); 331 332 SAXParser saxParser = spf.newSAXParser(); 334 335 XMLReader reader = saxParser.getXMLReader(); 337 338 reader.setFeature("http://xml.org/sax/features/namespaces", true); 340 341 return reader; 342 } 343 344 350 public static String getPackagePath(String className) { 351 return RegexUtil.getPackagePath(className); 352 } 353 354 359 public static Map toMap(Object [] keys, Object [] values) { 360 int keysSize = (keys != null) ? keys.length : 0; 361 int valuesSize = (values != null) ? values.length : 0; 362 363 if (keysSize == 0 && valuesSize == 0) { 364 return new HashMap (); 366 } 367 368 if (keysSize != valuesSize) { 369 throw new IllegalArgumentException ( 370 "The number of keys doesn't match the number of values."); 371 } 372 373 Map map = new HashMap (); 374 for (int i = 0; i < keysSize; i++) { 375 map.put(keys[i], values[i]); 376 } 377 378 return map; 379 } 380 381 384 public static String extractFileExtension(String fileName) { 385 int dotInd = fileName.lastIndexOf('.'); 386 387 return (dotInd > 0 && dotInd < fileName.length()) ? fileName 390 .substring(dotInd + 1) : null; 391 } 392 393 396 public static String stripFileExtension(String fileName) { 397 int dotInd = fileName.lastIndexOf('.'); 398 399 return (dotInd > 0) ? fileName.substring(0, dotInd) : fileName; 402 } 403 404 409 public static String stripLineBreaks(String string, String replaceWith) { 410 if (isEmptyString(string)) { 411 return string; 412 } 413 414 int len = string.length(); 415 StringBuffer buffer = new StringBuffer (len); 416 for (int i = 0; i < len; i++) { 417 char c = string.charAt(i); 418 419 switch (c) { 421 case '\n': 422 case '\r': if (i + 1 < len && string.charAt(i + 1) == '\n') { 424 i++; 425 } 426 427 buffer.append(replaceWith); 428 break; 429 default: 430 buffer.append(c); 431 } 432 } 433 434 return buffer.toString(); 435 } 436 437 441 public static String encodeXmlAttribute(String str) { 442 if (str == null) 443 return null; 444 445 int len = str.length(); 446 if (len == 0) 447 return str; 448 449 StringBuffer encoded = new StringBuffer (); 450 for (int i = 0; i < len; i++) { 451 char c = str.charAt(i); 452 if (c == '<') 453 encoded.append("<"); 454 else if (c == '\"') 455 encoded.append("""); 456 else if (c == '>') 457 encoded.append(">"); 458 else if (c == '\'') 459 encoded.append("'"); 460 else if (c == '&') 461 encoded.append("&"); 462 else 463 encoded.append(c); 464 } 465 466 return encoded.toString(); 467 } 468 469 477 public static String prettyTrim(String str, int maxLength) { 478 if (maxLength < 5) { 479 throw new IllegalArgumentException ( 480 "Algorithm for 'prettyTrim' works only with length >= 5. " 481 + "Supplied length is " 482 + maxLength); 483 } 484 485 if (str == null || str.length() <= maxLength) { 486 return str; 487 } 488 489 int len = maxLength - 3; 491 int startLen = len / 2; 492 int endLen = len - startLen; 493 494 return str.substring(0, startLen) + "..." + str.substring(str.length() - endLen); 495 } 496 497 502 public static Iterator sortedIterator(Iterator it, Comparator comparator) { 503 List list = new ArrayList (); 504 while (it.hasNext()) { 505 list.add(it.next()); 506 } 507 508 Collections.sort(list, comparator); 509 return list.iterator(); 510 } 511 512 515 public static int hashCode(Collection c) { 516 HashCodeBuilder builder = new HashCodeBuilder(); 517 for (Iterator i = c.iterator(); i.hasNext();) 518 builder.append(i.next()); 519 return builder.toHashCode(); 520 } 521 522 525 public static Pattern sqlPatternToPattern(String pattern, boolean ignoreCase) { 526 String preprocessed = RegexUtil.sqlPatternToRegex(pattern); 527 528 int flag = (ignoreCase) ? Pattern.CASE_INSENSITIVE : 0; 529 return Pattern.compile(preprocessed, flag); 530 } 531 532 538 public static boolean isAccessible(Member member) { 539 return Modifier.isPublic(member.getModifiers()) 540 && Modifier.isPublic(member.getDeclaringClass().getModifiers()); 541 } 542 543 549 public static Class getJavaClass(String className) throws ClassNotFoundException { 550 551 553 if (className == null) { 554 throw new ClassNotFoundException ("Null class name"); 555 } 556 557 ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 558 559 if (classLoader == null) { 560 classLoader = Util.class.getClassLoader(); 561 } 562 563 try { 566 return Class.forName(className, true, classLoader); 567 } 568 catch (ClassNotFoundException e) { 569 if (!className.endsWith("[]")) { 570 if ("byte".equals(className)) { 571 return Byte.TYPE; 572 } 573 else if ("int".equals(className)) { 574 return Integer.TYPE; 575 } 576 else if ("short".equals(className)) { 577 return Short.TYPE; 578 } 579 else if ("char".equals(className)) { 580 return Character.TYPE; 581 } 582 else if ("double".equals(className)) { 583 return Double.TYPE; 584 } 585 else if ("long".equals(className)) { 586 return Long.TYPE; 587 } 588 else if ("float".equals(className)) { 589 return Float.TYPE; 590 } 591 else if ("boolean".equals(className)) { 592 return Boolean.TYPE; 593 } 594 else { 596 int dot = className.lastIndexOf('.'); 597 if (dot > 0 && dot + 1 < className.length()) { 598 className = className.substring(0, dot) 599 + "$" 600 + className.substring(dot + 1); 601 try { 602 return Class.forName(className, true, classLoader); 603 } 604 catch (ClassNotFoundException nestedE) { 605 } 607 } 608 } 609 610 throw e; 611 } 612 613 if (className.length() < 3) { 614 throw new IllegalArgumentException ("Invalid class name: " + className); 615 } 616 617 className = className.substring(0, className.length() - 2); 619 620 if ("byte".equals(className)) { 621 return byte[].class; 622 } 623 else if ("int".equals(className)) { 624 return int[].class; 625 } 626 else if ("short".equals(className)) { 627 return short[].class; 628 } 629 else if ("char".equals(className)) { 630 return char[].class; 631 } 632 else if ("double".equals(className)) { 633 return double[].class; 634 } 635 else if ("float".equals(className)) { 636 return float[].class; 637 } 638 else if ("boolean".equals(className)) { 639 return boolean[].class; 640 } 641 642 return Class.forName("[L" + className + ";", true, classLoader); 643 } 644 } 645 } 646 | Popular Tags |