1 56 package org.objectstyle.cayenne.util; 57 58 import java.io.BufferedInputStream ; 59 import java.io.BufferedOutputStream ; 60 import java.io.BufferedReader ; 61 import java.io.ByteArrayInputStream ; 62 import java.io.ByteArrayOutputStream ; 63 import java.io.File ; 64 import java.io.FileInputStream ; 65 import java.io.FileOutputStream ; 66 import java.io.FileReader ; 67 import java.io.IOException ; 68 import java.io.InputStream ; 69 import java.io.ObjectInputStream ; 70 import java.io.ObjectOutputStream ; 71 import java.io.OutputStream ; 72 import java.io.Serializable ; 73 import java.lang.reflect.InvocationTargetException ; 74 import java.net.URL ; 75 import java.sql.SQLException ; 76 import java.util.ArrayList ; 77 import java.util.Collection ; 78 import java.util.Collections ; 79 import java.util.Comparator ; 80 import java.util.HashMap ; 81 import java.util.Iterator ; 82 import java.util.List ; 83 import java.util.Map ; 84 85 import javax.xml.parsers.ParserConfigurationException ; 86 import javax.xml.parsers.SAXParser ; 87 import javax.xml.parsers.SAXParserFactory ; 88 89 import org.apache.commons.lang.builder.EqualsBuilder; 90 import org.apache.commons.lang.builder.HashCodeBuilder; 91 import org.apache.oro.text.perl.Perl5Util; 92 import org.objectstyle.cayenne.CayenneException; 93 import org.objectstyle.cayenne.CayenneRuntimeException; 94 import org.xml.sax.SAXException ; 95 import org.xml.sax.XMLReader ; 96 97 102 public class Util { 103 104 private static final Perl5Util regexUtil = new Perl5Util(); 105 106 110 public static String stringFromFile(File file) throws IOException { 111 return stringFromFile(file, System.getProperty("line.separator")); 112 } 113 114 117 public static String stringFromFile(File file, String joinWith) throws IOException { 118 StringBuffer buf = new StringBuffer (); 119 BufferedReader in = new BufferedReader (new FileReader (file)); 120 121 try { 122 String line = null; 123 while ((line = in.readLine()) != null) { 124 buf.append(line).append(joinWith); 125 } 126 } 127 finally { 128 in.close(); 129 } 130 return buf.toString(); 131 } 132 133 137 public static boolean copy(File source, File destination) { 138 BufferedInputStream fin = null; 139 BufferedOutputStream fout = null; 140 try { 141 int bufSize = 8 * 1024; 142 fin = new BufferedInputStream (new FileInputStream (source), bufSize); 143 fout = new BufferedOutputStream (new FileOutputStream (destination), bufSize); 144 copyPipe(fin, fout, bufSize); 145 } 146 catch (IOException ioex) { 147 return false; 148 } 149 catch (SecurityException sx) { 150 return false; 151 } 152 finally { 153 if (fin != null) { 154 try { 155 fin.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 174 public static boolean copy(URL from, File to) { 175 BufferedInputStream urlin = null; 176 BufferedOutputStream fout = null; 177 try { 178 int bufSize = 8 * 1024; 179 urlin = 180 new BufferedInputStream (from.openConnection().getInputStream(), bufSize); 181 fout = new BufferedOutputStream (new FileOutputStream (to), bufSize); 182 copyPipe(urlin, fout, bufSize); 183 } 184 catch (IOException ioex) { 185 return false; 186 } 187 catch (SecurityException sx) { 188 return false; 189 } 190 finally { 191 if (urlin != null) { 192 try { 193 urlin.close(); 194 } 195 catch (IOException cioex) { 196 } 197 } 198 if (fout != null) { 199 try { 200 fout.close(); 201 } 202 catch (IOException cioex) { 203 } 204 } 205 } 206 return true; 207 } 208 209 218 public static void copyPipe(InputStream in, OutputStream out, int bufSizeHint) 219 throws IOException { 220 int read = -1; 221 byte[] buf = new byte[bufSizeHint]; 222 while ((read = in.read(buf, 0, bufSizeHint)) >= 0) { 223 out.write(buf, 0, read); 224 } 225 out.flush(); 226 } 227 228 232 public static boolean delete(String filePath, boolean recursive) { 233 File file = new File (filePath); 234 if (!file.exists()) { 235 return true; 236 } 237 238 if (!recursive || !file.isDirectory()) 239 return file.delete(); 240 241 String [] list = file.list(); 242 for (int i = 0; i < list.length; i++) { 243 if (!delete(filePath + File.separator + list[i], true)) 244 return false; 245 } 246 247 return file.delete(); 248 } 249 250 254 public static String substBackslashes(String string) { 255 if (string == null) { 256 return null; 257 } 258 259 return regexUtil.match("/\\\\/", string) 260 ? regexUtil.substitute("s/\\\\/\\//g", string) 261 : string; 262 } 263 264 269 public static Throwable unwindException(Throwable th) { 270 if (th instanceof CayenneException) { 271 CayenneException e = (CayenneException) th; 272 if (e.getCause() != null && e.getCause() != e) { 273 return unwindException(e.getCause()); 274 } 275 } 276 else if (th instanceof CayenneRuntimeException) { 277 CayenneRuntimeException e = (CayenneRuntimeException) th; 278 if (e.getCause() != null && e.getCause() != e) { 279 return unwindException(e.getCause()); 280 } 281 } 282 else if (th instanceof InvocationTargetException ) { 283 InvocationTargetException e = (InvocationTargetException ) th; 284 if (e.getTargetException() != null) { 285 return unwindException(e.getTargetException()); 286 } 287 } 288 else if (th instanceof SAXException ) { 289 SAXException sax = (SAXException ) th; 290 if (sax.getException() != null) { 291 return unwindException(sax.getException()); 292 } 293 } 294 else if (th instanceof SQLException ) { 295 SQLException sql = (SQLException ) th; 296 if (sql.getNextException() != null) { 297 return unwindException(sql.getNextException()); 298 } 299 } 300 301 return th; 302 } 303 304 309 public static boolean nullSafeEquals(Object obj1, Object obj2) { 310 if (obj1 == null && obj2 == null) { 311 return true; 312 } 313 else if (obj1 != null) 314 { 315 if (obj1.getClass().isArray()) { 320 EqualsBuilder builder = new EqualsBuilder(); 321 builder.append(obj1, obj2); 322 return builder.isEquals(); 323 } 324 else { return obj1.equals(obj2); 326 } 327 } 328 else { 329 return false; 330 } 331 } 332 333 340 public static int nullSafeCompare(boolean nullsFirst, Comparable o1, Object o2) { 341 if (o1 == null && o2 == null) { 342 return 0; 343 } 344 else if (o1 == null) { 345 return nullsFirst ? -1 : 1; 346 } 347 else if (o2 == null) { 348 return nullsFirst ? 1 : -1; 349 } 350 else { 351 return o1.compareTo(o2); 352 } 353 } 354 355 358 public static boolean isEmptyString(String string) { 359 return string == null || string.length() == 0; 360 } 361 362 365 public static Object cloneViaSerialization(Serializable obj) throws Exception { 366 ByteArrayOutputStream bytes = new ByteArrayOutputStream (); 367 ObjectOutputStream out = new ObjectOutputStream (bytes); 368 out.writeObject(obj); 369 out.close(); 370 371 byte[] data = bytes.toByteArray(); 372 373 ObjectInputStream in = new ObjectInputStream (new ByteArrayInputStream (data)); 374 Object objCopy = in.readObject(); 375 in.close(); 376 return objCopy; 377 } 378 379 384 public static XMLReader createXmlReader() 385 throws SAXException , ParserConfigurationException { 386 SAXParserFactory spf = SAXParserFactory.newInstance(); 387 388 SAXParser saxParser = spf.newSAXParser(); 390 391 XMLReader reader = saxParser.getXMLReader(); 393 394 reader.setFeature("http://xml.org/sax/features/namespaces", true); 396 397 return reader; 398 } 399 400 405 public static String getPackagePath(String className) { 406 if (regexUtil.match("/\\./", className)) { 407 String path = regexUtil.substitute("s/\\./\\//g", className); 408 return path.substring(0, path.lastIndexOf("/")); 409 } 410 else { 411 return ""; 412 } 413 } 414 415 420 public static Map toMap(Object [] keys, Object [] values) { 421 int keysSize = (keys != null) ? keys.length : 0; 422 int valuesSize = (values != null) ? values.length : 0; 423 424 if (keysSize == 0 && valuesSize == 0) { 425 return new HashMap (); 427 } 428 429 if (keysSize != valuesSize) { 430 throw new IllegalArgumentException ( 431 "The number of keys doesn't match the number of values."); 432 } 433 434 Map map = new HashMap (); 435 for (int i = 0; i < keysSize; i++) { 436 map.put(keys[i], values[i]); 437 } 438 439 return map; 440 } 441 442 445 public static String extractFileExtension(String fileName) { 446 int dotInd = fileName.lastIndexOf('.'); 447 448 return (dotInd > 0 && dotInd < fileName.length()) 451 ? fileName.substring(dotInd + 1) 452 : null; 453 } 454 455 458 public static String stripFileExtension(String fileName) { 459 int dotInd = fileName.lastIndexOf('.'); 460 461 return (dotInd > 0) ? fileName.substring(0, dotInd) : fileName; 464 } 465 466 471 public static String stripLineBreaks(String string, String replaceWith) { 472 if (isEmptyString(string)) { 473 return string; 474 } 475 476 int len = string.length(); 477 StringBuffer buffer = new StringBuffer (len); 478 for (int i = 0; i < len; i++) { 479 char c = string.charAt(i); 480 481 switch (c) { 483 case '\n': 484 case '\r': if (i + 1 < len && string.charAt(i + 1) == '\n') { 486 i++; 487 } 488 489 buffer.append(replaceWith); 490 break; 491 default: 492 buffer.append(c); 493 } 494 } 495 496 return buffer.toString(); 497 } 498 499 503 public static String encodeXmlAttribute(String str) { 504 if (str == null) 505 return null; 506 507 int len = str.length(); 508 if (len == 0) 509 return str; 510 511 StringBuffer encoded = new StringBuffer (); 512 for (int i = 0; i < len; i++) { 513 char c = str.charAt(i); 514 if (c == '<') 515 encoded.append("<"); 516 else if (c == '\"') 517 encoded.append("""); 518 else if (c == '>') 519 encoded.append(">"); 520 else if (c == '\'') 521 encoded.append("'"); 522 else if (c == '&') 523 encoded.append("&"); 524 else 525 encoded.append(c); 526 } 527 528 return encoded.toString(); 529 } 530 531 540 public static String prettyTrim(String str, int maxLength) { 541 if (maxLength < 5) { 542 throw new IllegalArgumentException ( 543 "Algorithm for 'prettyTrim' works only with length >= 5. " 544 + "Supplied length is " 545 + maxLength); 546 } 547 548 if (str == null || str.length() <= maxLength) { 549 return str; 550 } 551 552 int len = maxLength - 3; 554 int startLen = len / 2; 555 int endLen = len - startLen; 556 557 return str.substring(0, startLen) + "..." + str.substring(str.length() - endLen); 558 } 559 560 566 public static Iterator sortedIterator(Iterator it, Comparator comparator) { 567 List list = new ArrayList (); 568 while (it.hasNext()) { 569 list.add(it.next()); 570 } 571 572 Collections.sort(list, comparator); 573 return list.iterator(); 574 } 575 576 579 public static int hashCode(Collection c) { 580 HashCodeBuilder builder = new HashCodeBuilder(); 581 for (Iterator i = c.iterator(); i.hasNext();) 582 builder.append(i.next()); 583 return builder.toHashCode(); 584 } 585 586 596 public static String sqlPatternToRegex(String pattern, boolean ignoreCase) { 597 if (pattern == null) { 598 throw new NullPointerException ("Null pattern."); 599 } 600 601 if (pattern.length() == 0) { 602 throw new IllegalArgumentException ("Empty pattern."); 603 } 604 605 StringBuffer buffer = new StringBuffer (); 606 607 buffer.append("/^"); 611 for (int j = 0; j < pattern.length(); j++) { 612 char nextChar = pattern.charAt(j); 613 if (nextChar == '%') { 614 nextChar = '*'; 615 } 616 617 if (nextChar == '*' || nextChar == '?') { 618 buffer.append('.'); 619 } 620 else if ( 622 nextChar == '.' 623 || nextChar == '/' 624 || nextChar == '$' 625 || nextChar == '^') { 626 buffer.append('\\'); 627 } 628 629 buffer.append(nextChar); 630 } 631 632 buffer.append("$/"); 633 634 if (ignoreCase) { 635 buffer.append('i'); 636 } 637 638 String finalPattern = buffer.toString(); 639 640 try { 642 regexUtil.match(finalPattern, "abc_123"); 643 } 644 catch (Exception e) { 645 throw new IllegalArgumentException ( 646 "Error converting pattern: " + e.getLocalizedMessage()); 647 } 648 649 return finalPattern; 650 } 651 } 652 | Popular Tags |