001/* 002 * 003 * $Revision: 1315 $ 004 * $Date: 2020-03-19 14:33:30 -0700 (Thu, 19 Mar 2020) $ 005 * $Locker: $ 006 * 007 * 008 * Written by Tom Gutwin - WebARTS Design. 009 * http://www.webarts.bc.ca 010 * Copyright (C) 2001-2013 WebARTS Design, North Vancouver Canada 011 * This program is free software; you can redistribute it and/or modify 012 * it under the terms of the GNU General Public License as published by 013 * the Free Software Foundation; either version 2 of the License, or 014 * (at your option) any later version. 015 * 016 * This program is distributed in the hope that it will be useful, 017 * but WITHOUT ANY WARRANTY; without even the implied warranty of 018 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 019 * GNU General Public License for more details. 020 * 021 * You should have received a copy of the GNU General Public License 022 * along with this program; if not, write to the Free Software 023 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 024 */ 025package ca.bc.webarts.widgets; 026 027import ca.bc.webarts.widgets.ExampleFileFilter; 028 029import ca.bc.webarts.tools.Log; 030import ca.bc.webarts.tools.StreamGobbler; 031 032import gnu.regexp.RE; 033import gnu.regexp.REException; 034 035import com.aftexsw.util.bzip.BZip; 036 037import java.awt.Component; 038import java.awt.Frame; 039import java.awt.Image; 040import java.awt.Toolkit; 041import java.io.BufferedReader; 042import java.io.BufferedWriter; 043import java.io.File; 044import java.io.FileNotFoundException; 045import java.io.FileOutputStream; 046import java.io.FileReader; 047import java.io.FileWriter; 048import java.io.FileInputStream; 049import java.io.IOException; 050import java.io.InputStream; 051import java.io.PrintStream; 052import java.net.InetAddress; 053import java.net.MalformedURLException; 054import java.net.URL; 055import java.net.UnknownHostException; 056import java.nio.charset.Charset; 057import java.nio.file.Files; 058import java.nio.file.Paths; 059import java.nio.file.StandardOpenOption; 060import java.text.DecimalFormat; 061import java.util.ArrayList; 062import java.util.Calendar; 063import java.util.Collections; 064import java.util.Comparator; 065import java.util.Date; 066import java.util.Enumeration; 067import java.util.Hashtable; 068import java.util.Iterator; 069import java.util.List; 070import java.util.Map; 071import java.util.Set; 072import java.util.Vector; 073import java.util.jar.JarEntry; 074import java.util.jar.JarFile; 075import java.util.zip.ZipEntry; 076import java.util.zip.ZipOutputStream; 077import java.security.MessageDigest; 078import java.security.NoSuchAlgorithmException; 079 080import javax.xml.parsers.*; 081import javax.xml.transform.*; 082import javax.xml.transform.dom.DOMSource; 083import javax.xml.transform.stream.StreamResult; 084 085import org.w3c.dom.Document; 086import org.xml.sax.InputSource; 087import org.xml.sax.SAXException; 088 089import javax.swing.Icon; 090import javax.swing.ImageIcon; 091import javax.swing.JFileChooser; 092import javax.swing.JFrame; 093import javax.swing.SwingUtilities; 094import javax.swing.UIManager; 095 096import java.io.*; 097 098import org.apache.tools.ant.util.FileUtils; 099import org.apache.tools.ant.taskdefs.Replace; 100 101/* 102import org.geotools.referencing.GeodeticCalculator; 103import org.geotools.geometry.DirectPosition2D; 104import org.geotools.geometry.GeneralDirectPosition; 105import org.geotools.referencing.wkt.Parser; 106import org.opengis.referencing.crs.CoordinateReferenceSystem; 107import org.geotools.referencing.crs.DefaultProjectedCRS; 108import org.opengis.referencing.operation.TransformException; 109*/ 110 111/** 112 * A set of useful utility methods/functions for reuse. 113 * 114 * @author Tom Gutwin P.Eng 115 */ 116public class Util 117{ 118 /** A holder for this clients System File Separator. */ 119 public final static String SYSTEM_FILE_SEPERATOR = File.separator; 120 121 /** A holder for this clients System line termination separator. */ 122 public final static String SYSTEM_LINE_SEPERATOR = 123 System.getProperty("line.separator"); 124 125 /** 126 * A constant to specify which dialog to open with the chooseFileDialog. 127 */ 128 public final static short OPEN_DIALOG = 0; 129 130 /** 131 * A constant to specify which dialog to open with the chooseFileDialog. 132 */ 133 public final static short SAVE_DIALOG = 1; 134 135 /** The VM classpath (used in some methods).. */ 136 public static String CLASSPATH = System.getProperty("class.path"); 137 138 /** The users home ditrectory. */ 139 public static String USERHOME = System.getProperty("user.home"); 140 141 /** The users pwd ditrectory. */ 142 public static String USERDIR = System.getProperty("user.dir"); 143 144 /** A holder This classes name (used when logging). */ 145 private static String CLASSNAME = "ca.bc.webarts.widgets.Util"; 146 147 /** 148 * the Metal LookAndFeel CONSTANT. 149 */ 150 public static final short METAL_LOOKANDFEEL = 0; 151 152 /** 153 * the Windoze LookAndFeel CONSTANT. 154 */ 155 public static final short WINDOZE_LOOKANDFEEL = 1; 156 157 /** 158 * the Motif LookAndFeel CONSTANT. 159 */ 160 public static final short MOTIF_LOOKANDFEEL = 2; 161 162 /** 163 * the Mac LookAndFeel CONSTANT. 164 */ 165 public static final short MAC_LOOKANDFEEL = 3; 166 167 /** 168 * the Default LookAndFeel CONSTANT. DEFAULT_LOOKANDFEEL = METAL_LOOKANDFEEL 169 */ 170 public static final short DEFAULT_LOOKANDFEEL = METAL_LOOKANDFEEL; 171 172 /** 173 * the Mac LookAndFeel class name 174 */ 175 public static String macClassName = 176 "com.sun.java.swing.plaf.mac.MacLookAndFeel"; 177 /** 178 * the Java LookAndFeel class name 179 */ 180 public static String metalClassName = 181 "javax.swing.plaf.metal.MetalLookAndFeel"; 182 /** 183 * the motif LookAndFeel class name 184 */ 185 public static String motifClassName = 186 "com.sun.java.swing.plaf.motif.MotifLookAndFeel"; 187 /** 188 * the Windoze LookAndFeel class name 189 */ 190 public static String windowsClassName = 191 "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"; 192 193 /** Gets a Log instance in case any calling classes are using it. */ 194 private static Log log_ = Log.getInstance(); 195 196 /** Class flag signifying if the initUtil method has been called */ 197 private static boolean initUtil = false; 198 199 /** Class flag for the threadWatchdog method to enable the calling user 200 * to stop the watch. */ 201 public static boolean watchdogReset = false; 202 /** The temp dir where the zipped files go before archiving. */ 203 public static String zippedOutputLocation_ = "."; 204 /** The collection of filenames that had errors during compression. */ 205 public static Vector errorFiles_ = null; 206 207 final static String[] hex = { 208 "%00", "%01", "%02", "%03", "%04", "%05", "%06", "%07", 209 "%08", "%09", "%0a", "%0b", "%0c", "%0d", "%0e", "%0f", 210 "%10", "%11", "%12", "%13", "%14", "%15", "%16", "%17", 211 "%18", "%19", "%1a", "%1b", "%1c", "%1d", "%1e", "%1f", 212 "%20", "%21", "%22", "%23", "%24", "%25", "%26", "%27", 213 "%28", "%29", "%2a", "%2b", "%2c", "%2d", "%2e", "%2f", 214 "%30", "%31", "%32", "%33", "%34", "%35", "%36", "%37", 215 "%38", "%39", "%3a", "%3b", "%3c", "%3d", "%3e", "%3f", 216 "%40", "%41", "%42", "%43", "%44", "%45", "%46", "%47", 217 "%48", "%49", "%4a", "%4b", "%4c", "%4d", "%4e", "%4f", 218 "%50", "%51", "%52", "%53", "%54", "%55", "%56", "%57", 219 "%58", "%59", "%5a", "%5b", "%5c", "%5d", "%5e", "%5f", 220 "%60", "%61", "%62", "%63", "%64", "%65", "%66", "%67", 221 "%68", "%69", "%6a", "%6b", "%6c", "%6d", "%6e", "%6f", 222 "%70", "%71", "%72", "%73", "%74", "%75", "%76", "%77", 223 "%78", "%79", "%7a", "%7b", "%7c", "%7d", "%7e", "%7f", 224 "%80", "%81", "%82", "%83", "%84", "%85", "%86", "%87", 225 "%88", "%89", "%8a", "%8b", "%8c", "%8d", "%8e", "%8f", 226 "%90", "%91", "%92", "%93", "%94", "%95", "%96", "%97", 227 "%98", "%99", "%9a", "%9b", "%9c", "%9d", "%9e", "%9f", 228 "%a0", "%a1", "%a2", "%a3", "%a4", "%a5", "%a6", "%a7", 229 "%a8", "%a9", "%aa", "%ab", "%ac", "%ad", "%ae", "%af", 230 "%b0", "%b1", "%b2", "%b3", "%b4", "%b5", "%b6", "%b7", 231 "%b8", "%b9", "%ba", "%bb", "%bc", "%bd", "%be", "%bf", 232 "%c0", "%c1", "%c2", "%c3", "%c4", "%c5", "%c6", "%c7", 233 "%c8", "%c9", "%ca", "%cb", "%cc", "%cd", "%ce", "%cf", 234 "%d0", "%d1", "%d2", "%d3", "%d4", "%d5", "%d6", "%d7", 235 "%d8", "%d9", "%da", "%db", "%dc", "%dd", "%de", "%df", 236 "%e0", "%e1", "%e2", "%e3", "%e4", "%e5", "%e6", "%e7", 237 "%e8", "%e9", "%ea", "%eb", "%ec", "%ed", "%ee", "%ef", 238 "%f0", "%f1", "%f2", "%f3", "%f4", "%f5", "%f6", "%f7", 239 "%f8", "%f9", "%fa", "%fb", "%fc", "%fd", "%fe", "%ff" 240 }; 241 242 /** Inits the log and some other vars.*/ 243 private static synchronized void initUtil() 244 { 245 final String methodName = CLASSNAME + ": initUtil()"; 246 247 if (!initUtil || log_ == null) 248 { 249 //System.out.println("Into the init block"); 250 log_ = Log.getInstance(); 251 if (log_ != null) 252 { 253 //log_.setLogLevel(Log.MAJOR); 254 log_.startMethod(methodName); 255 } 256 CLASSPATH = System.getProperty("java.class.path"); 257 //System.out.println("In "+methodName); 258 initUtil = true; 259 if (log_ != null) 260 { 261 log_.endMethod(); 262 } 263 264 } 265 } 266 267 268 /** 269 * Ensures that a folder exists. 270 * <TABLE WIDTH="100%" BORDER="0" CELLSPACING="1" CELLPADDING="2"> 271 * 272 * <TR> 273 * 274 * <TDC OLSPAN="2"> 275 * <H2>Ensures that a folder exists</H2> 276 * </TD> 277 * 278 * </TR> 279 * 280 * <TR> 281 * 282 * <TD COLSPAN="2"> 283 * <BR> 284 * <B>Description:</B> <BR> 285 * use it like this: <br> 286 * ensureFolderExists(new File(fileName).getParentFile()); 287 * </TD> 288 * 289 * </TR> 290 * 291 * </TABLE> 292 * 293 * 294 * @param folder The File object to check. 295 */ 296 public static void ensureParentFolderExists(File folder) 297 { 298 //System.out.println(" 1 Making Dir: "+folder.getAbsolutePath()); 299 if (folder != null) 300 { 301 //System.out.println(" 2 Making Dir: "+folder.getAbsolutePath()); 302 ensureFolderExists(folder.getParentFile()); 303 //System.out.print(" 3 Making Dir: "+folder.getAbsolutePath()); 304 boolean suc = folder.mkdir(); 305 //System.out.println(" -->"+(suc?"Successful":"Failed")); 306 } 307 } 308 309 310 public static void ensureFolderExists(File folder) 311 { 312 //System.out.println(" 1 Making Dir: "+folder.getAbsolutePath()); 313 if ((folder != null) && !(folder.isDirectory() )) 314 { 315 //System.out.println(" 2 Making Dir: "+folder.getAbsolutePath()); 316 ensureFolderExists(folder.getParentFile()); 317 //System.out.print(" 3 Making Dir: "+folder.getAbsolutePath()); 318 boolean suc = folder.mkdir(); 319 //System.out.println(" -->"+(suc?"Successful":"Failed")); 320 } 321 } 322 323 324 public static void ensureParentFolderExists(String foldername) 325 { 326 if (foldername != null && !foldername.equals("")) 327 { 328 File folder = new File(foldername); 329 ensureParentFolderExists(folder); 330 } 331 } 332 333 334 public static void ensureFolderExists(String foldername) 335 { 336 if (foldername != null && !foldername.equals("")) 337 { 338 File folder = new File(foldername); 339 ensureFolderExists(folder); 340 } 341 } 342 343 344 /** 345 * Renames the specified file to the toFilename in the same directory. 346 * 347 * @param fromFilename is the absoulte pathname of the file to rename. 348 * @param toFilename is the new filename. 349 * @return the new absolute filename (including path) OR empty if failure 350 **/ 351 public static String renameFile(String fromFilename, String toFilename) 352 { 353 String retVal = ""; 354 if (fromFilename != null && !fromFilename.equals("")) 355 { 356 if(!fromFilename.contains(SYSTEM_FILE_SEPERATOR)) fromFilename = "."+SYSTEM_FILE_SEPERATOR+fromFilename; 357 if(toFilename.contains(SYSTEM_FILE_SEPERATOR)) toFilename.substring(toFilename.lastIndexOf(SYSTEM_FILE_SEPERATOR)+1); 358 File fromFile = new File(fromFilename); 359 if (fromFile != null && fromFile.exists()) 360 { 361 String foldername = fromFile.getParent(); 362 File toFile = new File(foldername+File.separator+toFilename); 363 if( fromFile.renameTo(toFile)) 364 retVal = foldername+File.separator+toFilename; 365 else System.out.println(" !* RenameFileERROR: File.renameTo failed - "+fromFilename +" to "+foldername+File.separator+toFilename); 366 /*else 367 { 368 // Try Native move call 369 String [] ss = {fromFilename,foldername+File.separator+toFilename}; 370 String ret = executeNativeApp("/bin/mv",ss,false); 371 System.out.println(" Native mv: "+ ret); 372 retVal = foldername+File.separator+toFilename; 373 }*/ 374 } 375 else System.out.println(" !* RenameFileERROR: fromFile is empty or null"); 376 } 377 else System.out.println(" !* RenameFileERROR: fromFilename is empty or null"); 378 379 return retVal; 380 } 381 382 383 /** 384 * Moves the specified file to the specified directory. It will create 385 * the target dir if it does not exist. 386 * 387 * @param filename is the absoulte pathname of the file to move. 388 * @param foldername is the directory to move it to. 389 **/ 390 public static boolean moveFile(String filename, String foldername) 391 { 392 boolean retVal = false; 393 if (foldername != null && !foldername.equals("") && 394 filename != null && !filename.equals("")) 395 { 396 File fromFile = new File(filename); 397 if (fromFile != null && fromFile.exists()) 398 { 399 File folder = new File(foldername); 400 ensureFolderExists(folder); 401 File toFile = new File(foldername+File.separator+fromFile.getName()); 402 retVal = fromFile.renameTo(toFile); 403 if (!retVal) 404 { 405 // Try Native move call 406 String [] ss = {filename,foldername}; 407 String ret = executeNativeApp("/bin/mv",ss,false); 408 System.out.println(" Native mv: "+ ret); 409 } 410 } 411 } 412 return retVal; 413 } 414 415 416 /** Converts an HEX number String to its decimal equivalent. 417 * @param str holding the Hex Number string to convert to decimal 418 * @return an int holding the decimal equivalent of the passed in HEX numberStr. 419 **/ 420 public static int convertHexNumberStringToDecimal(String str) 421 { 422 return convertHexNumberStringToDecimal(str, false); 423 } 424 425 426 /** Converts an HEX number String to its decimal equivalent. 427 * @param str holding the Hex Number string to convert to decimal 428 * @param dumpOut boolean flag to turn some debug output on/off 429 * @return an int holding the decimal equivalent of the passed in HEX numberStr. 430 **/ 431 public static int convertHexNumberStringToDecimal(String str, boolean dumpOut) 432 { 433 char[] chars = str.toCharArray(); 434 String out_put = ""; 435 436 if (dumpOut) System.out.println("\n AsciiHex: 0x"+str); 437 if (dumpOut) System.out.print( " Decimal: "); 438 439 StringBuffer hex = new StringBuffer(); 440 String hexInt = new String(); 441 for(int i = 0; i < chars.length; i++) 442 { 443 out_put = Integer.toHexString((int)chars[i]); 444 if (out_put.length()==1) hex.append("0"); 445 hex.append(out_put); 446 if (dumpOut) System.out.print((out_put.length()==1?"0":"")+ out_put); 447 } 448 hexInt = ""+(Integer.parseInt( hex.toString(), 16)); 449 if (dumpOut) System.out.println(""); 450 if (dumpOut) System.out.println( " Decimal: "+hexInt.toString()); 451 452 return Integer.parseInt(hexInt.toString()); 453 454 //return Integer.decode("0x"+str); 455 } 456 457 458 /** Converts an ascii String to a hex String **/ 459 public static String convertStringToHex(String str){ 460 461 char[] chars = str.toCharArray(); 462 463 StringBuffer hex = new StringBuffer(); 464 for(int i = 0; i < chars.length; i++){ 465 hex.append(Integer.toHexString((int)chars[i])); 466 } 467 468 return hex.toString(); 469 } 470 471 472 /** Converts a hex String to an ascii String **/ 473 public static String convertHexToString(String hex){ 474 475 StringBuilder sb = new StringBuilder(); 476 StringBuilder temp = new StringBuilder(); 477 478 //49204c6f7665204a617661 split into two characters 49, 20, 4c... 479 for( int i=0; i<hex.length()-1; i+=2 ){ 480 481 //grab the hex in pairs 482 String output = hex.substring(i, (i + 2)); 483 //convert hex to decimal 484 int decimal = Integer.parseInt(output, 16); 485 //convert the decimal to character 486 sb.append((char)decimal); 487 488 temp.append(decimal); 489 } 490 System.out.println("Decimal : " + temp.toString()); 491 492 return sb.toString(); 493 } 494 495 496 /** 497 * A simple byte to Hex String converter. 498 * 499 * @param b The byte to convert 500 * @return The resultant Hex String 501 */ 502 public static String toHEXString(byte b) 503 { 504 return ("" + "0123456789ABCDEF".charAt(0xf & b >> 4) + 505 "0123456789ABCDEF".charAt(b & 0xF)); 506 } 507 508 509 /** 510 * A simple int to Hex String converter. 511 * 512 * @param s The int to convert 513 * @return The resultant Hex String 514 */ 515 public static final String toHEXString(int s) 516 { 517 return Integer.toHexString(s); 518 /*if (s < 10) 519 { 520 return new StringBuffer(). 521 append((char)('0' + s)). 522 toString(); 523 } 524 else 525 { 526 return new StringBuffer(). 527 append((char)('A' + (s - 10))). 528 toString(); 529 } 530 */ 531 } 532 533 534 /** 535 * A simple int to Hex String converter. 536 * 537 * @param num The int to convert 538 * @return The resultant Hex char array 539 */ 540 public static final char [] toHEXChars(int num) 541 { 542 String s = toHEXString(num); 543 int numChars = s.length(); 544 char [] retVal = new char[numChars]; 545 for (int i = 0; i< numChars; i++) retVal[i] = s.charAt(i); 546 return retVal; 547 } 548 549 550 /** 551 * A simple int to Hex String converter. 552 * 553 * @param num The int to convert 554 * @return The resultant Hex char array 555 */ 556 public static final char [] toHEXChars(int num, int paddedLength) 557 { 558 String s = toHEXString(num); 559 //System.out.println("toHEXChars("+s+", "+paddedLength+")"); 560 int numChars = s.length(); 561 int sRef = 0; 562 char [] retVal = new char[paddedLength]; 563 for (int i = 0; i< paddedLength; i++) 564 if(i<(paddedLength-numChars)) retVal[i] = '0'; 565 else retVal[i] = s.charAt(sRef++); 566 return retVal; 567 } 568 569 570 /** 571 * Another simple int to Hex String converter. 572 * 573 * @param s The int to convert 574 * @return The resultant Hex String 575 */ 576 public static final String decimalToHexadecimal(int s) 577 { 578 StringBuffer retValBuf = new StringBuffer(); 579 int decimalNumber, remainder, quotient; 580 int i = 1, temp; 581 byte[] hexadecimalNumber = new byte[100]; 582 decimalNumber = s; 583 quotient = decimalNumber; 584 while (quotient != 0) 585 { 586 temp = (quotient % 16); //To convert integer into character 587 if (temp < 10) 588 { 589 temp = temp + 48; 590 } 591 else 592 { 593 temp = temp + 55; 594 } 595 hexadecimalNumber[i++] = (byte) temp; 596 quotient = quotient / 16; 597 } 598 //System.out.println(); 599 //System.out.print("Equivalent hexadecimal value of decimal number " + ( decimalNumber) + ": "); 600 for (int j = i - 1; j > 0; j--) 601 { 602 retValBuf.append((char)(hexadecimalNumber[j])); 603 //System.out.print((char)(hexadecimalNumber[j])); 604 } 605 //System.out.println(); 606 return retValBuf.toString(); 607 } 608 609 610 /** 611 * A simple int to Binary String converter. 612 * 613 * @param s The int to convert 614 * @return The resultant binary String 615 */ 616 public static final String decimalToBinary(int s) 617 { 618 StringBuffer retValBuf = new StringBuffer(); 619 int decimalNumber, remainder, quotient; 620 int[] binaryNumber = new int[100]; 621 int i = 1; 622 //System.out.print("Enter any decimal number: "); 623 decimalNumber = s; 624 quotient = decimalNumber; 625 while (quotient != 0) 626 { 627 binaryNumber[i++] = (quotient % 2); 628 quotient = quotient / 2; 629 } 630 System.out.print("Equivalent binary value of decimal number " + (decimalNumber) + ": "); 631 for (int j = i - 1; j > 0; j--) 632 { 633 retValBuf.append(binaryNumber[j]); 634 System.out.print(binaryNumber[j]); 635 } 636 return retValBuf.toString(); 637 } 638 639 640 /** 641 * Uses Java to compute the MD5 sum of a given input String. 642 * @param input is the string to compute 643 * @return the MD5Sum in Hexidecimal 644 */ 645 public static String computeMD5Sum(String input) 646 { 647 648 String retVal = ""; 649 try 650 { 651 StringBuffer sbuf = new StringBuffer(); 652 MessageDigest md = MessageDigest.getInstance("MD5"); 653 byte [] raw = md.digest(input.getBytes()); 654 655 for (int i = 0; i < raw.length; i++) 656 { 657 int c = (int) raw[i]; 658 if (c < 0) 659 { 660 c = (Math.abs(c) - 1) ^ 255; 661 } 662 String block = toHEXString(c >>> 4) + toHEXString(c & 15); 663 sbuf.append(block); 664 retVal = sbuf.toString(); 665 } 666 } 667 catch (NoSuchAlgorithmException crapOut) 668 { 669 670 } 671 672 return retVal; 673 } 674 675 676 public static String xmlToPrettyString(String xmlString, int indent) throws Exception 677 { 678 DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); 679 DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); 680 Document document = documentBuilder.parse(new InputSource(new StringReader(xmlString))); 681 682 TransformerFactory transformerFactory = TransformerFactory.newInstance(); 683 Transformer transformer = transformerFactory.newTransformer(); 684 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); 685 if (indent > 0) { 686 transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 687 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent)); 688 } 689 ByteArrayOutputStream os = new ByteArrayOutputStream(); 690 Result result = new StreamResult(os); 691 Source source = new DOMSource(document); 692 transformer.transform(source, result); 693 694 //aClass.outputStreamMethod(os); 695 String aString = new String(os.toByteArray(),"UTF-8"); 696 return aString; 697 } 698 699 700 /** 701 * SetsIcon for the passed in Frame 702 * 703 * @param imageFilename - is the filename for the new icon 704 * @param appFrame The new iconForApp value 705 */ 706 public static void setIconForApp(JFrame appFrame, String imageFilename) 707 { 708 setIconForApp(appFrame, Util.class.getResource(imageFilename)); 709 } 710 // end of setIconForApp 711 712 713 /** 714 * SetsIcon for the passed in Frame 715 * 716 * @param imageUrl - is the URL for the new icon 717 * @param appFrame The new iconForApp value 718 */ 719 public static void setIconForApp(JFrame appFrame, URL imageUrl) 720 { 721 ImageIcon image = new ImageIcon(imageUrl); 722 appFrame.setIconImage(image.getImage()); 723 image = null; 724 } 725 // end of setIconForApp 726 727 728 /** 729 * Creates a timestamp for the current date. It is in the form of 'year + 730 * "-" + month "-" + date "-" + hour "-" + seconds<br> 731 * For example: 2003-245 732 * 733 * @return The CurrentDateTime value. 734 */ 735 public static String createCurrentDateTime() 736 { 737 Calendar calendar_ = Calendar.getInstance(); 738 739 return ""+ calendar_.get(Calendar.YEAR) + "-" + 740 calendar_.get(Calendar.MONTH)+ "-" + 741 calendar_.get(Calendar.DATE)+ "-" + 742 calendar_.get(Calendar. HOUR_OF_DAY )+ "-" + 743 calendar_.get(Calendar.MINUTE); 744 } 745 746 747 /** 748 * Creates a timestamp for the current date. It is in the form of 'year + 749 * "-" + dayNum <br> 750 * For example: 2003-245 751 * 752 * @return The CurrentTimeStamp value. 753 */ 754 public static String createCurrentDateStamp() 755 { 756 Calendar calendar_ = Calendar.getInstance(); 757 758 return ""+ calendar_.get(Calendar.YEAR) + "-" + 759 calendar_.get(Calendar.DAY_OF_YEAR); 760 } 761 762 763 /** 764 * Creates a timestamp for the current date and time. It is in the form of 'year + 765 * "-" + dayNum + "-" + hour + "-" + min + "-" + sec + "-" + millis'.<br> 766 * For example: 2003-245-14-34-52-224 767 * 768 * @return The CurrentTimeStamp value. 769 */ 770 public static String createCurrentDateTimeStamp() 771 { 772 Calendar calendar_ = Calendar.getInstance(); 773 774 return ""+ calendar_.get(Calendar.YEAR) + "-" + 775 calendar_.get(Calendar.DAY_OF_YEAR) + "-" +createCurrentTimeStamp(); 776 } 777 778 779 /** 780 * Creates a timestamp for the current time in the form of 'hour + "-" + min 781 * + "-" + sec + "-" + millis'. 782 * 783 * @return The CurrentTimeStamp value. 784 */ 785 public static String createCurrentTimeStamp() 786 { 787 String value = ""; 788 Calendar calendar_ = Calendar.getInstance(); 789 int currMillis = calendar_.get(calendar_.MILLISECOND); 790 String millis = String.valueOf(currMillis); 791 if (currMillis < 10) 792 { 793 millis = "00" + currMillis; 794 } 795 else if (currMillis < 100) 796 { 797 millis = "0" + currMillis; 798 } 799 int currSec = calendar_.get(calendar_.SECOND); 800 String sec = String.valueOf(currSec); 801 if (currSec < 10) 802 { 803 sec = "0" + currSec; 804 } 805 int currMin = calendar_.get(calendar_.MINUTE); 806 String min = String.valueOf(currMin); 807 if (currMin < 10) 808 { 809 min = "0" + currMin; 810 } 811 int currHr = calendar_.get(calendar_.HOUR_OF_DAY); 812 String hour = String.valueOf(currHr); 813 if (currHr < 10) 814 { 815 hour = "0" + currHr; 816 } 817 818 return (String) hour + "-" + min + "-" + sec + "-" + millis; 819 } 820 821 822 /** 823 * Creates a Timer timestamp from the current time to the passed startTime 824 * in the form of <BR> 825 * 'hour + "-" + min + "-" + sec + "-" + millis'. 826 * 827 * THIS METHOD IS NOT COMPLETED. IT DOES NOT WORK YET. 828 * 829 * @return The Timer Timestamp value. 830 */ 831 public static String createTimerTimeStamp(int startTimeMillis) 832 { 833 String value = ""; 834 Calendar calendar_ = Calendar.getInstance(); 835 int currMillis = calendar_.get(calendar_.MILLISECOND) - startTimeMillis; 836 String millis = String.valueOf(currMillis); 837 int currSec = calendar_.get(calendar_.SECOND); 838 String sec = String.valueOf(currSec); 839 int currMin = calendar_.get(calendar_.MINUTE); 840 String min = String.valueOf(currMin); 841 int currHr = calendar_.get(calendar_.HOUR_OF_DAY); 842 String hour = String.valueOf(currHr); 843 if (currMillis < 10) 844 { 845 millis = "00" + currMillis; 846 } 847 else if (currMillis < 100) 848 { 849 millis = "0" + currMillis; 850 } 851 if (currSec < 10) 852 { 853 sec = "0" + currSec; 854 } 855 if (currMin < 10) 856 { 857 min = "0" + currMin; 858 } 859 if (currHr < 10) 860 { 861 hour = "0" + currHr; 862 } 863 864 return (String) hour + "-" + min + "-" + sec + "-" + millis; 865 } 866 867 868 /** 869 * Returns the calling classes name. 870 @return the calling methods name. 871 */ 872 public static String getCurrentClassName() 873 { 874 Throwable t = new Throwable(); 875 StackTraceElement[] es = t.getStackTrace(); 876 StackTraceElement e = es[1]; 877 return e.getClassName(); 878 //return e.getLineNumber(); 879 //return e.getMethodName(); 880 } 881 882 883 /** 884 * Returns the calling methods name. 885 @return the calling methods name. 886 */ 887 public static String getCurrentMethodName() 888 { 889 Throwable t = new Throwable(); 890 StackTraceElement[] es = t.getStackTrace(); 891 StackTraceElement e = es[1]; 892 //return e.getClassName(); 893 //return e.getLineNumber(); 894 return e.getMethodName(); 895 } 896 897 898 /** 899 * A simple String token replacement routine. Replaces all occurences of the 900 * token parameter with the replacement value in the passed in sentence 901 * parameter. 902 * 903 * @param sentence The String to perform the token replacement on 904 * @param token the token String to seartch for and replace 905 * @param replacement the tokens replacement value 906 * @return The new token replaced string 907 */ 908 public static String tokenReplace(String sentence, 909 String token, 910 String replacement) 911 { 912 initUtil(); 913 final String methodName = CLASSNAME + ": tokenReplace"; 914 if (log_ != null) 915 { 916 log_.startMethod(methodName); 917 } 918 919 /* 920 int a = 0; 921 String retVal = ""; 922 while ((a = sentence.indexOf(token)) > -1) 923 { 924 retVal += sentence.substring(0, a) + replacement; 925 sentence = sentence.substring(a + token.length()); 926 927 } 928 929 retVal += sentence; 930 */ 931 if (log_ != null) 932 { 933 log_.endMethod(); 934 } 935 936 return sentence.replace(token,replacement); 937 } 938 939 940 /** 941 * Recursively deletes all the files in the spec'd directory and 942 * subdirectories, and then removes the dir. 943 * 944 * @param fileName The filename of the directory to delete. 945 */ 946 public static boolean removeDir(String fileName) 947 { 948 initUtil(); 949 boolean retVal = false; 950 File dirToDel = initDirFile(fileName); 951 if (dirToDel != null) 952 { 953 String[] files = dirToDel.list(); 954 File tempFile; 955 956 //loop through all the files in the dir DELETING them 957 for (int i = 0; i < files.length; i++) 958 { 959 tempFile = new File(fileName + File.separator + files[i]); 960 if (tempFile.isDirectory()) 961 { 962 // recurse on the subdirectory 963 removeDir(fileName + File.separator + files[i]); 964 } 965 else 966 { 967 // Delete all the files 968 /* Java 7 only Code 969 try 970 { 971 retVal = java.nio.file.Files.deleteIfExists(tempFile.toPath()); 972 } 973 catch(Exception ex) 974 { 975 //System.out.println( ); 976 //ex.printStackTrace(); 977 } 978 */ 979 retVal = tempFile.delete(); 980 //System.out.println((retVal?" Success":" Failed")); 981 } 982 } 983 retVal = dirToDel.delete(); 984 } 985 return retVal; 986 } 987 988 989 /** 990 * Deletes a file. 991 * 992 * @param fileName The filename to delete. 993 */ 994 public static boolean removeFile(String fileName) 995 { 996 initUtil(); 997 boolean retVal = false; 998 if (fileName != null) 999 { 1000 File tempFile = new File(fileName); 1001 1002 if (tempFile != null && tempFile.exists()) 1003 { 1004 /* Java 7 only Code 1005 //System.out.print( "Attempting to delete filename: "+fileName); 1006 try 1007 { 1008 retVal = java.nio.file.Files.deleteIfExists(tempFile.toPath()); 1009 } 1010 catch(Exception ex) 1011 { 1012 System.out.println( ); 1013 ex.printStackTrace(); 1014 } 1015 */ 1016 retVal = tempFile.delete(); 1017 System.out.println((retVal?" Success":" Failed")); 1018 } 1019 } 1020 return retVal; 1021 } 1022 1023 1024 /** 1025 * Deletes all files in the spec'd dir that are older than the spec'd 1026 * number of days. 1027 * 1028 * @param dirName The directory to parse for files to delete. 1029 * @param numDays The age of the files to delete. 1030 * @param recurse Do the removal recursively. 1031 */ 1032 public static boolean removeOldFiles(String dirName, 1033 int numDays, 1034 boolean recurse) 1035 { 1036 initUtil(); 1037 boolean retVal = false; 1038 final String methodName = CLASSNAME + ": removeOldFiles()"; 1039 if (log_ != null) 1040 { 1041 log_.startMethod(methodName); 1042 } 1043 File dirFile = new File(dirName); 1044 1045 if (dirFile.isDirectory() && dirFile.canRead()) 1046 { 1047 String[] waste = dirFile.list(); 1048 File tempFile = null; 1049 for (int i = 0; i < waste.length; i++) 1050 { 1051 tempFile = new File(dirName + File.separator + waste[i]); 1052 if (tempFile != null && !tempFile.isDirectory()) 1053 { 1054 // if file is older than numDays... delete it 1055 long fileAge = tempFile.lastModified(); 1056 Calendar rightNow = Calendar.getInstance(); 1057 long rightNowInMillis = rightNow.getTimeInMillis(); 1058 long numDaysInMillis = (new java.lang.Integer(numDays)).longValue() * 1059 24l * 60l * 60l * 1000l; 1060 if (rightNowInMillis - fileAge > numDaysInMillis) 1061 { 1062 //delete the file 1063 System.out.println("Deleting file "+ tempFile.getPath()); 1064 tempFile.delete(); 1065 } 1066 } 1067 else if (tempFile != null && recurse) 1068 { 1069 removeOldFiles(dirName + File.separator + waste[i], numDays, recurse); 1070 } 1071 } 1072 } 1073 1074 if (log_ != null) 1075 { 1076 log_.endMethod(); 1077 } 1078 return retVal; 1079 } 1080 1081 1082 /** 1083 * Obtains the bytes of data contained in all files in this dir 1084 * (and subdirs). 1085 * 1086 * @param fileName The filename of the directory . 1087 * 1088 * @return the size of the dir in bytes. 1089 */ 1090 public static long dirSizeOld(String fileName, boolean recurseSubdirs) 1091 { 1092 initUtil(); 1093 long retVal = 0L; 1094 File dirToCalc = initDirFile(fileName); 1095 1096 if (dirToCalc != null) 1097 { 1098 String[] files = dirToCalc.list(); 1099 File tempFile; 1100 1101 //loop through all the files in the dir 1102 if (files != null) 1103 { 1104 for (int i = 0; i < files.length; i++) 1105 { 1106 tempFile = new File(fileName + File.separator + files[i]); 1107 if (tempFile.isDirectory() && recurseSubdirs) 1108 { 1109 // recurse on the subdirectory 1110 retVal += dirSize(fileName + File.separator + files[i], true); 1111 } 1112 else 1113 { 1114 // add its size 1115 retVal += tempFile.length(); 1116 } 1117 } 1118 } 1119 else 1120 log_.minor("Problem reading Directory "+fileName); 1121 } 1122 return retVal; 1123 } 1124 1125 1126 /** 1127 * Obtains the bytes of data contained in all files in this dir 1128 * (and subdirs). 1129 * 1130 * @param fileName The filename of the directory . 1131 * 1132 * @return the size of the dir in bytes. 1133 */ 1134 public static long dirSize(String fileName, boolean recurseSubdirs) 1135 { 1136 initUtil(); 1137 long retVal = 0L; 1138 File dirToCalc = initDirFile(fileName); 1139 String fileDir; 1140 String dirName; 1141 if(fileName.lastIndexOf(SYSTEM_FILE_SEPERATOR )>-1) 1142 { 1143 fileDir = fileName.substring(0, fileName.lastIndexOf(SYSTEM_FILE_SEPERATOR )); 1144 dirName = fileName.substring(fileName.lastIndexOf(SYSTEM_FILE_SEPERATOR )+1).trim(); 1145 } 1146 else 1147 { 1148 fileDir = "."; 1149 dirName = fileName.trim(); 1150 } 1151 1152 if (dirToCalc != null) 1153 { 1154 String[] files = dirToCalc.list(); 1155 File tempFile; 1156 1157 try 1158 { 1159 java.nio.file.Path startPath = java.nio.file.FileSystems.getDefault().getPath(fileDir, dirName); 1160 final java.util.concurrent.atomic.AtomicLong size = new java.util.concurrent.atomic.AtomicLong(0); 1161 1162 //loop through all the files in the dir 1163 if (files != null) 1164 { 1165 for (int i = 0; i < files.length; i++) 1166 { 1167 tempFile = new File(fileName + File.separator + files[i]); 1168 if (tempFile.isDirectory() && recurseSubdirs) 1169 { 1170 // recurse on the subdirectory 1171 fileDir = fileName; 1172 dirName = files[i]; 1173 startPath = java.nio.file.FileSystems.getDefault().getPath(fileDir, dirName); 1174 size.addAndGet(java.nio.file.Files.size(startPath)); 1175 } 1176 else 1177 { 1178 // add its size 1179 size.addAndGet(tempFile.length()); 1180 } 1181 } 1182 } 1183 else 1184 log_.minor("Problem reading Directory "+fileName); 1185 1186 retVal = size.get(); 1187 } 1188 catch (java.nio.file.InvalidPathException invPathEx) 1189 { 1190 log_.minor("Problem reading Directory "+fileName); 1191 log_.minor(" fileDir "+fileDir); 1192 log_.minor(" dirName "+dirName); 1193 } 1194 catch (IOException invPathEx) 1195 { 1196 log_.minor("IOException reading Dir "+fileName); 1197 log_.minor(" fileDir "+fileDir); 1198 log_.minor(" dirName "+dirName); 1199 } 1200 } 1201 return retVal; 1202 } 1203 1204 1205 /** 1206 * Using the new NIO classes, obtains the bytes of data contained in all files in this dir 1207 * (and subdirs). 1208 * Implements <a href="https://stackoverflow.com/questions/7255592/get-file-directory-size-using-java-7-new-io">https://stackoverflow.com/questions/7255592/get-file-directory-size-using-java-7-new-io</a> 1209 * 1210 * @param fileName The filename of the directory . 1211 * @param recurseSubdirs include the subDirs in the result. 1212 * 1213 * @return the size of the dir in bytes. 1214 */ 1215 public static long dirSize2(String fileName, boolean recurseSubdirs) 1216 { 1217 initUtil(); 1218 long retVal = 0L; 1219 if(fileName.endsWith(SYSTEM_FILE_SEPERATOR)) fileName=fileName.substring(0, fileName.lastIndexOf(SYSTEM_FILE_SEPERATOR )); 1220 final String fileDir; 1221 final String dirName; 1222 if(fileName.lastIndexOf(SYSTEM_FILE_SEPERATOR )>-1) 1223 { 1224 fileDir = fileName.substring(0, fileName.lastIndexOf(SYSTEM_FILE_SEPERATOR )); 1225 dirName = fileName.substring(fileName.lastIndexOf(SYSTEM_FILE_SEPERATOR )+1).trim(); 1226 } 1227 else 1228 { 1229 fileDir = "."; 1230 dirName = fileName.trim(); 1231 } 1232 1233 try 1234 { 1235 java.nio.file.Path startPath = java.nio.file.FileSystems.getDefault().getPath(fileDir, dirName); 1236 final java.util.concurrent.atomic.AtomicLong size = new java.util.concurrent.atomic.AtomicLong(0); 1237 1238 System.out.println(" --> "+startPath.toString() +" ("+java.nio.file.Files.size(startPath)+")"); 1239 size.addAndGet(java.nio.file.Files.size(startPath)); 1240 //retVal += java.nio.file.Files.size(startPath); 1241 if(true && recurseSubdirs) 1242 { 1243 //System.out.println(" walkFileTree:"+fileDir+" , "+dirName); 1244 java.nio.file.Files.walkFileTree(startPath, 1245 new java.nio.file.SimpleFileVisitor<java.nio.file.Path>() { 1246 long totalSize = 0L; 1247 long fSize = 0L; 1248 @Override 1249 public java.nio.file.FileVisitResult visitFile(java.nio.file.Path filePath, 1250 java.nio.file.attribute.BasicFileAttributes attrs) throws IOException { 1251 //size.addAndGet(attrs.size()); 1252 fSize = java.nio.file.Files.size(filePath); 1253 //System.out.println(" > "+filePath.toString() +" ("+fSize+")"); 1254 size.addAndGet(fSize); 1255 totalSize+=fSize; 1256 return java.nio.file.FileVisitResult.CONTINUE; 1257 } 1258 1259 @Override 1260 public java.nio.file.FileVisitResult visitFileFailed(java.nio.file.Path filePath, IOException exc) throws IOException { 1261 // Skip folders that can't be traversed 1262 System.out.println("skipped: " + filePath + "\n e=" + exc); 1263 exc.printStackTrace(); 1264 //log_.minor("Problem reading Directory "+fileName); 1265 log_.minor(" fileDir "+fileDir); 1266 log_.minor(" dirName "+dirName); 1267 return java.nio.file.FileVisitResult.CONTINUE; 1268 } 1269 }); 1270 } 1271 1272 retVal = size.get(); 1273 } 1274 catch (java.nio.file.InvalidPathException invPathEx) 1275 { 1276 log_.minor("Problem reading Directory "+fileName); 1277 log_.minor(" fileDir "+fileDir); 1278 log_.minor(" dirName "+dirName); 1279 } 1280 catch (IOException invPathEx) 1281 { 1282 log_.minor("IOException reading Dir "+fileName); 1283 log_.minor(" fileDir "+fileDir); 1284 log_.minor(" dirName "+dirName); 1285 } 1286 1287 //System.out.println(" dirSize2="+retVal); 1288 return retVal; 1289 } 1290 1291 1292 /** 1293 * Helper method to copy a file 1294 * 1295 * @param from the from filename 1296 * @param to the to filename 1297 **/ 1298 public static void copyFile(String from, String to) throws IOException 1299 { 1300 File newFile = new File(to); 1301 if (newFile != null && newFile.exists()) 1302 newFile.delete(); 1303 (FileUtils.newFileUtils()).copyFile(from, to); 1304 } 1305 1306 1307 /** 1308 * Token replace method for a given filename (NO recursion) and then saves the file with the 1309 * swapped tokens. If you don't want to overwrite the original file make a 1310 * copy 1st and then call this method on the copy. 1311 * 1312 * @param file The file(name) to act on 1313 * @param token The search token (that will get replaced) 1314 * @param value The replacement string. 1315 */ 1316 public static void tokenReplaceInFile(String file, String token, String value) 1317 { 1318 tokenReplaceInFile( file, token, value, false); 1319 } 1320 1321 1322 /** 1323 * Token replace method for a given filename (and optional recusion into subdirs) and then saves the file with the 1324 * swapped tokens. If you don't want to overwrite the original file make a 1325 * copy 1st and then call this method on the copy. 1326 * 1327 * @param file The file(name) to act on 1328 * @param token The search token (that will get replaced) 1329 * @param value The replacement string. 1330 */ 1331 public static void tokenReplaceInFile(String file, String token, String value, boolean recurseSubdirs) 1332 { 1333 //boolean recurseSubdirs = true; 1334 // System.out.println("INTO tokenReplaceInFile("+file+", "+ token+", "+ value+", "+ recurseSubdirs+")"); 1335 1336 if (file!=null && !file.equals("")) 1337 { 1338 File rootFile = new File(file); 1339 //System.out.print("."); 1340 if( rootFile != null && !rootFile.isDirectory() && rootFile.canRead() ) 1341 { 1342 Replace replace = new Replace(); 1343 replace.setProject(new org.apache.tools.ant.Project()); 1344 replace.setFile(rootFile); 1345 replace.setToken(token); 1346 replace.setValue(value); 1347 replace.execute(); 1348 //System.out.println("~"); 1349 } 1350 else if (rootFile != null && rootFile.isDirectory() && rootFile.canRead() ) 1351 { 1352 if (recurseSubdirs) 1353 { 1354 System.out.println("Recursing into "+rootFile); 1355 String[] files = rootFile.list(); 1356 File tempFile; 1357 //if ( verbose ) 1358 //{ 1359 // System.out.println("Recursing into "+filename); 1360 //} 1361 1362 //loop through all the files in the dir 1363 for (int i = 0; files != null && i < files.length; i++) 1364 { 1365 System.out.println(" ... S&R "+rootFile.toString()+SYSTEM_FILE_SEPERATOR+files[i]); 1366 tokenReplaceInFile(rootFile.toString()+SYSTEM_FILE_SEPERATOR+files[i], token, value, recurseSubdirs); 1367 } 1368 } 1369 } 1370 } 1371 else 1372 System.out.println(" File is null - '"+(file!=null?file:"NULL")+"'"); 1373 }// -- tokenReplaceInFile() 1374 1375 1376 /** 1377 * Abstracts the compressing of a file with zip format - simly takes the file and wraps it whole into a zip file. 1378 * 1379 * @param s is the String to writeout 1380 * @param inFilename is the file name of the file to write the String into 1381 * @return if success, the full pathed filename is returned else null (default is infilename with the extension, after the last period, replaced with 'zip'. 1382 **/ 1383 public static String compressFileWithZip(String inFilename) 1384 { 1385 return compressFileWithZip(inFilename, 1386 (inFilename.substring(inFilename.lastIndexOf(".")+1).equalsIgnoreCase("kml") 1387 ? inFilename.substring(0,inFilename.lastIndexOf("."))+".kmz" 1388 : inFilename.substring(0,inFilename.lastIndexOf("."))+".zip" 1389 ) 1390 ); 1391 } 1392 1393 1394 /** 1395 * Abstracts the compressing of a file with zip format - simly takes the file and wraps it whole into a zip file. 1396 * 1397 * @param inFilenames is the input file to zip up 1398 * @param zipFilename is the file name of the resulting zipfile 1399 * @return if success, the full pathed filename is returned else null 1400 **/ 1401 public static String compressFileWithZip(String inFilename, String zipFilename) 1402 { 1403 String retVal = null; 1404 byte[] buffer = new byte[1024]; 1405 if (zipFilename==null || zipFilename.equals("")) 1406 zipFilename = inFilename.substring(0,inFilename.lastIndexOf("."))+".zip"; 1407 1408 1409 File tempFile = new File(inFilename); 1410 1411 if (tempFile != null && !tempFile.isDirectory() && tempFile.canRead()) 1412 try 1413 { 1414 FileOutputStream fos = new FileOutputStream(zipFilename); 1415 ZipOutputStream zos = new ZipOutputStream(fos); 1416 ZipEntry ze= new ZipEntry(inFilename); 1417 zos.putNextEntry(ze); 1418 FileInputStream in = new FileInputStream(inFilename); 1419 1420 int len; 1421 while ((len = in.read(buffer)) > 0) 1422 { 1423 zos.write(buffer, 0, len); 1424 } 1425 1426 in.close(); 1427 //in.finalize(); 1428 in = null; 1429 //tempFile.finalize(); 1430 tempFile = null; 1431 zos.closeEntry(); 1432 1433 //remember close it 1434 zos.close(); 1435 System.gc(); 1436 retVal = zipFilename; 1437 //System.out.println("Done"); 1438 1439 } 1440 catch(IOException ex) 1441 { 1442 ex.printStackTrace(); 1443 } 1444 1445 return retVal; 1446 } 1447 1448 1449 /** 1450 * Wrapper method to accept a dir or individual file in the passed in File 1451 * object AND then calls the method that writes the passed file/dir to this 1452 * MultiZip instances zip output stream. This is a recursive function. If the 1453 * passed File object is a file then it calls the function to write to zip 1454 * output stream. If it is a directory it gets the list of file objects in 1455 * the child directory and recurses on them. 1456 * 1457 * @param fo The File object to zip up (can be an actual file or dir). 1458 * @return the new length in bytes of the zipped file 1459 */ 1460 public static long recursiveBzip2(File fo) 1461 { 1462 //final String methodName = className_ + ": recursiveBzip2(File)"; 1463 //logger_.debug("Entering " + methodName); 1464 long retVal = 0L; 1465 /** The collection of filenames that actually got comp'd. */ 1466 Vector compressedFilenames = new Vector(); 1467 1468 String fullFilename = fo.getAbsolutePath().trim(); 1469 if (!fo.isDirectory()) 1470 { 1471 //logger_.info("Bzip2ing "+fullFilename); 1472 StringBuffer outLocation = new StringBuffer(); 1473 if (zippedOutputLocation_ != null) 1474 { 1475 // use the spec'd location 1476 String fileSep = System.getProperty("file.separator"); 1477 outLocation.append(zippedOutputLocation_); 1478 if (!zippedOutputLocation_.endsWith(fileSep) && 1479 !fullFilename.startsWith(fileSep)) 1480 { 1481 outLocation.append(fileSep); 1482 } 1483 outLocation.append(fullFilename); 1484 outLocation.append(".bz2"); 1485 //logger_.info("Bzip2ing " + fullFilename); 1486 //logger_.info(" to " + outLocation.toString()); 1487 File outFile = new File(outLocation.toString()); 1488 Util.ensureFolderExists(outFile.getParentFile()); 1489 try 1490 { 1491 BZip.compress(fo, outFile, 9); 1492 compressedFilenames.add(outLocation.toString()); 1493 retVal += outFile.length(); 1494 } 1495 catch (java.lang.ArithmeticException mathEx) 1496 { 1497 //logger_.error("BZip2 ERROR: " + fullFilename); 1498 //logger_.error(mathEx.getMessage()); 1499 errorFiles_.add(fullFilename); 1500 } 1501 } 1502 else 1503 { 1504 // zip it in place 1505 //logger_.info("Bzip2ing "+fullFilename); 1506 File outFile = new File(fullFilename + ".bz2"); 1507 Util.ensureFolderExists(outFile.getParentFile()); 1508 try 1509 { 1510 BZip.compress(fo, outFile, 9); 1511 compressedFilenames.add(fullFilename + ".bz2"); 1512 retVal += outFile.length(); 1513 } 1514 catch (java.lang.ArithmeticException mathEx) 1515 { 1516 //logger_.error("BZip2 ERROR: " + fullFilename); 1517 //logger_.error(mathEx.getMessage()); 1518 } 1519 } 1520 } 1521 else 1522 { 1523 //logger_.info("Recursing " + fo.getPath()); 1524 String srcFileNames[] = fo.list(); 1525 for (int i = 0; i < srcFileNames.length; i++) 1526 { 1527 retVal += recursiveBzip2(new File(fullFilename + 1528 File.separator + 1529 srcFileNames[i])); 1530 } 1531 } 1532 1533 //logger_.debug("Exiting " + methodName); 1534 return retVal; 1535 } 1536 1537 1538 /** 1539 * Abstracts the compressing of all files in a dir with zip format - simply takes the dirFiles and wraps it whole into a zip file. 1540 * IT DOES NOT keep the top level dirname. It acts on the files incside the dir. 1541 * 1542 * @param inDirName is the input dir to source the files from to zip up 1543 * @param zipFilename is the file name of the resulting zipfile 1544 * @return if success, the full pathed filename is returned else null 1545 **/ 1546 public static String compressDirFilesWithZip(String inDirName, String zipFilename) 1547 { 1548 String retVal = null; 1549 byte[] buffer = new byte[1024]; 1550 if (zipFilename==null || zipFilename.equals("")) 1551 zipFilename = inDirName+".zip"; 1552 1553 File tempFile = new File(inDirName); 1554 File currFileBuff = null; 1555 String currFileName = ""; 1556 1557 if (tempFile != null && tempFile.isDirectory() && tempFile.canRead()) 1558 try 1559 { 1560 FileOutputStream fos = new FileOutputStream(zipFilename); 1561 ZipOutputStream zos = new ZipOutputStream(fos); 1562 1563 // Loop through all files in Dir 1564 File[] dirFiles = new File(inDirName).listFiles(); 1565 for (File currFile: dirFiles) 1566 { 1567 currFileBuff = currFile; 1568 currFileName = currFile.getName(); 1569 1570 if (!currFile.isDirectory()) 1571 { 1572 ZipEntry ze= new ZipEntry(currFileName); 1573 //System.out.println("Adding file : " + currFile.getName()); 1574 zos.putNextEntry(ze); 1575 FileInputStream in = new FileInputStream(currFile); 1576 1577 int len; 1578 while ((len = in.read(buffer)) > 0) 1579 { 1580 zos.write(buffer, 0, len); 1581 } 1582 1583 in.close(); 1584 //in.finalize(); 1585 in = null; 1586 //tempFile.finalize(); 1587 } 1588 else 1589 { 1590 //System.out.println(" Calling addDirToArchive: " + currFile.getName()+ " , "+ 1591 // currFile.getAbsolutePath().substring(0,currFile.getAbsolutePath().indexOf(currFile.getName()))); 1592 addDirToArchive(zos, currFile, 1593 currFile.getAbsolutePath().substring(0,currFile.getAbsolutePath().indexOf(currFile.getName()))); 1594 } 1595 tempFile = null; 1596 zos.closeEntry(); 1597 } 1598 1599 //remember close it 1600 zos.close(); 1601 System.gc(); 1602 retVal = zipFilename; 1603 //System.out.println("Done"); 1604 1605 } 1606 catch(IOException ex) 1607 { 1608 System.err.println("compressDirFilesWithZip error: \n"+ 1609 " inDirName="+inDirName+"\n"+ 1610 " zipFilename="+zipFilename+"\n"+ 1611 " currFileName="+currFileName+"\n"); 1612 ex.printStackTrace(); 1613 } 1614 1615 return retVal; 1616 } 1617 1618 1619 /** 1620 * Simple recursive method that takes a Directory File and pumps its files into the passed in zip.<br /> 1621 * <b>It adds the files within 'srcFile' to the zip.</b><br /> 1622 * You also pass it the root path that will be chopped off the front of the embedded file paths 1623 * so everything ends up in a nice root of the zip file.<br /> 1624 * For example: <pre> 1625 * String inDirName = "c:\Users\JoeBlo\Docs\work\ProjectA"; 1626 * File dirFile = new File(inDirName); 1627 * 1628 * String zipFilename = "ProjectA_files.zip"; 1629 * FileOutputStream fos = new FileOutputStream(zipFilename); 1630 * ZipOutputStream zos = new ZipOutputStream(fos); 1631 * 1632 * // get the root part of the path to the file to zip up 1633 * // gets "c:\Users\JoeBlo\Docs\work" 1634 * String rootDirStr = dirFile.getAbsolutePath().substring(0,dirFile.getAbsolutePath().indexOf(dirFile.getName())); 1635 * 1636 * // create a zip with the files within 'dirFile' inside it 1637 * addDirToArchive(zos, dirFile, rootDirStr); 1638 * zos.close(); 1639 * </pre> 1640 * 1641 * @param zos is the already created ZipOutputStream to add to 1642 * @param srcFile is the Directory File to zip up its contained files 1643 * @param rootDir the root path that will be chopped off the front of the embedded file paths so everything ends up in a nice root of the zip file. 1644 **/ 1645 private static void addDirToArchive(ZipOutputStream zos, File srcFile, String rootDir) throws IOException 1646 { 1647 1648 File[] files = srcFile.listFiles(); 1649 1650 for (int i = 0; i < files.length; i++) 1651 { 1652 // if the file is directory, use recursion 1653 if (files[i].isDirectory()) 1654 { 1655 //System.out.println("Adding directory: " + files[i].getName()); 1656 addDirToArchive(zos, files[i], rootDir); 1657 continue; 1658 } 1659 1660 //try 1661 //{ 1662 //System.out.println(" Adding file: " + files[i].getAbsolutePath() + 1663 // " as "+ files[i].getAbsolutePath().substring(rootDir.length())); 1664 // create byte buffer 1665 byte[] buffer = new byte[1024]; 1666 1667 FileInputStream fis = new FileInputStream(files[i]); 1668 1669 // Zip files should use '/' as the file/directory seperator. 1670 // Google Earth (kmz) will not find sub dirs if using a '\' 1671 zos.putNextEntry(new ZipEntry(tokenReplace(files[i].getAbsolutePath().substring(rootDir.length()),"\\","/"))); 1672 1673 int length; 1674 while ((length = fis.read(buffer)) > 0) 1675 { 1676 zos.write(buffer, 0, length); 1677 } 1678 1679 zos.closeEntry(); 1680 // close the InputStream 1681 fis.close(); 1682 1683 //} 1684 //catch (IOException ioe) 1685 //{ 1686 // System.out.println("IOException :" + ioe); 1687 //} 1688 } 1689 } //addDirToArchive 1690 1691 1692 /** 1693 * Abstracts the loading of a resource image file from ca.bc.webarts.resources.images as an icon. 1694 * 1695 * @param name is the file name of the file to read 1696 **/ 1697 public static Icon loadIcon(String name) 1698 { 1699 return loadIcon("ca.bc.webarts.resources.images", name); 1700 } 1701 1702 /** 1703 * Abstracts the loading of a resource image file as an icon. 1704 * 1705 * @param name is the file name of the file to read 1706 **/ 1707 public static Icon loadIcon(String resourcePackageName, String name) 1708 { 1709 java.net.URL imgURL = Util.class.getResource("/"+tokenReplace(resourcePackageName,".","/")+"/" + name); 1710 if (imgURL != null) 1711 { 1712 return new ImageIcon(imgURL); 1713 } 1714 else 1715 { 1716 System.err.println("Unable to find " + "/"+tokenReplace(resourcePackageName,".","/")+"/" +name); 1717 return null; 1718 } 1719 } 1720 1721 1722 /** 1723 * Abstracts the writing of an InputSteam to a file. 1724 * 1725 * @param fileName is the file name of the file to write the String into 1726 * @return if success.. the full pathed filename is returned else null 1727 **/ 1728 public static String writeStringToFile(java.io.InputStream inputStream, String fileName) 1729 { 1730 String retVal = fileName; 1731 String props = "java.io.tmpdir"; 1732 String tempDir = System.getProperty("java.io.tmpdir"); 1733 try 1734 { 1735 // write the inputStream to a FileOutputStream 1736 OutputStream out = new FileOutputStream(new File(fileName)); 1737 1738 int read = 0; 1739 byte[] bytes = new byte[1024]; 1740 while ((read = inputStream.read(bytes)) != -1) 1741 { 1742 out.write(bytes, 0, read); 1743 } 1744 inputStream.close(); 1745 out.flush(); 1746 1747 System.out.println("New file created!"); 1748 } 1749 catch (IOException e) 1750 { 1751 System.out.println(e.getMessage()); 1752 retVal = ""; 1753 } 1754 return retVal; 1755 } 1756 1757 1758 /** 1759 * Abstracts the writing of an InputSteam to a file. 1760 * 1761 * @param fileName is the file name of the file to write the String into 1762 * @return if success.. the full pathed filename is returned else null 1763 **/ 1764 public static String writeStringToFile(java.io.ByteArrayInputStream inputStream, String fileName) 1765 { 1766 String retVal = fileName; 1767 String props = "java.io.tmpdir"; 1768 String tempDir = System.getProperty("java.io.tmpdir"); 1769 try 1770 { 1771 // write the inputStream to a FileOutputStream 1772 OutputStream out = new FileOutputStream(new File(fileName)); 1773 1774 int read = 0; 1775 byte[] bytes = new byte[1024]; 1776 while ((read = inputStream.read(bytes)) != -1) 1777 { 1778 out.write(bytes, 0, read); 1779 } 1780 inputStream.close(); 1781 out.flush(); 1782 1783 System.out.println("New file created!"); 1784 } 1785 catch (IOException e) 1786 { 1787 System.out.println(e.getMessage()); 1788 retVal = ""; 1789 } 1790 return retVal; 1791 } 1792 1793 1794 /** 1795 * Abstracts the appending of string to a file and creates it if not already there. 1796 * see http://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardOpenOption.html 1797 * 1798 * @param s is the String to writeout 1799 * @param fileName is the file name of the file to write the String into 1800 * @return if success.. the full pathed filename is returned else null 1801 **/ 1802 public static String appendStringToFile(String s, String fileName) 1803 { 1804 String retVal = null; 1805 PrintWriter out = null; 1806 BufferedWriter bufWriter = null; 1807 1808 try 1809 { 1810 bufWriter = 1811 Files.newBufferedWriter( 1812 Paths.get(fileName), 1813 Charset.forName("UTF8"), 1814 StandardOpenOption.WRITE, 1815 StandardOpenOption.APPEND, 1816 StandardOpenOption.CREATE); 1817 out = new PrintWriter(bufWriter, true); 1818 } 1819 catch(IOException e) 1820 { 1821 //Oh, no! Failed to create PrintWriter 1822 } 1823 1824 if (out!=null) 1825 { 1826 try 1827 { 1828 //After successful creation of PrintWriter 1829 out.print(s); 1830 retVal = fileName; 1831 } 1832 catch( Exception e ) 1833 { 1834 // File writing/opening failed at some stage. 1835 } 1836 finally 1837 { 1838 try 1839 { 1840 if( out != null ) 1841 { 1842 out.close(); // Will close bw and fw too 1843 } 1844 else if( bufWriter != null ) 1845 { 1846 bufWriter.close(); // Will close fw too 1847 } 1848 else 1849 { 1850 // Oh boy did it fail hard! :3 1851 } 1852 } 1853 catch( IOException e ) 1854 { 1855 // Closing the file writers failed for some obscure reason 1856 } 1857 } 1858 } 1859 return retVal; 1860 } 1861 1862 1863 /** 1864 * Abstracts the writing of string to a file. 1865 * 1866 * @param s is the String to writeout 1867 * @param fileName is the file name of the file to write the String into 1868 * @return if success.. the full pathed filename is returned else null 1869 **/ 1870 public static String writeStringToFile(String s, String fileName) 1871 {return writeStringToFile( s, fileName, false);} 1872 1873 1874 /** 1875 * Abstracts the writing of string to a (zip) file (Zip NOT IMPLEMENTED YET). 1876 * 1877 * @param s is the String to writeout 1878 * @param fileName is the file name of the file to write the String into 1879 * @param zipCompress boolean fall to compress with zip compression 1880 * @return if success.. the full pathed filename is returned else null 1881 **/ 1882 public static String writeStringToFile(String s, String fileName, boolean zipCompress) 1883 { 1884 String retVal = fileName; 1885 1886 try 1887 { 1888 // FileWriter was not closing the stream 1889 /* 1890 FileWriter f = new FileWriter(fileName); 1891 f.write(s); 1892 f.flush(); 1893 f.close(); 1894 f = null; 1895 */ 1896 FileOutputStream fos = new FileOutputStream(fileName); 1897 byte[] strBytes = s.getBytes(); 1898 fos.write(strBytes); 1899 fos.flush(); 1900 fos.close(); 1901 fos = null; 1902 System.gc(); // this is required because a bug in Java won't realease 1903 } 1904 catch (IOException ioEx) 1905 { 1906 System.out.println("\nERROR Writing file: "+fileName); 1907 retVal = null; 1908 } 1909 1910 return retVal; 1911 } 1912 1913 1914 /** 1915 * Abstracts the reading of a file and returns the contents as a String. 1916 * 1917 * @param fileName is the file naem to read into a String 1918 * @return the Text file contents as a String 1919 **/ 1920 public static String readFileToString(String fileName) 1921 { 1922 String stringLine; 1923 BufferedReader in; 1924 StringBuffer stringOut = new StringBuffer(""); 1925 try 1926 { 1927 in = new BufferedReader(new FileReader(fileName)); 1928 while ((stringLine = in.readLine()) != null) 1929 { 1930 stringOut.append(stringLine); 1931 stringOut.append(SYSTEM_LINE_SEPERATOR); 1932 } 1933 } 1934 catch (FileNotFoundException fnfEx) 1935 { 1936 System.out.println("Cannot find file: "+fileName); 1937 stringOut = new StringBuffer(""); 1938 } 1939 catch (IOException ioEx) 1940 { 1941 System.out.println("Error Reading File to String: "+fileName); 1942 stringOut = new StringBuffer(""); 1943 } 1944 1945 return stringOut.toString(); 1946 } 1947 1948 1949 /** 1950 * Searches the provided file for the search String. 1951 * 1952 * @param searchStr The searchString/regexp to search for. 1953 * @param filename The filename to search through. 1954 * @param verbose true will produce output to System.out just like the 1955 * UNIX find cmd 1956 * 1957 * @return an array of the matched lines 1958 */ 1959 public static String [] searchInFile(String searchStr, String filename, 1960 boolean verbose) 1961 { 1962 initUtil(); 1963 Vector <String> retVal = new Vector <String>(); 1964 BufferedReader in; 1965 RE expression = null; 1966 String s; 1967 int regExFlags = RE.REG_ICASE; 1968 int numExtraBeforeLines = 2; 1969 String [] extraBeforeLines = new String [numExtraBeforeLines]; 1970 int currLineNumber = 0; 1971 for (int i=0; i< numExtraBeforeLines ; i++) 1972 extraBeforeLines[i] = ""; 1973 1974 File rootFile = new File(filename); 1975 1976 if (rootFile != null && !rootFile.isDirectory()) 1977 { 1978 if(rootFile.canRead()) 1979 { 1980 try 1981 { 1982 in = new BufferedReader(new FileReader(filename)); 1983 currLineNumber = 0; 1984 while ((s = in.readLine()) != null) 1985 { 1986 currLineNumber++; 1987 expression = new RE(searchStr, regExFlags); 1988 if (expression.getMatch(s)!=null) 1989 { 1990 if ( verbose ) 1991 { 1992 System.out.println("FILE: "+filename); 1993 for (int i=0; i< numExtraBeforeLines ; i++) 1994 System.out.println(" "+currLineNumber+extraBeforeLines[i]); 1995 System.out.println(" "+currLineNumber + " "+s); 1996 System.out.println(); 1997 } 1998 retVal.addElement(s); 1999 } 2000 for (int i=0; i< numExtraBeforeLines-1 ; i++) 2001 extraBeforeLines[i] = extraBeforeLines[i+1]; 2002 extraBeforeLines[numExtraBeforeLines-1] = s; 2003 } 2004 in.close(); 2005 } 2006 catch (REException reEx) 2007 { 2008 reEx.printStackTrace(); 2009 } 2010 catch (FileNotFoundException fEx) 2011 { 2012 fEx.printStackTrace(); 2013 } 2014 catch (IOException ioEx) 2015 { 2016 ioEx.printStackTrace(); 2017 } 2018 2019 } 2020 } 2021 String [] rets = new String [retVal.size()]; 2022 2023 for (int i=0; i < retVal.size(); i++) 2024 { 2025 rets[i] = (String) retVal.elementAt(i); 2026 } 2027 return rets; 2028 } 2029 2030 2031 /** 2032 * Searches the provided file/directory (and subdirs) for the search String. 2033 * 2034 * @param searchStr The searchString/regexp to search for. 2035 * @param filename The filename/directoryName to search through. 2036 * @param recurseSubdirs Flags if the sub-dirs are searched. 2037 * @param fileRegExp Flags if 'fileName' should be regarded as a regular 2038 * expression. 2039 * @param verbose true will produce output to System.out just like the 2040 * UNIX find cmd 2041 * 2042 * @return a hash of the full cannoical paths/and a Vector of the lineNumbers 2043 * in that file 2044 */ 2045 public static Hashtable searchInFile(String searchStr, String filename, 2046 boolean recurseSubdirs, boolean fileRegExp, 2047 boolean verbose) 2048 { 2049 initUtil(); 2050 Hashtable retVal = new Hashtable(); 2051 Vector fileLineNumbers = new Vector(); 2052 BufferedReader in; 2053 RE expression = null; 2054 String s; 2055 int regExFlags = RE.REG_ICASE; 2056 int numExtraBeforeLines = 2; 2057 String [] extraBeforeLines = new String [numExtraBeforeLines]; 2058 String currFilename; 2059 int currLineNumber = 0; 2060 for (int i=0; i< numExtraBeforeLines ; i++) 2061 extraBeforeLines[i] = ""; 2062 2063 File rootFile = new File(filename); 2064 2065 if (rootFile != null && !rootFile.isDirectory()) 2066 { 2067 if(rootFile.canRead()) 2068 { 2069 currFilename = filename; 2070 try 2071 { 2072 in = new BufferedReader(new FileReader(currFilename)); 2073 fileLineNumbers.clear(); 2074 currLineNumber = 0; 2075 while ((s = in.readLine()) != null) 2076 { 2077 currLineNumber++; 2078 expression = new RE(searchStr, regExFlags); 2079 if (expression.getMatch(s)!=null) 2080 { 2081 if ( verbose ) 2082 { 2083 System.out.println("FILE: "+currFilename); 2084 for (int i=0; i< numExtraBeforeLines ; i++) 2085 System.out.println(" "+currLineNumber+extraBeforeLines[i]); 2086 System.out.println(" "+currLineNumber + " "+s); 2087 System.out.println(); 2088 } 2089 fileLineNumbers.add(new Integer(currLineNumber)); 2090 } 2091 for (int i=0; i< numExtraBeforeLines-1 ; i++) 2092 extraBeforeLines[i] = extraBeforeLines[i+1]; 2093 extraBeforeLines[numExtraBeforeLines-1] = s; 2094 } 2095 in.close(); 2096 if (fileLineNumbers.size() > 0) 2097 retVal.put(currFilename, fileLineNumbers.clone()); 2098 } 2099 catch (REException reEx) 2100 { 2101 reEx.printStackTrace(); 2102 } 2103 catch (FileNotFoundException fEx) 2104 { 2105 fEx.printStackTrace(); 2106 } 2107 catch (IOException ioEx) 2108 { 2109 ioEx.printStackTrace(); 2110 } 2111 } 2112 } 2113 else 2114 { 2115 // it is a directory so recurse on files if recursing flag is set 2116 if (recurseSubdirs) 2117 { 2118 String[] files = rootFile.list(); 2119 File tempFile; 2120 //if ( verbose ) 2121 //{ 2122 // System.out.println("Recursing into "+filename); 2123 //} 2124 2125 //loop through all the files in the dir 2126 Hashtable recursedHash = null; 2127 for (int i = 0; files != null && i < files.length; i++) 2128 { 2129 recursedHash = null; 2130 recursedHash = searchInFile(searchStr, 2131 filename + File.separator + files[i], 2132 recurseSubdirs, fileRegExp, verbose); 2133 if (recursedHash != null ) retVal.putAll(recursedHash); 2134 } 2135 } 2136 } 2137 2138 return retVal; 2139 } 2140 2141 2142 /** 2143 * Searches the provided directory (and subdirs) for the requested file. 2144 * 2145 * @param fileName The filename/regexp to search for. 2146 * @param directory The filename of the directory to delete. 2147 * @param recurseSubdirs Flags if the sub-dirs are searched. 2148 * @param regExp Flags if 'fileName' should be regarded as a regular 2149 * expression. 2150 * @param verbose true will produce output to System.out just like the 2151 * UNIX find cmd 2152 * 2153 * @return the full cannoical paths to the found files. 2154 */ 2155 public static Vector findFile(String fileName, String directory, 2156 boolean recurseSubdirs, boolean regExp, boolean verbose) 2157 { 2158 initUtil(); 2159 final String methodName = CLASSNAME + ": findFile(" + 2160 fileName + " " + directory + " " + recurseSubdirs+ " " + regExp+ " " + verbose+ " )"; 2161 if (log_ != null) log_.startMethod(methodName); 2162 Vector retVal = new Vector(); 2163 File dirToSearch = initDirFile(directory); 2164 2165 if (dirToSearch != null) 2166 { 2167 String[] files = dirToSearch.list(); 2168 File tempFile; 2169 if ( files!= null) log_.debug("Searching "+files.length +" files&dirs"); 2170 2171 //loop through all the files in the dir 2172 for (int i = 0; files != null && i < files.length; i++) 2173 { 2174 tempFile = new File(directory + File.separator + files[i]); 2175 if (tempFile.isDirectory() && recurseSubdirs) 2176 { 2177 // recurse on the subdirectory 2178 retVal.addAll(findFile(fileName, directory + File.separator + files[i], 2179 recurseSubdirs, regExp, verbose)); 2180 } 2181 else if (!tempFile.isDirectory()) 2182 { 2183 // does it match 2184 String absPath = tempFile.getAbsolutePath(); 2185 log_.debug("Searching "+absPath); 2186 2187 if (regExp) 2188 { 2189 try 2190 { 2191 RE expression = new RE(fileName); 2192 if (expression.isMatch(files[i])) 2193 { 2194 retVal.add(absPath); 2195 if (verbose) System.out.println(absPath); 2196 } 2197 } 2198 catch (REException reExp) 2199 { 2200 reExp.printStackTrace(); 2201 break; 2202 } 2203 } 2204 else if (files[i].trim().indexOf(fileName) >= 0) 2205 { 2206 retVal.add(absPath); 2207 if (verbose)System.out.println(absPath); 2208 } 2209 } 2210 } 2211 } 2212 if (log_ != null) log_.endMethod(methodName); 2213 return retVal; 2214 } 2215 2216 2217 /** 2218 * Initisalizes File only if it is directory.It is represented by the passed 2219 * in String. 2220 * 2221 * @param s the directory name to init as a File 2222 * @return An instatiated File object if the passed string is a dir, null 2223 * if not 2224 */ 2225 public static File initDirFile(String s) 2226 { 2227 initUtil(); 2228 File retVal = null; 2229 File dirFile = new File(s); 2230 if (dirFile.isDirectory() && dirFile.canRead()) 2231 { 2232 retVal = dirFile; 2233 } 2234 return retVal; 2235 } 2236 2237 2238public static String csvToJSON(String content, String separator){ 2239 2240 StringBuilder sb=new StringBuilder("[\n"); 2241 2242 String spacer = " "; 2243 String csv = content; 2244 String csvValues[] = csv.split("\n"); 2245 String header[]=csvValues[0].split("\\"+separator); 2246 2247 for(int i=1;i<csvValues.length;i++) 2248 { 2249 sb.append(spacer).append("{").append("\n"); 2250 String tmp[]=csvValues[i].split("\\"+separator); 2251 for(int j=0;j<tmp.length;j++) 2252 { 2253 sb.append(spacer).append(spacer).append("\"").append(header[j]).append("\":\"").append(tmp[j]).append("\""); 2254 if(j<tmp.length-1) 2255 { 2256 sb.append(",\n"); 2257 } 2258 else 2259 { 2260 sb.append("\n"); 2261 } 2262 } 2263 if(i<csvValues.length-1) 2264 { 2265 sb.append(spacer); 2266 sb.append("},\n"); 2267 } 2268 else{ 2269 sb.append(spacer); 2270 sb.append("}\n"); 2271 } 2272 } 2273 2274 sb.append("]"); 2275 2276 return sb.toString(); 2277} 2278 2279 2280 /** 2281 * Renames files to a more URL friendly format. 2282 * <P>It goes through each file in the specified directory and renames them 2283 * using the spacesToCapsInFileName method of renaming. 2284 * 2285 * @see #spacesToCapsInFileName(String) 2286 * @see #dirFile 2287 **/ 2288public static void spacesToCapsInDir(String dirName) 2289{ 2290 spacesToCapsInDir(dirName, true); 2291} 2292 2293 2294/** 2295 * Renames files to a more URL friendly format. 2296 * <P>It goes through each file in the specified directory and renames them 2297 * using the spacesToCapsInFileName method of renaming. 2298 * 2299 * @see #spacesToCapsInFileName(String) 2300 * @see #dirFile 2301 **/ 2302public static void spacesToCapsInDir(String dirName, boolean doUnderscores) 2303{ 2304 spacesToCapsInDir( dirName, doUnderscores, true); 2305} 2306 2307/** 2308 * Renames files to a more URL friendly format. 2309 * <P>It goes through each file in the specified directory and renames them 2310 * using the spacesToCapsInFileName method of renaming. 2311 * 2312 * @see #spacesToCapsInFileName(String) 2313 * @see #dirFile 2314 **/ 2315public static void spacesToCapsInDir(String dirName, boolean doUnderscores, boolean verboseOut) 2316{ 2317 File dirFile = initDirFile(dirName); 2318 //verboseOut = false; 2319 if (dirFile !=null) 2320 { 2321 String newDirName = dirName; 2322 boolean succeeded = false; 2323 // check and rename the initial dir 2324 if (dirFile.toString().indexOf(" ") != -1 || 2325 dirFile.toString().indexOf("_") != -1) 2326 { 2327 newDirName = spacesToCapsInString(dirFile.toString(), doUnderscores); 2328 if (verboseOut) System.out.println("Renaming: "+dirFile.toString()+" -> "+newDirName); 2329 //if (verboseOut) System.out.println(" "+dirFile.getAbsolutePath()+" "+spacesToCapsInString(dirFile.toString(), true)); 2330 succeeded = dirFile.renameTo(new File(newDirName)); 2331 } 2332 if (true) 2333 { 2334 succeeded = false; 2335 dirFile = initDirFile(newDirName); 2336 if (dirFile != null && 2337 dirFile.isDirectory() && 2338 dirFile.canRead() && 2339 newDirName != null ) 2340 { 2341 String [] fileName = dirFile.list(); 2342 if (verboseOut) System.out.print("Formatting dir="+dirFile.toString()); 2343 if (verboseOut) System.out.println(" It has "+fileName.length + " files."); 2344 File tempFile; 2345 for (int i=0;i< fileName.length;i++) 2346 { 2347 tempFile = new File(newDirName+File.separator+fileName[i]); 2348 2349 // do a depth first file rename of the subdir files 2350 if (tempFile != null && tempFile.isDirectory()) 2351 spacesToCapsInDir(tempFile.toString(), doUnderscores); 2352 String newName = spacesToCapsInString(fileName[i], doUnderscores); 2353 //if (verboseOut) System.out.println(fileName[i] +" .. " +newName); 2354 try 2355 { 2356 if (newName !="" && fileName[i].length() != newName.length()) 2357 { 2358 //if (verboseOut) System.out.println(i+".1) "+tempFile.toString()); 2359 //if (verboseOut) System.out.print(i+".2) "+newDirName+File.separator+newName); 2360 succeeded = tempFile.renameTo( 2361 new File(newDirName+File.separator+newName)); 2362 if (succeeded) 2363 if (verboseOut) System.out.println(" succeeded."); 2364 else 2365 if (verboseOut) System.out.println(""); 2366 File tempFile2 = new File(newDirName+File.separator+fileName[i]); 2367 if (tempFile2.exists() && 2368 tempFile.exists() && 2369 !newName.toUpperCase().equals(fileName[i].toUpperCase())) 2370 { 2371 tempFile2.delete(); 2372 } 2373 } 2374 } 2375 catch (SecurityException ex) 2376 { 2377 System.err.println("SecurityException " + ex); 2378 } 2379 catch (NullPointerException ex) 2380 { 2381 System.err.println("NullPointerException " + ex); 2382 } 2383 } //loop 2384 } 2385 } 2386 else 2387 { 2388 System.err.println("Could not rename "+dirName +" to "+newDirName); 2389 } 2390 } 2391 else 2392 System.err.println("Problems initing "+dirName ); 2393} 2394 2395 2396/** 2397 * Removes any space chars ' ' from a filename and Capitalizes the next char. 2398 * <P><B>NOTE:</B> The file is expected to be in 2399 * the current working directorydirectory 2400 * 2401 * @param fName a string representing the file to perform the action 2402 * @return the new filename representation 2403 **/ 2404public static String spacesToCapsInFileName(String fName) 2405{ 2406 String newName = ""; 2407 File tempFile; 2408 if (fName != null){ 2409 tempFile = new File(USERDIR+File.separator+fName); 2410 if(!tempFile.isDirectory()) 2411 { 2412 newName = spacesToCapsInString(fName); 2413 } 2414 } 2415 return newName; 2416} 2417 2418 2419/** 2420 * Removes any space chars ' ' from a String and Capitalizes the next char. 2421 * 2422 * @param fName a string perform the action 2423 * @return the new representation 2424 **/ 2425public static String spacesToCapsInString(String fName) 2426{ 2427 return spacesToCapsInString(fName, false); 2428} 2429 2430 2431/** 2432 * Removes any space chars ' ' from a String and Capitalizes the next char. 2433 * 2434 * @param fName a string perform the action 2435 * @param includeUnderscoreflag if '_' are also removed 2436 * @return the new representation 2437 **/ 2438public static String spacesToCapsInString(String fName, boolean includeUnderscore) 2439{ 2440 initUtil(); 2441 String newName = ""; 2442 boolean space = false; 2443 for (int j=0; j< fName.length(); j++) 2444 { 2445 char newChar = fName.charAt(j); 2446 if (newChar == ' ' || (newChar == '_' && includeUnderscore)) 2447 { 2448 // set the space flag so the next char can be cap'd 2449 space = true; 2450 } 2451 else 2452 { 2453 if (space) // was the last char a space??? 2454 { 2455 newName += String.valueOf(Character.toUpperCase(newChar)); 2456 } 2457 else 2458 { 2459 newName += String.valueOf(newChar); 2460 } 2461 space = false; 2462 } 2463 } 2464 return newName; 2465} 2466 2467///opt/jetty/baseDir/webapps/tunes/WEB-INF/classes 2468/** 2469 * Takes a string and adds a space in front of any capitalized char. 2470 * Basically the reverse of the method spacesToCapsInString. 2471 * 2472 * @param fName a string perform the action 2473 * @return the new representation 2474 **/ 2475public static String capsToSpacesInString(String fName) 2476{ 2477 initUtil(); 2478 StringBuffer newName = new StringBuffer(); 2479 char newChar; 2480 for (int j=0; j< fName.length(); j++) 2481 { 2482 newChar = fName.charAt(j); 2483 //System.out.println("char="+newChar + ((newChar=='(' || newChar=='[' || newChar=='{' || newChar=='<' || newChar=='&') ?" Yes":" No")); 2484 if (Character.isLetter(newChar)) 2485 { 2486 if(Character.isUpperCase(newChar)) 2487 { 2488 newName.append(" "); 2489 } 2490 } 2491 else if(newChar=='(' || newChar=='[' || newChar=='{' || newChar=='<' || newChar=='&') 2492 { 2493 newName.append(" "); 2494 } 2495 newName.append(String.valueOf(newChar)); 2496 } 2497 return newName.toString(); 2498} 2499 2500 2501/** 2502 * Takes a string and adds a space in front of any capitalized char. 2503 * Basically the reverse of the method spacesToCapsInString. 2504 * 2505 * @param fName a string perform the action 2506 * @return the new representation 2507 **/ 2508public static String capsToUndersInString(String fName) 2509{ 2510 initUtil(); 2511 StringBuffer newName = new StringBuffer(); 2512 char newChar; 2513 for (int j=0; j< fName.length(); j++) 2514 { 2515 newChar = fName.charAt(j); 2516 if (Character.isLetter(newChar) && Character.isUpperCase(newChar)) 2517 { 2518 newName.append("_"); 2519 } 2520 newName.append(String.valueOf(newChar)); 2521 } 2522 return newName.toString(); 2523} 2524 2525 2526 /** 2527 * Gives you the rightmost number of chars in a string. 2528 * 2529 * @param value is the string to pull result from 2530 * @param numChars the number of chars to return from the right side of 'value' 2531 * @return a string holding the rightmost number of chars in the passed in String 2532 **/ 2533 public static String right(String value, int numChars) 2534 { 2535 String retVal = value; 2536 if(value!=null && value.length()>= numChars) retVal = value.substring(value.length() - numChars); 2537 return retVal; 2538 } 2539 2540 2541 /** 2542 * Gives you the leftmost number of chars in a string. 2543 * 2544 * @param value is the string to pull result from 2545 * @param numChars the number of chars to return from the left side of 'value' 2546 * @return a string holding the leftmost number of chars in the passed in String 2547 **/ 2548 public static String left(String value, int numChars) 2549 { 2550 String retVal = value; 2551 if(value!=null && value.length()>= numChars) retVal = value.substring(0,numChars); 2552 return retVal; 2553 } 2554 2555 2556 /** 2557 * Searches the classpath for the specified filename and then returns the 2558 * full path that is used for it. 2559 * 2560 * @param filename to look for in the classpath 2561 * @param fallBack if the file is not found in classpath 2562 * @return the path description of the passed filename as found in 2563 * the classpath. 2564 */ 2565 public static String getFilePathFromClasspath(String filename, String fallBack) 2566 { 2567 initUtil(); 2568 final String methodName = CLASSNAME + 2569 ": getFilePathFromClasspath(String, String)"; 2570 if (log_ != null) 2571 { 2572 log_.startMethod(methodName); 2573 } 2574 String retVal = getFilePathFromClasspath(filename); 2575 //System.out.println("File In Classpath="+retVal); 2576 if (retVal == null || retVal.equals("")) 2577 { 2578 retVal = fallBack; 2579 } 2580 if (log_ != null) 2581 { 2582 log_.endMethod(); 2583 } 2584 //System.out.println("File In Classpath="+retVal); 2585 return retVal; 2586 } 2587 2588 2589 /** 2590 * Searches the classpath for the specified filename and then returns the 2591 * full path that is used for it. 2592 * 2593 * @param filename the filename to look for 2594 * @return the path description of the passed filename as found in 2595 * the classpath. 2596 */ 2597 public static String getFilePathFromClasspath(String filename) 2598 { 2599 initUtil(); 2600 final String methodName = CLASSNAME + ": getFilePathFromClasspath"; 2601 if (log_ != null) 2602 { 2603 log_.startMethod(methodName); 2604 } 2605 String retVal = ""; 2606 String pathSep = System.getProperty("path.separator"); 2607 if (CLASSPATH == null) 2608 { 2609 return ""; 2610 } 2611 int fileIndex = CLASSPATH.indexOf(filename); 2612 if (log_ != null) 2613 { 2614 log_.debug("Searching the Classpath for " + filename + 2615 " " + fileIndex); 2616 } 2617 if (fileIndex >= 0) 2618 { 2619 int startSpot = 0; 2620 int nextSpot = CLASSPATH.indexOf(pathSep); 2621 // the fileName is in the classpath 2622 if (log_ != null) 2623 { 2624 log_.debug("Start Looking at (" + startSpot + "," + nextSpot + ")"); 2625 } 2626 while ((nextSpot < fileIndex) && nextSpot != -1) 2627 { 2628 startSpot = nextSpot; 2629 nextSpot = CLASSPATH.indexOf(pathSep, startSpot + 1); 2630 if (log_ != null) 2631 { 2632 log_.debug(", (" + startSpot + "," + nextSpot + ")"); 2633 } 2634 } 2635 if (startSpot <= 0) 2636 { 2637 startSpot = -1; 2638 } 2639 if (nextSpot <= 0) 2640 { 2641 nextSpot = CLASSPATH.length(); 2642 } 2643 retVal = CLASSPATH.substring(startSpot + 1, nextSpot); 2644 } 2645 else 2646 if (log_ != null) 2647 { 2648 log_.minor(filename + " cannot be found in classpath."); 2649 } 2650 if (log_ != null) 2651 { 2652 log_.endMethod(); 2653 } 2654 return retVal; 2655 } 2656 2657 2658 /** 2659 * This method seeks out and returns the Parent Frame for a given component. 2660 * 2661 * @param c The Component to be used as the basis of the frame search 2662 * @return Frame The Frame that eventually holds the giuven Component. 2663 */ 2664 public static Frame getAncestorFrame(Component c) { 2665 Frame retVal = null; 2666 while ((c = c.getParent()) != null) 2667 if (c instanceof Frame) { 2668 retVal = (Frame) c; 2669 } 2670 return retVal; 2671 } 2672 2673 2674 /** 2675 * Calls the User Interface Manager and sets the look and feel setting based 2676 * on the parameter it is passed. Use the Class Contstants UTIL.METAL_LOOKANDFEEL, etc. 2677 * 2678 * @param i The new TheLookAndFeel value 2679 */ 2680 public static void setTheLookAndFeel(short i, Component comp) { 2681 /* Force SwingSet to come up in the Cross Platform L&F */ 2682 try { 2683 switch ((int)i){ 2684 case METAL_LOOKANDFEEL: 2685 // If you want the Java L&F 2686 UIManager.setLookAndFeel(metalClassName); 2687 log_.debug("Setting the Java L&F"); 2688 break; 2689 case WINDOZE_LOOKANDFEEL: 2690 // If you want the System L&F 2691 UIManager.setLookAndFeel(windowsClassName);//UIManager.getSystemLookAndFeelClassName()); 2692 log_.debug("Setting the System L&F"); 2693 break; 2694 case MOTIF_LOOKANDFEEL: 2695 // If you want the Motif L&F 2696 UIManager.setLookAndFeel(motifClassName); 2697 log_.debug("Setting the Motif L&F"); 2698 break; 2699 case MAC_LOOKANDFEEL: 2700 // If you want the Mac L&F 2701 UIManager.setLookAndFeel(macClassName); 2702 log_.debug("Setting the Mac L&F"); 2703 break; 2704 default: 2705 // defaults to Java L&F 2706 UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); 2707 log_.debug("Setting the Java L&F"); 2708 } 2709 SwingUtilities.updateComponentTreeUI(Util.getAncestorFrame(comp)); 2710 } 2711 catch (Exception exc) 2712 { 2713 System.err.println("Error loading L&F: " + exc); 2714 } 2715 } 2716 2717 2718 /** 2719 * Loads the requested Image filename from the specified jarfile. 2720 * 2721 * @param imageFilename the filename in the jarfile to use as the basis for 2722 * the Image to retrieve. 2723 * @param jarFilename the jar file to look through for the image. 2724 * @return Image the Image loaded from the filename spec'd as 2725 * an imput param, It returns null if it cannot retrieve the Image. 2726 */ 2727 public static Image loadImage(String imageFilename, String jarFilename) 2728 { 2729 initUtil(); 2730 final String methodName = CLASSNAME + ": loadImage(String, String)"; 2731 if (log_ != null) 2732 { 2733 log_.startMethod(methodName); 2734 } 2735 if (log_ != null) 2736 { 2737 log_.debug("Loading Imagename " + imageFilename); 2738 } 2739 Image retVal = (new ImageIcon(Util.class.getResource("/" + imageFilename))). 2740 getImage(); 2741 /* 2742 * String iconJarFileName = jarFilename; //getFilePathFromClasspath(jarFilename); 2743 * if(log_!=null) log_.debug("Loading Imagename "+imageFilename+" from Jarfile "+jarFilename); 2744 * InputStream in = null; 2745 * JarEntry tempJarEntry = null; 2746 * byte [] imageBytes; 2747 * long imageFileSize = 0l; 2748 * int bytesRead = 0; 2749 * try 2750 * { 2751 * JarFile jar = new JarFile(iconJarFileName, false); 2752 * tempJarEntry = jar.getJarEntry(imageFilename); 2753 * in = jar.getInputStream(tempJarEntry); 2754 * imageFileSize = tempJarEntry.getSize(); 2755 * imageBytes = new byte[(int)imageFileSize]; 2756 * for (int j=0;j<imageFileSize;j++) 2757 * imageBytes[j] = new Integer(in.read()).byteValue(); 2758 * if(log_!=null) log_.debug("Loaded "+imageFileSize+" Bytes."); 2759 * retVal = (Toolkit.getDefaultToolkit()).createImage(imageBytes); 2760 * } 2761 * catch (NullPointerException fEx) 2762 * { 2763 * System.out.println("No graphicJarEntry NullPointerException " + 2764 * imageFilename); 2765 * } 2766 * catch (FileNotFoundException fEx) 2767 * { 2768 * System.out.println("graphic FileNotFoundException " +imageFilename); 2769 * } 2770 * catch (IOException ioEx) 2771 * { 2772 * System.out.println("graphic FileNotFoundException " +imageFilename); 2773 * } 2774 * catch (SecurityException secEx) 2775 * { 2776 * System.out.println("graphic SecurityException " +imageFilename); 2777 * } 2778 */ 2779 if (log_ != null) 2780 { 2781 log_.endMethod(); 2782 } 2783 return retVal; 2784 } 2785 2786 2787 /** 2788 * Loads the requested Image filename from the classpath. 2789 * 2790 * @param imageFilename the filename in the jarfile to use as the basis for 2791 * the Image to retrieve. 2792 * @return Image the Image loaded from the filename spec'd as 2793 * an imput param, It returns null if it cannot retrieve the Image. 2794 */ 2795 public static Image loadImage(String imageFilename) 2796 { 2797 initUtil(); 2798 final String methodName = CLASSNAME + ": loadImage()"; 2799 if (log_ != null) 2800 { 2801 log_.startMethod(methodName); 2802 } 2803 if (log_ != null) 2804 { 2805 log_.debug("Loading Imagename " + imageFilename); 2806 } 2807 //System.out.println("Loading Imagename "+imageFilename); 2808 URL resourceUrl = Util.class.getResource(imageFilename); 2809 Image retVal = null; 2810 if (resourceUrl != null) 2811 { 2812 retVal = (new ImageIcon(resourceUrl)).getImage(); 2813 } 2814 else 2815 if (log_ != null) 2816 { 2817 log_.minor("DID NOT Get the Resource URL for :" + imageFilename); 2818 } 2819 2820 if (retVal == null) 2821 { 2822 if (log_ != null) 2823 { 2824 log_.minor("Could NOT create Image for " + imageFilename); 2825 } 2826 } 2827 if (log_ != null) 2828 { 2829 log_.endMethod(); 2830 } 2831 return retVal; 2832 } 2833 2834 2835 /** 2836 * A method to simply abstract the Try/Catch required to put the current 2837 * thread to sleep for the specified time in ms. 2838 * 2839 * @param waitTime the sleep time in milli seconds (ms). 2840 * @return boolean value specifying if the sleep completed (true) or 2841 * was interupted (false). 2842 */ 2843 public static boolean sleep(long waitTime) 2844 { 2845 final String methodName = CLASSNAME + ": sleep(Long)"; 2846 if (log_ != null) 2847 { 2848 //log_.startMethod(methodName); 2849 } 2850 boolean retVal = true; 2851 /* 2852 * BLOCK for the spec'd time 2853 */ 2854 try 2855 { 2856 Thread.sleep(waitTime); 2857 } 2858 catch (InterruptedException iex) 2859 { 2860 retVal = false; 2861 } 2862 if (log_ != null) 2863 { 2864 //log_.endMethod(); 2865 } 2866 return retVal; 2867 } 2868 2869 2870 /** 2871 * A method to simply sort a Hashtable holding a String key & Integer values) by its Highest To Lowest values 2872 * then alphabetical (low to high) for the keys. Default is to sort Integer Highest to lowest. 2873 * 2874 * @param hIn the original hashtable to sort. 2875 * @return the sorted ArrayList 2876 */ 2877 public static ArrayList<Set<Map.Entry<String, Integer>>> sortByValues(Hashtable<String, Integer> hIn) 2878 { 2879 final String methodName = CLASSNAME + ": sortByValues(Hashtable)"; 2880 if (log_ != null) 2881 { 2882 //log_.startMethod(methodName); 2883 } 2884 return sortByValues(hIn, false); 2885 } 2886 2887 2888 /** 2889 * A method to simply sort a Hashtable(holding a String key & Integer values) by its Integer values 2890 * then by its String keys. The boolean ascendingOrder controls direction of sort: 2891 * false means descending Integer sort (High to low) then Alpahbetical -low to Highest 2892 * true means ascending Integer sort then Alpahbetical -Highest To Lowest. 2893 * 2894 * @param hIn the original hashtable to sort. 2895 * @ param ascendingOrder true will reverse the Order of the sorting to Integervalues low to high then String keys High to low (Reverse Alpha) 2896 * @return the sorted ArrayList 2897 */ 2898 public static ArrayList<Set<Map.Entry<String, Integer>>> sortByValues(Hashtable<String, Integer> hIn, final boolean ascendingOrder) 2899 { 2900 final String methodName = CLASSNAME + ": sortByValues(Hashtable)"; 2901 if (log_ != null) 2902 { 2903 //log_.startMethod(methodName); 2904 } 2905 boolean debugOut = false; 2906 2907 Hashtable<Object, Object> retVal = null; 2908 //Put keys and values in to an arraylist using entryset 2909 ArrayList myArrayList=new ArrayList(hIn.entrySet()); 2910 if (debugOut) System.out.println("\n\nsorting hashtable: "+hIn.toString()); 2911 if (debugOut) System.out.println("\n\nsorting ArrayList: "+myArrayList.toString()); 2912 2913 //Sort the values based on values first and then keys. 2914 Collections.sort(myArrayList, 2915 new Comparator() 2916 { 2917 public int compare(Object obj1, Object obj2) 2918 { 2919 int result=0; 2920 Map.Entry e1 = (Map.Entry)obj1 ; 2921 Map.Entry e2 = (Map.Entry)obj2 ;//Sort based on values. 2922 2923 Integer value1 = (Integer)e1.getValue(); 2924 Integer value2 = (Integer)e2.getValue(); 2925 if(value1.compareTo(value2)==0) // if the Integers are the same then sort by the String 2926 { 2927 String word1=(String)e1.getKey(); 2928 String word2=(String)e2.getKey(); 2929 if (ascendingOrder) 2930 { 2931 result=word2.compareToIgnoreCase(word1); 2932 } 2933 else 2934 { 2935 //Sort String in an alphabetical order 2936 result=word1.compareToIgnoreCase(word2); 2937 } 2938 } 2939 else 2940 { 2941 if (ascendingOrder) 2942 { 2943 //Sort values in a ascending order 2944 result=value1.compareTo( value2 ); 2945 } 2946 else 2947 { 2948 //Sort values in a descending order 2949 result=value2.compareTo( value1 ); 2950 } 2951 } 2952 return result; 2953 } // compare 2954 } // MyValueComparator 2955 ); //Collections.sort 2956 2957 if (debugOut) 2958 { 2959 //Show sorted results 2960 Iterator itr=myArrayList.iterator(); 2961 String key=""; 2962 int value=0; 2963 int cnt=0; 2964 while(itr.hasNext()) 2965 { 2966 cnt++; 2967 Map.Entry e=(Map.Entry)itr.next(); 2968 2969 key = (String)e.getKey(); 2970 value = ((Integer)e.getValue()).intValue(); 2971 2972 System.out.println(key+", "+value); 2973 } 2974 } 2975 if (log_ != null) 2976 { 2977 log_.endMethod(); 2978 } 2979 return myArrayList ; 2980 } 2981 2982 2983 /** 2984 * Encapsulates the showing of the FileChooser dialog and returns a String 2985 * representing the absolute path. <P> 2986 * 2987 * NO file filters will be used and NO directory selection is allowed. 2988 * 2989 * @param parent the owner of this dialog (generally just send this) 2990 * @param startPath the dir to start the file chooser dialog from 2991 * @return the absolute path of the chosen file. 2992 */ 2993 public static String chooseAFilename(Component parent, String startPath) 2994 { 2995 initUtil(); 2996 final String methodName = CLASSNAME + ": chooseAFilename(String)"; 2997 if (log_ != null) 2998 { 2999 log_.startMethod(methodName); 3000 } 3001 if (log_ != null) 3002 { 3003 log_.endMethod(); 3004 } 3005 return chooseAFilename(parent, startPath, null, false); 3006 } 3007 3008 3009 /** 3010 * Encapsulates the showing of the FileChooser dialog and returns a String 3011 * representing the absolute path.<P> 3012 * 3013 * This method requires all the config parms specified by the 3014 * ExampleFileFilter. 3015 * 3016 * @param parent the owner of this dialog (generally just send this) 3017 * @param startPath the dir to start the file chooser dialog from 3018 * @param filters an array holding the Filters to use in the dialog 3019 * @param filesAndDirs specs if the user will be allowed to choose both 3020 * files or dirs. 3021 * @return the absolute path of the chosen file. 3022 */ 3023 public static String chooseAFilename(Component parent, 3024 String startPath, 3025 ExampleFileFilter[] filters, 3026 boolean filesAndDirs 3027 ) 3028 { 3029 return chooseAFilename(parent, startPath, filters, 3030 filesAndDirs, Util.OPEN_DIALOG); 3031 } 3032 3033 3034 /** 3035 * Encapsulates the showing of the FileChooser dialog and returns a String 3036 * representing the absolute path.<P> 3037 * 3038 * This method requires all the config parms specified by the 3039 * ExampleFileFilter. 3040 * 3041 * @param parent the owner of this dialog (generally just send this) 3042 * @param startPath the dir to start the file chooser dialog from 3043 * @param filters an array holding the Filters to use in the dialog 3044 * @param filesAndDirs specs if the user will be allowed to choose both 3045 * files or dirs. 3046 * @param openOrClose Description of the Parameter 3047 * @return the absolute path of the chosen file. 3048 */ 3049 public static String chooseAFilename(Component parent, 3050 String startPath, 3051 ExampleFileFilter[] filters, 3052 boolean filesAndDirs, 3053 short openOrClose) 3054 { 3055 initUtil(); 3056 final String methodName = CLASSNAME + 3057 ": chooseAFilename(String,ExampleFileFilter[],boolean)"; 3058 if (log_ != null) 3059 { 3060 log_.startMethod(methodName); 3061 } 3062 String retVal = ""; 3063 JFileChooser chooser = new JFileChooser(); 3064 if (filters != null && filters.length > 0) 3065 { 3066 for (int i = 0; i < filters.length; i++) 3067 { 3068 chooser.addChoosableFileFilter(filters[i]); 3069 } 3070 chooser.setFileFilter(filters[0]); 3071 } 3072 if (filesAndDirs) 3073 { 3074 chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); 3075 } 3076 if (openOrClose == SAVE_DIALOG) 3077 { 3078 if (chooser.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) 3079 { 3080 retVal = chooser.getSelectedFile().getAbsolutePath(); 3081 System.out.println("You chose this file: " + retVal); 3082 } 3083 } 3084 else 3085 { 3086 if (chooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) 3087 { 3088 retVal = chooser.getSelectedFile().getAbsolutePath(); 3089 System.out.println("You chose this file: " + retVal); 3090 } 3091 } 3092 if (log_ != null) 3093 { 3094 log_.endMethod(); 3095 } 3096 return retVal; 3097 } 3098 3099 3100 /** 3101 * Converts an Absolute path to a relative path from the VM Working Dir. 3102 * 3103 * @param absPath is the File to use to to convert 3104 * @return null if can't be done, otherwise it returns the relative path. 3105 */ 3106 public static String absoluteToPwdRelativePath(File absPath) 3107 { 3108 String retVal = null; 3109 if (absPath !=null) 3110 retVal = absoluteToPwdRelativePath(absPath.getAbsolutePath()); 3111 3112 return retVal; 3113 } 3114 3115 3116 /** 3117 * Converts an Absolute path to a relative path from the VM Working Dir. 3118 * 3119 * @param absPath is the absolute path to convert 3120 * @return null if can't be done, otherwise it returns the relative path. 3121 */ 3122 public static String absoluteToPwdRelativePath(String absPath) 3123 { 3124 initUtil(); 3125 final String methodName = CLASSNAME + ": getFileDir(String)"; 3126 if (log_ != null) 3127 { 3128 log_.startMethod(methodName); 3129 } 3130 String retVal = null; 3131 3132 String pwd = System.getProperty("user.dir"); 3133 if (absPath != null && absPath.indexOf(pwd) != -1) 3134 { 3135 // Found It 3136 retVal = absPath.substring(pwd.length()+1); 3137 } 3138 3139 if (log_ != null) 3140 { 3141 log_.endMethod(); 3142 } 3143 return retVal; 3144 } 3145 3146 3147 /** 3148 * Removes a '/..' from the filename string and returns the corrected dir 3149 * name reference. For Example : pass it "/a/b/c/../d" it returns "/a/b/d". 3150 * 3151 * @param path is the absolute path to convert 3152 * @return null if can't be done, otherwise it returns the corrected path. 3153 */ 3154 public static String removeParentRelativeReference(String path) 3155 { 3156 initUtil(); 3157 final String methodName = CLASSNAME + ": removeParentRelativeReference(String)"; 3158 if (log_ != null) 3159 { 3160 log_.startMethod(methodName); 3161 } 3162 String retVal = path; 3163 String parentRefString = SYSTEM_FILE_SEPERATOR+".."; 3164 int spot = -1; 3165 int removeSpot = -1; 3166 3167 //System.out.println("Path = "+path); 3168 //System.out.println("parentRef = "+parentRefString); 3169 if (path != null) 3170 { 3171 spot = retVal.indexOf(parentRefString); 3172 while (spot != -1) 3173 { 3174 // Found It 3175 removeSpot = retVal.substring(0,spot-1).lastIndexOf(SYSTEM_FILE_SEPERATOR); 3176 retVal = retVal.substring(0,removeSpot)+retVal.substring(spot+3); 3177 3178 //System.out.println("spot = "+spot); 3179 //System.out.println("removeSpot = "+removeSpot); 3180 //System.out.println("retVal = "+retVal); 3181 3182 spot = retVal.indexOf(parentRefString); 3183 } 3184 } 3185 3186 if (log_ != null) 3187 { 3188 log_.endMethod(); 3189 } 3190 return retVal; 3191 } 3192 3193 3194 /** 3195 * Creates a File representing the Dir for the specified filename string. 3196 * 3197 * @param fileString is the filename to get the dir for 3198 */ 3199 public static File getFileDir(String fileString) 3200 { 3201 initUtil(); 3202 final String methodName = CLASSNAME + ": getFileDir(String)"; 3203 if (log_ != null) 3204 { 3205 log_.startMethod(methodName); 3206 } 3207 File retVal = null; 3208 if (fileString != null && 3209 !fileString.equals("")) 3210 { 3211 int endSpot = fileString.lastIndexOf(File.separator); 3212 if(endSpot >=0) 3213 { 3214 retVal = new File(fileString.substring(0,endSpot)); 3215 } 3216 else 3217 { 3218 retVal = new File("."); 3219 } 3220 } 3221 3222 if (log_ != null) 3223 { 3224 log_.endMethod(); 3225 } 3226 return retVal; 3227 } 3228 3229 3230 /** 3231 * Gets a string representing the Dir for the specified filename string. 3232 * 3233 * @param fileString is the filename to get the dir for 3234 */ 3235 public static String getFileDirStr(String fileString) 3236 { 3237 initUtil(); 3238 final String methodName = CLASSNAME + ": getFileDirStr(String)"; 3239 if (log_ != null) 3240 { 3241 log_.startMethod(methodName); 3242 } 3243 String retVal = null; 3244 if (fileString != null && 3245 !fileString.equals("")) 3246 { 3247 int endSpot = fileString.lastIndexOf(File.separator); 3248 if(endSpot >=0) 3249 { 3250 retVal = fileString.substring(0,endSpot); 3251 } 3252 else 3253 { 3254 retVal = "."; 3255 } 3256 } 3257 3258 if (log_ != null) 3259 { 3260 log_.endMethod(); 3261 } 3262 return retVal; 3263 } 3264 3265 3266 /** 3267 * Creates a URL for the specified filename string. 3268 * 3269 * @param fileString is the filename to turn into a file://URL 3270 * @return the converted file://URL 3271 */ 3272 public static URL getFileBaseURL(String fileString) 3273 { 3274 initUtil(); 3275 final String methodName = CLASSNAME + ": getFileBaseURL(String)"; 3276 if (log_ != null) 3277 { 3278 log_.startMethod(methodName); 3279 } 3280 /* 3281 * because this is an application the codebase does not work 3282 */ 3283 /* 3284 * we have to create the codeBase URL from the userDir 3285 */ 3286 URL convertedURL = null; 3287 int i = 0; 3288 String tempPath = null; 3289 try 3290 { 3291 // 1st see if the string is already a URL 3292 convertedURL = new URL(fileString); 3293 } 3294 catch (MalformedURLException ex) 3295 { 3296 try 3297 { 3298 try 3299 { 3300 /* 3301 * 1st test if this is a DOS/OS/2 style path with a drive letter 3302 */ 3303 if (fileString.charAt(1) == ':') 3304 { 3305 tempPath = fileString.substring(0, 1); 3306 tempPath += ":"; 3307 /* 3308 * Replace the file separators with the forward slash 3309 */ 3310 for (i = 2; i <= fileString.length() - 1; i++) 3311 { 3312 if (fileString.charAt(i) != SYSTEM_FILE_SEPERATOR.charAt(0)) 3313 { 3314 tempPath += fileString.substring(i, i + 1); 3315 } 3316 else 3317 { 3318 tempPath += "/"; 3319 } 3320 } 3321 //System.out.print("Appears to be a DOS or OS/2 filesystem - "); 3322 convertedURL = new URL("FILE:////" +encodeToURL( tempPath)); 3323 //System.out.println(""+ convertedURL); 3324 } 3325 else 3326 { 3327 /* 3328 * 2nd test if this is a UN*x style path without a drive letter 3329 */ 3330 if (fileString.charAt(0) == '/') 3331 { 3332 //System.out.println("Appears to be a Unix filesystem"); 3333 //convertedURL = new URL("file://" + fileString); 3334 convertedURL = new URL("file","", encodeToURL(fileString)); 3335 } 3336 else 3337 { 3338 //System.out.println("Appears to be a relative filesystem"); 3339 convertedURL = new URL("file://./"); 3340 convertedURL = new URL("file","", encodeToURL(fileString)); 3341 } 3342 } 3343 // System.out.println("APP convertedURL=" + convertedURL.toString()); 3344 } 3345 catch (java.net.MalformedURLException t) 3346 { 3347 System.out.println("caught java.net.MalformedURLException: " + t + 3348 "Cannot retrieve User Directory"); 3349 t.printStackTrace(); 3350 } 3351 } 3352 catch (StringIndexOutOfBoundsException t) 3353 { 3354 System.out.println("caught StringIndexOutOfBoundsException: " + t + 3355 "Cannot retrieve User Directory"); 3356 t.printStackTrace(); 3357 } 3358 } 3359 if (log_ != null) 3360 { 3361 log_.endMethod(); 3362 } 3363 return convertedURL; 3364 } 3365 3366 3367 /** 3368 * Creates a URL[] for the given Strings. 3369 * 3370 * @param fileStrings Description of Parameter 3371 * @return The FileBaseURLs value 3372 */ 3373 public static URL[] getFileBaseURLs(String[] fileStrings) 3374 { 3375 final String methodName = CLASSNAME + ": getFileBaseURLs(String[])"; 3376 initUtil(); 3377 if (log_ != null) 3378 { 3379 log_.startMethod(methodName); 3380 } 3381 URL[] retVal = null; 3382 if (fileStrings != null) 3383 { 3384 int size = fileStrings.length; 3385 // System.out.println("Into getFileBaseURLs " + size); 3386 retVal = new URL[size]; 3387 for (int i = 0; i < size; i++) 3388 { 3389 retVal[i] = getFileBaseURL(fileStrings[i]); 3390 } 3391 } 3392 if (log_ != null) 3393 { 3394 log_.endMethod(); 3395 } 3396 3397 return retVal; 3398 } 3399 3400 3401 3402 /** 3403 * Encode a string to the "x-www-form-urlencoded" form, enhanced 3404 * with the UTF-8-in-URL proposal. This is what happens: 3405 * 3406 * <ul> 3407 * <li><p>The ASCII characters 'a' through 'z', 'A' through 'Z', 3408 * and '0' through '9' remain the same. 3409 * 3410 * <li><p>The unreserved characters - _ . ! ~ * ' ( ) remain the same. 3411 * 3412 * <li><p>The space character ' ' is converted into a plus sign '+'. 3413 * 3414 * <li><p>All other ASCII characters are converted into the 3415 * 3-character string "%xy", where xy is 3416 * the two-digit hexadecimal representation of the character 3417 * code 3418 * 3419 * <li><p>All non-ASCII characters are encoded in two steps: first 3420 * to a sequence of 2 or 3 bytes, using the UTF-8 algorithm; 3421 * secondly each of these bytes is encoded as "%xx". 3422 * </ul> 3423 * 3424 * @param s The string to be encoded 3425 * @return The encoded string 3426 */ 3427 public static String encodeToURL(String s) 3428 { 3429 StringBuffer sbuf = new StringBuffer(); 3430 int len = s.length(); 3431 for (int i = 0; i < len; i++) { 3432 int ch = s.charAt(i); 3433 if ('A' <= ch && ch <= 'Z') { // 'A'..'Z' 3434 sbuf.append((char)ch); 3435 } else if ('a' <= ch && ch <= 'z') { // 'a'..'z' 3436 sbuf.append((char)ch); 3437 } else if ('0' <= ch && ch <= '9') { // '0'..'9' 3438 sbuf.append((char)ch); 3439 } else if (ch == ' ') { // space 3440 sbuf.append('+'); 3441 } else if (ch == '-' || ch == '_' // unreserved 3442 || ch == '.' || ch == '!' 3443 || ch == '~' || ch == '*' 3444 || ch == '\'' || ch == '(' 3445 || ch == ')') { 3446 sbuf.append((char)ch); 3447 } else if (ch <= 0x007f) { // other ASCII 3448 sbuf.append(hex[ch]); 3449 } else if (ch <= 0x07FF) { // non-ASCII <= 0x7FF 3450 sbuf.append(hex[0xc0 | (ch >> 6)]); 3451 sbuf.append(hex[0x80 | (ch & 0x3F)]); 3452 } else { // 0x7FF < ch <= 0xFFFF 3453 sbuf.append(hex[0xe0 | (ch >> 12)]); 3454 sbuf.append(hex[0x80 | ((ch >> 6) & 0x3F)]); 3455 sbuf.append(hex[0x80 | (ch & 0x3F)]); 3456 } 3457 } 3458 return sbuf.toString(); 3459 } 3460 3461 3462 /* 3463 * Created: 17 April 1997 3464 * Author: Bert Bos <bert@w3.org> 3465 * 3466 * unescape: http://www.w3.org/International/unescape.java 3467 * 3468 * Copyright © 1997 World Wide Web Consortium, (Massachusetts 3469 * Institute of Technology, European Research Consortium for 3470 * Informatics and Mathematics, Keio University). All Rights Reserved. 3471 * This work is distributed under the W3C® Software License [1] in the 3472 * hope that it will be useful, but WITHOUT ANY WARRANTY; without even 3473 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 3474 * PURPOSE. 3475 * 3476 * [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 3477 */ 3478 public static String decodeURL(String s) 3479 { 3480 StringBuffer sbuf = new StringBuffer () ; 3481 int l = s.length() ; 3482 int ch = -1 ; 3483 int b, sumb = 0; 3484 for (int i = 0, more = -1 ; i < l ; i++) 3485 { 3486 /* Get next byte b from URL segment s */ 3487 switch (ch = s.charAt(i)) 3488 { 3489 case '%': 3490 ch = s.charAt (++i) ; 3491 int hb = (Character.isDigit ((char) ch) 3492 ? ch - '0' 3493 : 10+Character.toLowerCase((char) ch) - 'a') & 0xF ; 3494 ch = s.charAt (++i) ; 3495 int lb = (Character.isDigit ((char) ch) 3496 ? ch - '0' 3497 : 10+Character.toLowerCase ((char) ch)-'a') & 0xF ; 3498 b = (hb << 4) | lb ; 3499 break ; 3500 3501 case '+': 3502 b = ' ' ; 3503 break ; 3504 3505 default: 3506 b = ch ; 3507 } 3508 /* Decode byte b as UTF-8, sumb collects incomplete chars */ 3509 if ((b & 0xc0) == 0x80) 3510 { // 10xxxxxx (continuation byte) 3511 sumb = (sumb << 6) | (b & 0x3f) ; // Add 6 bits to sumb 3512 if (--more == 0) sbuf.append((char) sumb) ; // Add char to sbuf 3513 } 3514 else if ((b & 0x80) == 0x00) 3515 { // 0xxxxxxx (yields 7 bits) 3516 sbuf.append((char) b) ; // Store in sbuf 3517 } 3518 else if ((b & 0xe0) == 0xc0) 3519 { // 110xxxxx (yields 5 bits) 3520 sumb = b & 0x1f; 3521 more = 1; // Expect 1 more byte 3522 } 3523 else if ((b & 0xf0) == 0xe0) 3524 { // 1110xxxx (yields 4 bits) 3525 sumb = b & 0x0f; 3526 more = 2; // Expect 2 more bytes 3527 } 3528 else if ((b & 0xf8) == 0xf0) 3529 { // 11110xxx (yields 3 bits) 3530 sumb = b & 0x07; 3531 more = 3; // Expect 3 more bytes 3532 } 3533 else if ((b & 0xfc) == 0xf8) 3534 { // 111110xx (yields 2 bits) 3535 sumb = b & 0x03; 3536 more = 4; // Expect 4 more bytes 3537 } 3538 else /*if ((b & 0xfe) == 0xfc)*/ 3539 { // 1111110x (yields 1 bit) 3540 sumb = b & 0x01; 3541 more = 5; // Expect 5 more bytes 3542 } 3543 /* We don't test if the UTF-8 encoding is well-formed */ 3544 } 3545 return sbuf.toString() ; 3546 } 3547 3548 3549 /** 3550 * gets the current VMs localhost address. 3551 * 3552 * @return the current VMs localhost address, Null if it can't be gotten. 3553 */ 3554 public static InetAddress getLocalhostName() 3555 { 3556 initUtil(); 3557 final String methodName = CLASSNAME + ": getLocalhostrName()"; 3558 if (log_ != null) 3559 { 3560 log_.startMethod(methodName); 3561 } 3562 InetAddress retVal = null; 3563 try 3564 { 3565 retVal = InetAddress.getLocalHost(); 3566 } 3567 catch (UnknownHostException unknownEx) 3568 { 3569 log_.minor("Cant't get the hostname address.", unknownEx); 3570 } 3571 if (log_ != null) 3572 { 3573 log_.endMethod(); 3574 } 3575 return retVal; 3576 } 3577 3578 3579 /** Calculated the BCH GIS location in Lat/Long of a BCH GIS x,y asset position. 3580 * BCH GIS is a Lambert Conformal Projection for BC Hydro. 3581 <pre> 3582 proj -I +proj=lcc +lat_1=50 +lat_2=56 +lat_0=53.0 +lon_0=-123.0 +x_0=0 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=cm 3583 3584 The Well Know Text (WKT) is: 3585 PROJCS["BC Hydro Lambert Conformal Conic", 3586 GEOGCS["North American Datum_1983", 3587 DATUM["North American Datum 1983", 3588 SPHEROID["Geodetic Reference System of 1980",6378137,298.2572221009113]], 3589 PRIMEM["Greenwich",0], 3590 UNIT["Decimal Degree",0.0174532925199433]], 3591 PROJECTION["Lambert Conformal Conic 2SP"], 3592 PARAMETER["standard_parallel_1",50], 3593 PARAMETER["standard_parallel_2",56], 3594 PARAMETER["latitude_of_origin",53], 3595 PARAMETER["central_meridian",-123], 3596 PARAMETER["false_easting",0], 3597 PARAMETER["false_northing",0], 3598 UNIT["METER",1]] 3599 </pre> 3600 3601 see http://www.geoapi.org/2.0/javadoc/org/opengis/referencing/doc-files/WKT.html 3602 **/ 3603 /* 3604 public static LatLong getBCHAssetLatLong(double x, double y) throws IllegalArgumentException 3605 { 3606 LatLong retVal = new LatLong(); 3607 String bchWKT = "PROJCS[\"BC Hydro Lambert Conformal Conic\",\n"+ 3608 " GEOGCS[\"North American Datum 1983\",\n"+ 3609 " DATUM[\"North American Datum 1983\",\n"+ 3610 " SPHEROID[\"Geodetic Reference System of 1980\",6378137,298.2572221009113]],\n"+ 3611 " PRIMEM[\"Greenwich\",0],\n"+ 3612 " UNIT[\"Decimal Degree\",0.0174532925199433]],\n"+ 3613 " PROJECTION[\"Lambert_Conformal_Conic_2SP\"],\n"+ 3614 " PARAMETER[\"standard_parallel_1\",50],\n"+ 3615 " PARAMETER[\"standard_parallel_2\",56],\n"+ 3616 " PARAMETER[\"latitude_of_origin\",52.991936976411],\n"+ // 52.991936976411 3617 " PARAMETER[\"central_meridian\",-123.0161404723602],\n"+ // -123.0161404723602 3618 " PARAMETER[\"false_easting\",0],\n"+ 3619 " PARAMETER[\"false_northing\",0],\n"+ 3620 " UNIT[\"METER\",1]]"; 3621 3622 Parser parser = new Parser(); 3623 3624 try 3625 { 3626 CoordinateReferenceSystem crs = parser.parseCoordinateReferenceSystem(bchWKT) ; 3627 // org.geotools.referencing.crs.DefaultProjectedCRS 3628 //System.out.println("The CRS is of type: "+crs.getClass().getName()); 3629 3630 DefaultProjectedCRS bchCrs = (DefaultProjectedCRS) crs; 3631 3632 GeodeticCalculator gc = new GeodeticCalculator(bchCrs) ; 3633 3634 if (false) // debug statements 3635 { 3636 System.out.println(" Initial Starting Position (meters)="+ gc.getStartingPosition()); 3637 //System.out.println(" datum="+ bchCrs.getDatum()); 3638 System.out.println("\n WKT="+ bchCrs.toWKT()); 3639 3640 } 3641 3642 // set the start measure position to the BCH Origin 3643 gc.setStartingGeographicPoint(LatLong.BCH_LONG_ORIGIN, LatLong.BCH_LAT_ORIGIN); //this is now built into the Parsed CRS 3644 //java.awt.geom.Point2D bchOriginLatLong = new java.awt.geom.Point2D.Double(LatLong.BCH_LONG_ORIGIN, LatLong.BCH_LAT_ORIGIN); 3645 3646 //gc.setDestinationGeographicPoint(x,y); //new java.awt.geom.Point2D.Float(x,y)); 3647 gc.setDestinationPosition(new GeneralDirectPosition(x,y) ); //new java.awt.geom.Point2D.Float(x,y)); 3648 3649 // TEST 3650 //gc.setDestinationGeographicPoint(bchOriginLatLong); 3651 3652 GeneralDirectPosition startPosition = (GeneralDirectPosition)gc.getStartingPosition(); 3653 GeneralDirectPosition destPosition = (GeneralDirectPosition)gc.getDestinationPosition(); // returns the CRS unit (meters) 3654 java.awt.geom.Point2D startLatLong = gc.getStartingGeographicPoint() ; //The x and y coordinates are the longitude and latitude in decimal degrees, respectively. 3655 java.awt.geom.Point2D destLatLong = gc.getDestinationGeographicPoint(); //The x and y coordinates are the longitude and latitude in decimal degrees, respectively. 3656 retVal = new LatLong(destLatLong.getY(), destLatLong.getX()); 3657 3658 if (false) // debug statements 3659 { 3660 System.out.println("\n------------------------------\n Starting Position (meters)="+ startPosition); 3661 System.out.println("Detination Position (meters)="+ destPosition); 3662 System.out.println("\n Starting Position (LatLong) Lat="+ startLatLong.getY()+ " Long="+ startLatLong.getX()); 3663 System.out.println("Detination Position (LatLong) Lat="+ destLatLong.getY()+ " Long="+ destLatLong.getX()); 3664 System.out.println("Distance="+ gc.getOrthodromicDistance() ); 3665 } 3666 3667 } 3668 catch (TransformException tEx) 3669 { 3670 tEx.printStackTrace(); 3671 } 3672 catch(java.text.ParseException pEx) 3673 { 3674 pEx.printStackTrace(); 3675 } 3676 catch(Exception ex) 3677 { 3678 ex.printStackTrace(); 3679 } 3680 return retVal; 3681 } 3682 */ 3683 3684 /** Calculates the Distance in meters between two LatLong points on the earth assuming it is a perfect sphere. **/ 3685 public static double sphereDistanceBetween(double lat1, double lng1, double lat2, double lng2) 3686 { 3687 double earthRadius = 3958.75; // this is in miles 3688 double dLat = Math.toRadians(lat2-lat1); 3689 double dLng = Math.toRadians(lng2-lng1); 3690 double a = Math.sin(dLat/2) * Math.sin(dLat/2) + 3691 Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * 3692 Math.sin(dLng/2) * Math.sin(dLng/2); 3693 double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 3694 double dist = earthRadius * c; 3695 3696 double meterConversion = 1609.344; 3697 3698 return (dist * meterConversion); 3699 } 3700 3701 3702 /** 3703 * Executes the Specified Native OS application with the provided commandline 3704 * parameters. This method blocks until the Executed app is complete. It also 3705 * cleans up its sub-process and garbage collects. This method inherits the current workingDir. 3706 * 3707 * @param executableLocation is the path to the executable to run 3708 * @param cmds and extra commandline parameters to tag onto the 3709 * end of the commandline that gets executed. 3710 * @param verboseOutput flag for optionaly printing extra application state output. 3711 * 3712 * @return returns the captured output from the executed app/process 3713 * 3714 * @see StreamGobbler 3715 * @see java.lang.Runtime#getRuntime 3716 **/ 3717 public static String executeNativeApp(String executableLocation, 3718 String[] cmds, 3719 boolean verboseOutput) 3720 { return executeNativeApp(executableLocation, cmds, verboseOutput, null); } 3721 3722 /** 3723 * Executes the Specified Native OS application with the provided commandline 3724 * parameters and Working Directory. This method blocks until the Executed app is complete. It also 3725 * cleans up its sub-process and garbage collects. 3726 * 3727 * @param executableLocation is the path to the executable to run 3728 * @param cmds and extra commandline parameters to tag onto the 3729 * end of the commandline that gets executed. 3730 * @param verboseOutput flag for optionaly printing extra application state output. 3731 * @param workingDir the working dir to exec from - To inherit current, pass a null. 3732 * 3733 * @return returns the captured output from the executed app/process 3734 * 3735 * @see StreamGobbler 3736 * @see java.lang.Runtime#getRuntime 3737 **/ 3738 public static String executeNativeApp(String executableLocation, 3739 String[] cmds, 3740 boolean verboseOutput, 3741 String workingDir) 3742 { 3743 final String methodName = CLASSNAME + ": executeNativeApp(String,String[],boolean)"; 3744 initUtil(); 3745 if (log_ != null) 3746 { 3747 log_.startMethod(methodName); 3748 } 3749 String retVal = ""; 3750 3751 StreamGobbler inputGobbler = new StreamGobbler(); 3752 inputGobbler.setCapture(true); 3753 executeNativeApp(executableLocation,cmds,null,inputGobbler,verboseOutput, workingDir); 3754 log_.debug("App Execution Complete"); 3755 retVal = inputGobbler.getCapturedOutput(); 3756 3757 if (log_ != null) 3758 { 3759 log_.endMethod(); 3760 } 3761 return retVal; 3762 } 3763 3764 3765 /** 3766 * Executes the Specified Native OS application with the provided commandline 3767 * parameters. This method blocks until the Executed app is complete. It also 3768 * cleans up its sub-process and garbage collects. 3769 * 3770 * @param executableLocation is the path to the executable to run 3771 * @param cmds and extra commandline parameters to tag onto the 3772 * end of the commandline that gets executed. 3773 * @param outFilename an outputFile to dump the exe output (If this is null 3774 * it sends the output to System.out). 3775 * @param verboseOutput flag for optionaly printing extra applicvation state output. 3776 * 3777 * @return returns the return code from the executed app/process 3778 * 3779 * @see StreamGobbler 3780 * @see java.lang.Runtime#getRuntime 3781 **/ 3782 public static int executeNativeApp(String executableLocation, 3783 String[] cmds, 3784 String outFilename, 3785 boolean verboseOutput) 3786 { 3787 return executeNativeApp(executableLocation, 3788 cmds, 3789 outFilename, 3790 null, 3791 verboseOutput, 3792 null); 3793 } 3794 3795 3796 /** 3797 * Executes the Specified Native OS application with the provided commandline 3798 * parameters. This method blocks until the Executed app is complete. It also 3799 * cleans up its sub-process and garbage collects. 3800 * 3801 * @param executableLocation is the path to the executable to run 3802 * @param appParms and extra commandline parameters to tag onto the 3803 * end of the commandline that gets executed. 3804 * @param outFilename an outputFile to dump the exe output (If this is null 3805 * it sends the output to System.out). 3806 * @param inputGobbler is the StreamGobbler object to use in gobbling the Commands InputStream. 3807 * @param verboseOutput flag for optionaly printing extra applicvation state output. 3808 * 3809 * @return returns the return code from the executed app/process 3810 * 3811 * @see StreamGobbler 3812 * @see java.lang.Runtime#getRuntime 3813 **/ 3814 public static int executeNativeApp(String executableLocation, 3815 Vector appParms, 3816 String outFilename, 3817 StreamGobbler inputGobbler, 3818 boolean verboseOutput) 3819 { return executeNativeApp(executableLocation, appParms, outFilename, inputGobbler, verboseOutput, null); } 3820 3821 3822 /** 3823 * Executes the Specified Native OS application with the provided commandline 3824 * parameters. This method blocks until the Executed app is complete. It also 3825 * cleans up its sub-process and garbage collects. 3826 * 3827 * @param executableLocation is the path to the executable to run 3828 * @param appParms and extra commandline parameters to tag onto the 3829 * end of the commandline that gets executed. 3830 * @param outFilename an outputFile to dump the exe output (If this is null 3831 * it sends the output to System.out). 3832 * @param inputGobbler is the StreamGobbler object to use in gobbling the Commands InputStream. 3833 * @param verboseOutput flag for optionaly printing extra applicvation state output. 3834 * @param workingDir the working dir to exec from - To inherit current, pass a null. 3835 * 3836 * @return returns the return code from the executed app/process 3837 * 3838 * @see StreamGobbler 3839 * @see java.lang.Runtime#getRuntime 3840 **/ 3841 public static int executeNativeApp(String executableLocation, 3842 Vector appParms, 3843 String outFilename, 3844 StreamGobbler inputGobbler, 3845 boolean verboseOutput, 3846 String workingDir) 3847 { 3848 int retVal = -1; 3849 int cmdParms = 0; 3850 if (appParms != null) 3851 cmdParms = appParms.size(); 3852 String [] cmds = new String [cmdParms]; 3853 //cmds[0] = executableLocation; 3854 3855 if (verboseOutput) System.out.print("Executing: "+ executableLocation); 3856 for (int i=0; i < cmdParms; i++) 3857 { 3858 if (verboseOutput) System.out.print(" " + i + ")"); 3859 if (verboseOutput) System.out.print(" " + (String)appParms.elementAt(i)); 3860 cmds[i] = (String) appParms.elementAt(i); 3861 if (verboseOutput) System.out.print(" " + cmds[i]); 3862 } 3863 if (verboseOutput) System.out.println(""); 3864 3865 return executeNativeApp(executableLocation, 3866 cmds, 3867 outFilename, 3868 inputGobbler, 3869 verboseOutput, 3870 workingDir); 3871 } 3872 3873 3874 /** 3875 * Executes the Specified Native OS application with the provided commandline 3876 * parameters. This method blocks until the Executed app is complete. It also 3877 * cleans up its sub-process and garbage collects. 3878 * 3879 * @param executableLocation is the path to the executable to run 3880 * @param cmds and extra commandline parameters to tag onto the 3881 * end of the commandline that gets executed. 3882 * @param outFilename an outputFile to dump the exe output (If this is null 3883 * it sends the output to System.out). 3884 * @param inputGobbler is the StreamGobbler object to use in gobbling the Commands InputStream. 3885 * @param verboseOutput flag for optionaly printing extra applicvation state output. 3886 * @param workingDir the working dir to exec from - To inherit current, pass a null. 3887 * 3888 * @return returns the return code from the executed app/process 3889 * 3890 * @see StreamGobbler 3891 * @see java.lang.Runtime#getRuntime 3892 **/ 3893 public static int executeNativeApp(String executableLocation, 3894 String[] cmds, 3895 String outFilename, 3896 StreamGobbler inputGobbler, 3897 boolean verboseOutput, 3898 String workingDir) 3899 { 3900 int retVal = -1; 3901 3902 if (workingDir==null) workingDir = USERDIR; 3903 3904 // Start the app... This starts a new process 3905 try 3906 { 3907 // set up the arrays to send to exec. 3908 //String[] prefix = new String[]{}; 3909 String[] prefix = new String[]{executableLocation}; 3910 //String[] prefix = new String[]{"cmd.exe", "/U", "/E:OFF", "/C"}; 3911 //String[] prefix = new String[]{"start", "/I", "/B"}; 3912 String[] actualArgs = new String[prefix.length + cmds.length]; 3913 System.arraycopy(prefix, 0, actualArgs, 0, prefix.length); 3914 System.arraycopy(cmds, 0, actualArgs, prefix.length, cmds.length); 3915 3916 // collect and init the environment 3917 ProcessRunner osSupport = ProcessRunner.getProcessRunner(); 3918 Hashtable variables = osSupport.getEnvironmentVariables(); 3919 String [] env = new String[variables.size()]; 3920 if(osSupport.supportsEnvironmentVariables()) 3921 { 3922 int counter = 0; 3923 Enumeration keys = variables.keys(); 3924 while(keys.hasMoreElements()) 3925 { 3926 Object key = keys.nextElement(); 3927 env[counter++]= (key + "=" + variables.get(key)); 3928 } 3929 } 3930 3931 //for (int i=0; i < env.length; i++) 3932 // System.out.println(env[i]); 3933 //System.out.println(""); 3934 if (verboseOutput) 3935 { 3936 for (int i=0; i < actualArgs.length; i++) 3937 System.out.print(actualArgs[i] + " "); 3938 System.out.println(""); 3939 } 3940 3941 // get set up to get any output? 3942 FileOutputStream pumpedOutputFile = null; 3943 PrintStream pumpedPrintStream = System.out; 3944 if (outFilename != null && !outFilename.equals("")) 3945 { 3946 pumpedOutputFile = new FileOutputStream(outFilename); 3947 pumpedPrintStream = new PrintStream(pumpedOutputFile); 3948 } 3949 //set up the Gobbler 3950 if (inputGobbler == null) inputGobbler = new StreamGobbler(); 3951 inputGobbler.setPrependString(""); 3952 inputGobbler.setOs_(pumpedPrintStream); 3953 StreamGobbler errorGobbler = new StreamGobbler(); 3954 errorGobbler.setPrependString("Error> "); 3955 3956 // get the system call process set up and running 3957 Runtime runtime = Runtime.getRuntime(); 3958 //Process p = runtime.exec(actualArgs, env, new File(".\\.")); 3959 /*System.out.println("***Calling runtimeexec "+actualArgs[0]+","+ 3960 (actualArgs.length>1?actualArgs[1]+",":"")+ 3961 (actualArgs.length>2?actualArgs[2]+",":"")+ 3962 (actualArgs.length>3?actualArgs[3]+",":"")+ 3963 (actualArgs.length>4?actualArgs[4]+",":"")); 3964 System.out.println("From Dir:"+workingDir); 3965 */ 3966 Process p = runtime.exec(actualArgs, null, new File(workingDir)); 3967 3968 // capture any input we get 3969 // any error message? 3970 //StreamGobbler outputGobbler = new StreamGobbler(p.getOutputStream(), "Out> "); 3971 3972 // capture any output we get 3973 // any error message? 3974 inputGobbler.setInputStream(p.getInputStream()); 3975 errorGobbler.setInputStream(p.getErrorStream()); 3976 3977 // kick them off 3978 inputGobbler.start(); 3979 errorGobbler.start(); 3980 //outputGobbler.start(); 3981 3982 // now wait for the process to end 3983 try 3984 { 3985 sleep(3000); 3986 p.waitFor(); 3987 if (verboseOutput) System.out.println("Process Done Executing."); 3988 //if (verboseOutput) System.out.println(outputGobbler.getCapturedOutput()); 3989 } 3990 catch (Exception intEx) 3991 { 3992 if (verboseOutput) System.out.print("APP Interupted?"); 3993 } 3994 retVal = p.exitValue(); 3995 if (verboseOutput) System.out.println("APP return value:"+retVal); 3996 errorGobbler.finishedGobbling_ = true; 3997 //outputGobbler.finishedGobbling_ = true; 3998 inputGobbler.finishedGobbling_ = true; 3999 if (pumpedOutputFile != null) 4000 { 4001 pumpedOutputFile.flush(); 4002 pumpedOutputFile.close(); 4003 } 4004 p.destroy(); 4005 p = null; 4006 runtime.gc(); 4007 } 4008 catch (IOException ioEx) 4009 { 4010 System.out.println("ERROR: An IO exception occured while attempting " + 4011 "execution of the " + executableLocation + " application."); 4012 ioEx.printStackTrace(); 4013 } 4014 catch (SecurityException securityEx) 4015 { 4016 System.out.println("ERROR: A Java Security Manager is in use and is " + 4017 "restricting execution of the " + executableLocation + " application."); 4018 } 4019 catch (Exception ex) 4020 { 4021 System.out.println("ERROR: A Java Exception Occured " + 4022 "restricting execution of the " + executableLocation + " application."); 4023 ex.printStackTrace(); 4024 } 4025 4026 return retVal; 4027 } 4028 4029 4030 /** 4031 * A Thread Watchdog that watches the passed in thread and Interupts it if it 4032 * has not finished by the requested time. 4033 * 4034 * @param watchThread is the thread to watch 4035 * @param timeToTerminate is the time to wait befor Interupting 4036 * @exception SecurityException If the interrupt is not allowed on the thread 4037 * 4038 * @return true or false to specify if this watchdog had to interupt. 4039 **/ 4040 public static boolean threadWatchdog(final Thread watchThread, 4041 final long timeToTerminate) 4042 throws SecurityException 4043 { 4044 boolean retVal = false; 4045 4046 // inline Thread to do the watching 4047 Thread watchdogThread = new Thread (){ 4048 Thread threadToWatch = null; 4049 long timeWatched = 0; 4050 int sleepTime = 500; 4051 4052 public void run() 4053 { 4054 watchdogReset = false; 4055 while (timeWatched < timeToTerminate && 4056 watchThread.isAlive() && 4057 !watchThread.isInterrupted() && 4058 !watchdogReset) 4059 { 4060 timeWatched += sleepTime; 4061 try 4062 { 4063 sleep(sleepTime); 4064 } 4065 catch (InterruptedException iex) 4066 { 4067 } 4068 } 4069 4070 if (timeWatched >= timeToTerminate) 4071 { 4072 // this throws a security exception If the interrupt is not allowed 4073 watchThread.interrupt(); 4074 } 4075 } 4076 }; 4077 4078 watchdogThread.start(); 4079 4080 return retVal; 4081 } 4082 4083 4084 /** 4085 * Executes the Specified Native OS application with the provided commandline 4086 * parameters. This method blocks until the Executed app is complete. It also 4087 * cleans up its sub-process and garbage collects. This method defaults to 4088 * print System.out statements to describe the state of execution. If you 4089 * don't want anything but the executed application output call the 4090 * overridden method with the verbose flag. 4091 * 4092 * @param executableLocation is the path to the executable to run 4093 * 4094 * @param appParms and extra commandline parameters to tag onto the 4095 * end of the commandline that gets executed. 4096 * 4097 * @param outFilename an outputFile to dump the exe output. 4098 * 4099 * @return returns the return code from the executed app/process 4100 * 4101 * @see StreamGobbler 4102 * @see java.lang.Runtime#getRuntime 4103 **/ 4104 public static int executeNativeApp(String executableLocation, 4105 Vector appParms, 4106 String outFilename) 4107 { 4108 return executeNativeApp(executableLocation, appParms, outFilename, true); 4109 } 4110 4111 4112 /** 4113 * Executes the Specified Native OS application with the provided commandline 4114 * parameters. This method blocks until the Executed app is complete. It also 4115 * cleans up its sub-process and garbage collects. 4116 * 4117 * @param executableLocation is the path to the executable to run 4118 * @param appParms and extra commandline parameters to tag onto the 4119 * end of the commandline that gets executed. 4120 * @param outFilename an outputFile to dump the exe output (This can be null) 4121 * @param verboseOutput flag for optionaly printing extra applicvation state output. 4122 * 4123 * @return returns the return code from the executed app/process 4124 * 4125 * @see StreamGobbler 4126 * @see java.lang.Runtime#getRuntime 4127 **/ 4128 public static int executeNativeApp(String executableLocation, 4129 Vector appParms, 4130 String outFilename, 4131 boolean verboseOutput) 4132 { 4133 int retVal = -1; 4134 int cmdParms = 0; 4135 if (appParms != null) 4136 cmdParms = appParms.size(); 4137 String [] cmds = new String [cmdParms]; 4138 //cmds[0] = executableLocation; 4139 4140 if (verboseOutput) System.out.print("Executing: "+ executableLocation); 4141 for (int i=0; i < cmdParms; i++) 4142 { 4143 if (verboseOutput) System.out.print(" " + i + ")"); 4144 if (verboseOutput) System.out.print(" " + (String)appParms.elementAt(i)); 4145 cmds[i] = (String) appParms.elementAt(i); 4146 if (verboseOutput) System.out.print(" " + cmds[i]); 4147 } 4148 if (verboseOutput) System.out.println(""); 4149 4150 return executeNativeApp(executableLocation, 4151 cmds, 4152 outFilename, 4153 verboseOutput); 4154 } 4155 4156 4157 /** 4158 * Executes the Specified Native OS application with the provided commandline 4159 * parameters. This method blocks until the Executed app is complete. It also 4160 * cleans up its sub-process and garbage collects. 4161 * 4162 * @param executableLocation is the path to the executable to run 4163 * @param appParms and extra commandline parameters to tag onto the 4164 * end of the commandline that gets executed. 4165 * @param verboseOutput flag for optionaly printing extra applicvation state output. 4166 * 4167 * @return returns the captured results stream from the executed app/process 4168 * 4169 * @see StreamGobbler 4170 * @see java.lang.Runtime#getRuntime 4171 **/ 4172 public static String executeNativeApp(String executableLocation, 4173 Vector appParms, 4174 boolean verboseOutput) 4175 {return executeNativeApp(executableLocation,appParms, verboseOutput, null);} 4176 4177 4178 /** 4179 * Executes the Specified Native OS application with the provided commandline 4180 * parameters. This method blocks until the Executed app is complete. It also 4181 * cleans up its sub-process and garbage collects. 4182 * 4183 * @param executableLocation is the path to the executable to run 4184 * @param appParms and extra commandline parameters to tag onto the 4185 * end of the commandline that gets executed. 4186 * @param verboseOutput flag for optionaly printing extra applicvation state output. 4187 * 4188 * @return returns the captured results stream from the executed app/process 4189 * 4190 * @see StreamGobbler 4191 * @see java.lang.Runtime#getRuntime 4192 **/ 4193 public static String executeNativeApp(String executableLocation, 4194 Vector appParms, 4195 boolean verboseOutput, 4196 String workingDir) 4197 { 4198 int cmdParms = 0; 4199 if (appParms != null) 4200 cmdParms = appParms.size(); 4201 String [] cmds = new String [cmdParms]; 4202 //cmds[0] = executableLocation; 4203 4204 if (verboseOutput) System.out.print("Executing: "+ executableLocation); 4205 for (int i=0; i < cmdParms; i++) 4206 { 4207 if (verboseOutput) System.out.print(" " + i + ")"); 4208 if (verboseOutput) System.out.print(" " + (String)appParms.elementAt(i)); 4209 cmds[i] = (String) appParms.elementAt(i); 4210 if (verboseOutput) System.out.print(" " + cmds[i]); 4211 } 4212 if (verboseOutput) System.out.println(""); 4213 4214 return executeNativeApp(executableLocation, 4215 cmds, 4216 verboseOutput, 4217 workingDir); 4218 } 4219 4220 4221 /** 4222 * gets the current date and time. 4223 * 4224 * @return the current Date. 4225 */ 4226 public static Date getCurrentDate() 4227 { 4228 initUtil(); 4229 final String methodName = CLASSNAME + ": getCurrentDate()"; 4230 if (log_ != null) 4231 { 4232 log_.startMethod(methodName); 4233 } 4234 Date retVal = new Date(); 4235 if (log_ != null) 4236 { 4237 log_.endMethod(); 4238 } 4239 return retVal; 4240 } 4241 4242 4243 /** 4244 * Counts the files in a dir (optionally recurses sub dirs) 4245 * 4246 * @param dirName 4247 * @param recurse 4248 * @return the number of files (not counting the directories) 4249 */ 4250 public static long countFilesInDir(String dirName, 4251 boolean recurse) 4252 { 4253 initUtil(); 4254 final String methodName = CLASSNAME + ": countFilesInDir()"; 4255 if (log_ != null) 4256 { 4257 log_.startMethod(methodName); 4258 } 4259 long retVal = 0L; 4260 File dirFile = new File(dirName); 4261 4262 if (dirFile.isDirectory() && dirFile.canRead()) 4263 { 4264 String[] waste = dirFile.list(); 4265 File tempFile = null; 4266 for (int i = 0; i < waste.length; i++) 4267 { 4268 tempFile = new File(dirName + File.separator + waste[i]); 4269 if (tempFile != null && !tempFile.isDirectory()) 4270 { 4271 retVal++; 4272 } 4273 else if (tempFile != null && recurse) 4274 { 4275 retVal += 4276 countFilesInDir(dirName + File.separator + waste[i], true); 4277 } 4278 } 4279 } 4280 4281 if (log_ != null) 4282 { 4283 log_.endMethod(); 4284 } 4285 return retVal; 4286 } 4287 4288 public static void main(String [] args) 4289 { 4290 final String methodName = CLASSNAME + ": main()"; 4291 initUtil(); 4292 /*if (log_ != null) 4293 { 4294 //log_.setLogFile(Log.CONSOLE); 4295 log_.setLogLevel(Log.FULL); 4296 log_.startMethod(methodName); 4297 } */ 4298 log_.debug("args: "); 4299 for (int i=1; i < args.length; i++) log_.debug(""+i+" "+args[i]); 4300 4301 StringBuffer helpMsg = new StringBuffer(SYSTEM_LINE_SEPERATOR); 4302 helpMsg.append("--- WebARTS Util Class --------------------------------"); 4303 helpMsg.append("----------------------"); 4304 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4305 helpMsg.append("WebARTS Util Class"); 4306 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4307 helpMsg.append("SYNTAX:"); 4308 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4309 helpMsg.append(" java ca.bc.webarts.widgets.Util methodName methodArgs"); 4310 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4311 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4312 helpMsg.append("Available Methods:"); 4313 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4314 helpMsg.append("--> ensureFolderExists fullDirectoryName||fullFilename"); 4315 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4316 helpMsg.append("--> removeDir fullDirectoryName fullDirectoryName2 ..."); 4317 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4318 helpMsg.append("--> createCurrentTimeStamp"); 4319 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4320 helpMsg.append("--> createCurrentDateTimeStamp"); 4321 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4322 helpMsg.append("--> capsToSpacesInString StringToConvert"); 4323 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4324 helpMsg.append("--> spacesToCapsInString StringToConvert"); 4325 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4326 helpMsg.append("--> spacesToCapsInDir directoryName"); 4327 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4328 helpMsg.append("--> removeParentRelativeReference pathName"); 4329 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4330 helpMsg.append("--> countFilesInDir fullDirectoryName"); 4331 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4332 helpMsg.append("--> dirSize fullDirectoryName"); 4333 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4334 helpMsg.append("--> removeOldFiles fullDirectoryName daysOld"); 4335 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4336 helpMsg.append("--> testHexConverters decimalNumber [decimalNumber2] [decimalNumber3] [...]"); 4337 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4338 helpMsg.append("--> sleep ms"); 4339 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4340 helpMsg.append("--> executeNativeApp executableLocation [parms] "); 4341 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4342 helpMsg.append("--> findFile fileToFind [dirToStart] [recurseSubDirs] [regExp] "); 4343 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4344 helpMsg.append(" - if using a regExp, the fileToFind param is a quoted Java regExp such as \"[*.png]\" or \"[a-zA-Z*.zip]\""); 4345 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4346 helpMsg.append("--> searchInFile file/dirToSearch searchStr"); 4347 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4348 helpMsg.append("--> tokenReplaceInFile file/dirToSearch tokenStr replaceStr "); 4349 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4350 helpMsg.append("--> tokenReplaceInRecursedFile file/dirToSearch tokenStr replaceStr "); 4351 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4352 helpMsg.append("--> zipUpFile filename "); 4353 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4354 helpMsg.append("--> renameFile fromFilename toFilename"); 4355 helpMsg.append(" - Renames the specified fromFile to the toFilename in the same directory."); 4356 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4357 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4358 helpMsg.append("---------------------------------------------------------"); 4359 helpMsg.append("----------------------"); 4360 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4361 4362 if (args ==null || args.length<1) 4363 System.out.println(helpMsg.toString()); 4364 else 4365 { 4366 // ***************************************************** 4367 if (args[0].equals("removeDir")) 4368 { 4369 if (args.length >1) 4370 { 4371 File tmpDirFile = null; 4372 for (int i=1; i < args.length; i++) 4373 { 4374 if ((tmpDirFile = initDirFile(args[i])) != null) 4375 { 4376 if (removeDir(args[i])) 4377 System.out.println("Directory Removed: "+args[i]); 4378 else 4379 System.out.println("Directory NOT Removed successfully: "+args[i]); 4380 } 4381 else 4382 { 4383 helpMsg.append("ERROR: Cannot find the Directory named:"); 4384 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4385 helpMsg.append(args[i]); 4386 System.out.println(helpMsg.toString()); 4387 } 4388 } 4389 } 4390 else 4391 { 4392 helpMsg.append("ERROR: The removeDir method requires at least 1"); 4393 helpMsg.append(" directory name to operate."); 4394 System.out.println(helpMsg.toString()); 4395 } 4396 } 4397 if (args[0].equals("ensureFolderExists")) 4398 { 4399 if (args.length >1) 4400 { 4401 File tmpDirFile = null; 4402 for (int i=1; i < args.length; i++) 4403 { 4404 ensureParentFolderExists(args[i]); 4405 } 4406 } 4407 else 4408 { 4409 helpMsg.append("ERROR: The ensureFolderExists method requires at least 1"); 4410 helpMsg.append(" directory name to operate."); 4411 System.out.println(helpMsg.toString()); 4412 } 4413 } 4414 // ***************************************************** 4415 else if (args[0].equals("countFilesInDir")) 4416 { 4417 if (args.length >1) 4418 { 4419 File tmpDirFile = null; 4420 for (int i=1; i < args.length; i++) 4421 { 4422 if ((tmpDirFile = initDirFile(args[i])) != null) 4423 { 4424 long retVal = countFilesInDir(args[i], true); 4425 System.out.println("Number Of Files = " + retVal); 4426 } 4427 else 4428 { 4429 helpMsg.append("ERROR: Cannot find the Directory named:"); 4430 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4431 helpMsg.append(args[i]); 4432 System.out.println(helpMsg.toString()); 4433 } 4434 } 4435 } 4436 else 4437 { 4438 helpMsg.append("ERROR: The countFilesInDir method requires 1"); 4439 helpMsg.append(" directory name to operate."); 4440 System.out.println(helpMsg.toString()); 4441 } 4442 } 4443 // ***************************************************** 4444 else if (args[0].equals("countFilesInDir")) 4445 { 4446 if (args.length >1) 4447 { 4448 File tmpDirFile = null; 4449 for (int i=1; i < args.length; i++) 4450 { 4451 if ((tmpDirFile = initDirFile(args[i])) != null) 4452 { 4453 long retVal = countFilesInDir(args[i], true); 4454 System.out.println("Number Of Files = " + retVal); 4455 } 4456 else 4457 { 4458 helpMsg.append("ERROR: Cannot find the Directory named:"); 4459 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4460 helpMsg.append(args[i]); 4461 System.out.println(helpMsg.toString()); 4462 } 4463 } 4464 } 4465 else 4466 { 4467 helpMsg.append("ERROR: The countFilesInDir method requires 1"); 4468 helpMsg.append(" directory name to operate."); 4469 System.out.println(helpMsg.toString()); 4470 } 4471 } 4472 // ***************************************************** 4473 else if (args[0].equals("tokenReplaceInFile")) 4474 { 4475 if (args.length == 4) 4476 { 4477 File rootFile = new File(args[1]); 4478 if (rootFile != null && !rootFile.isDirectory() && rootFile.canRead()) 4479 { 4480 tokenReplaceInFile(args[1], args[2], args[3]); 4481 } 4482 else 4483 { 4484 helpMsg.append("ERROR: Cannot find the file named:"); 4485 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4486 helpMsg.append(args[1]); 4487 System.out.println(helpMsg.toString()); 4488 } 4489 } 4490 else 4491 { 4492 helpMsg.append("ERROR: The tokenReplaceInFile method requires"); 4493 helpMsg.append(" 3 parameters:\n a file name to operate on,\n"); 4494 helpMsg.append("the the token string to search for in the file, and \n"); 4495 helpMsg.append("the replacement string"); 4496 System.out.println(helpMsg.toString()); 4497 } 4498 } 4499 // ***************************************************** 4500 else if (args[0].equals("tokenReplaceInRecursedFile")) 4501 { 4502 boolean recurseSubdirs = true; 4503 if (args.length == 4) 4504 { 4505 File rootFile = new File(args[1]); 4506 if (rootFile != null && rootFile.canRead()) 4507 { 4508 tokenReplaceInFile(args[1], args[2], args[3], true); 4509 } 4510 else 4511 { 4512 4513 helpMsg.append("ERROR: Cannot find the file named:"); 4514 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4515 helpMsg.append(args[1]); 4516 System.out.println(helpMsg.toString()); 4517 } 4518 } 4519 else 4520 { 4521 helpMsg.append("ERROR: The tokenReplaceInRecursedFile method requires"); 4522 helpMsg.append(" 3 parameters:\n a file name to operate on,\n"); 4523 helpMsg.append("the the token string to search for in the file, and \n"); 4524 helpMsg.append("the replacement string"); 4525 System.out.println(helpMsg.toString()); 4526 } 4527 } 4528 // ***************************************************** 4529 else if (args[0].equals("dirSize")) 4530 { 4531 if (args.length >1) 4532 { 4533 File tmpDirFile = null; 4534 for (int i=1; i < args.length; i++) 4535 { 4536 if ((tmpDirFile = initDirFile(args[i])) != null) 4537 { 4538 long retVal = dirSize(args[i], true); 4539 DecimalFormat decForm = new DecimalFormat("##0.000E0"); 4540 String formattedRetVal = decForm.format(retVal); 4541 if ((formattedRetVal.substring(formattedRetVal.length()-1)). 4542 equals("9")) 4543 formattedRetVal = 4544 formattedRetVal.substring(0,formattedRetVal.length()-2)+" Gb"; 4545 else if ((formattedRetVal.substring(formattedRetVal.length()-1)). 4546 equals("6")) 4547 formattedRetVal = 4548 formattedRetVal.substring(0,formattedRetVal.length()-2)+" Mb"; 4549 else if ((formattedRetVal.substring(formattedRetVal.length()-1)). 4550 equals("3")) 4551 formattedRetVal = 4552 formattedRetVal.substring(0,formattedRetVal.length()-2)+" kb"; 4553 4554 //formattedRetVal = decForm.format(retVal); 4555 System.out.println("Directory size = " + formattedRetVal); 4556 4557 } 4558 else 4559 { 4560 helpMsg.append("ERROR: Cannot find the Directory named:"); 4561 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4562 helpMsg.append(args[i]); 4563 System.out.println(helpMsg.toString()); 4564 } 4565 } 4566 } 4567 else 4568 { 4569 helpMsg.append("ERROR: The dirSize method requires 1"); 4570 helpMsg.append(" directory name to operate."); 4571 System.out.println(helpMsg.toString()); 4572 } 4573 } 4574 // ***************************************************** 4575 else if (args[0].equals("dirSize2")) 4576 { 4577 if (args.length >1) 4578 { 4579 File tmpDirFile = null; 4580 for (int i=1; i < args.length; i++) 4581 { 4582 if ((tmpDirFile = initDirFile(args[i])) != null) 4583 { 4584 long retVal = dirSize2(args[i], true); 4585 DecimalFormat decForm = new DecimalFormat("##0.000E0"); 4586 String formattedRetVal = decForm.format(retVal); 4587 if ((formattedRetVal.substring(formattedRetVal.length()-1)). 4588 equals("9")) 4589 formattedRetVal = 4590 formattedRetVal.substring(0,formattedRetVal.length()-2)+" Gb"; 4591 else if ((formattedRetVal.substring(formattedRetVal.length()-1)). 4592 equals("6")) 4593 formattedRetVal = 4594 formattedRetVal.substring(0,formattedRetVal.length()-2)+" Mb"; 4595 else if ((formattedRetVal.substring(formattedRetVal.length()-1)). 4596 equals("3")) 4597 formattedRetVal = 4598 formattedRetVal.substring(0,formattedRetVal.length()-2)+" kb"; 4599 4600 //formattedRetVal = decForm.format(retVal); 4601 System.out.println("Directory size = " + formattedRetVal); 4602 4603 } 4604 else 4605 { 4606 helpMsg.append("ERROR: Cannot find the Directory named:"); 4607 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4608 helpMsg.append(args[i]); 4609 System.out.println(helpMsg.toString()); 4610 } 4611 } 4612 } 4613 else 4614 { 4615 helpMsg.append("ERROR: The dirSize method requires 1"); 4616 helpMsg.append(" directory name to operate."); 4617 System.out.println(helpMsg.toString()); 4618 } 4619 } 4620 // ***************************************************** 4621 else if (args[0].equals("capsToSpacesInString")) 4622 { 4623 if (args.length >1) 4624 { 4625 StringBuffer result = new StringBuffer(); 4626 for (int i=1; i< args.length; i++) 4627 { 4628 result.append(capsToSpacesInString(args[i])); 4629 result.append(" "); 4630 } 4631 System.out.println(result.toString().trim()); 4632 } 4633 else 4634 { 4635 helpMsg.append("ERROR: The capsToSpacesInString method requires"); 4636 helpMsg.append(" at least 1 String Argument to operate."); 4637 System.out.println(helpMsg.toString()); 4638 } 4639 } 4640 // ***************************************************** 4641 else if (args[0].equals("spacesToCapsInString")) 4642 { 4643 if (args.length >1) 4644 { 4645 StringBuffer result = new StringBuffer(); 4646 for (int i=1; i< args.length; i++) 4647 { 4648 result.append(args[i]); 4649 result.append(" "); 4650 } 4651 System.out.println(spacesToCapsInString(result.toString().trim())); 4652 } 4653 else 4654 { 4655 helpMsg.append("ERROR: The spacesToCapsInString method requires"); 4656 helpMsg.append(" at least 1 String Argument to operate."); 4657 System.out.println(helpMsg.toString()); 4658 } 4659 } 4660 // ***************************************************** 4661 else if (args[0].equals("spacesToCapsInDir")) 4662 { 4663 if (args.length >1) 4664 { 4665 for (int i=1; i< args.length; i++) 4666 { 4667 spacesToCapsInDir(args[i].toString().trim()); 4668 } 4669 } 4670 else 4671 { 4672 helpMsg.append("ERROR: The spacesToCapsInFilenames method requires"); 4673 helpMsg.append(" at least 1 String Argument to specify the dir to parse for filenames."); 4674 System.out.println(helpMsg.toString()); 4675 } 4676 } 4677 // ***************************************************** 4678 else if (args[0].equals("removeParentRelativeReference")) 4679 { 4680 if (args.length >1) 4681 { 4682 for (int i=1; i< args.length; i++) 4683 { 4684 System.out.println(removeParentRelativeReference(args[i].trim())); 4685 } 4686 } 4687 else 4688 { 4689 helpMsg.append("ERROR: The removeParentRelativeReference method requires"); 4690 helpMsg.append(" at least 1 path String Argument to operate."); 4691 System.out.println(helpMsg.toString()); 4692 } 4693 } 4694 // ***************************************************** 4695 else if (args[0].equals("sleep")) 4696 { 4697 if (args.length >1) 4698 { 4699 sleep(Integer.parseInt(args[1])); 4700 //System.out.println(sleep(Integer.parseInt(args[1]))); 4701 } 4702 else 4703 { 4704 helpMsg.append("ERROR: The sleep method requires"); 4705 helpMsg.append(" the sleep time specified in ms."); 4706 System.out.println(helpMsg.toString()); 4707 } 4708 } 4709 // ***************************************************** 4710 else if (args[0].equalsIgnoreCase("testHexConverters")) 4711 { 4712 if (args.length >1) 4713 { 4714 int d = 0; 4715 Vector cmdArgs = new Vector(); 4716 for (int i=1; i< args.length; i++) 4717 { 4718 d=Integer.parseInt(args[i]); 4719 System.out.println("\n----------- "+d+" -----------\n"); 4720 System.out.println("decimalToHexadecimal : " +decimalToHexadecimal(d)); 4721 System.out.println("convertStringToHex : " +convertStringToHex(""+d)); 4722 System.out.println("toHEXString : " +toHEXString(d) + " ("+convertHexNumberStringToDecimal(toHEXString(d))+")"); 4723 } 4724 } 4725 else 4726 { 4727 helpMsg.append("ERROR: The testHexConverters method requires"); 4728 helpMsg.append(" at least 1 decimal number to test Convert to HEX."); 4729 System.out.println(helpMsg.toString()); 4730 } 4731 } 4732 // ***************************************************** 4733 else if (args[0].equals("executeNativeApp")) 4734 { 4735 if (args.length >1) 4736 { 4737 Vector cmdArgs = new Vector(); 4738 for (int i=2; i< args.length; i++) 4739 { 4740 cmdArgs.add(args[i]); 4741 } 4742 System.out.println("\nexecuteNativeApp: Output Sent to std out."); 4743 boolean verboseScreenOutput = true; 4744 //executeNativeApp(args[1], cmdArgs, "appOut.txt", verboseScreenOutput); 4745 System.out.println(executeNativeApp(args[1], cmdArgs, verboseScreenOutput)); 4746 //System.out.println(sleep(Integer.parseInt(args[1]))); 4747 } 4748 else 4749 { 4750 helpMsg.append("ERROR: The executeNativeApp method requires"); 4751 helpMsg.append(" at least a name of an executable to run."); 4752 System.out.println(helpMsg.toString()); 4753 } 4754 } 4755 // ***************************************************** 4756 else if (args[0].startsWith("findFile")) 4757 { 4758 if (args.length >1 && args.length <6) 4759 { 4760 boolean recurseSubdirs = true; 4761 boolean regExp = false; 4762 boolean verbose = true; 4763 String directory = System.getProperty("user.dir"); 4764 String searchForStr = args[1]; 4765 if (args.length < 3) 4766 { 4767 recurseSubdirs = true; 4768 regExp = false; 4769 verbose = true; 4770 directory = System.getProperty("user.dir"); 4771 searchForStr = args[1]; 4772 } 4773 else if (args.length <4) 4774 { 4775 recurseSubdirs = true; 4776 regExp = false; 4777 verbose = true; 4778 directory = args[2]; 4779 searchForStr = args[1]; 4780 } 4781 else if (args.length <5 ) 4782 { 4783 recurseSubdirs = Boolean.valueOf(args[3]).booleanValue(); 4784 regExp = false; 4785 verbose = true; 4786 directory = args[2]; 4787 searchForStr = args[1]; 4788 } 4789 else if (args.length <6 ) 4790 { 4791 recurseSubdirs = Boolean.valueOf(args[3]).booleanValue(); 4792 regExp = Boolean.valueOf(args[4]).booleanValue(); 4793 verbose = true; 4794 directory = args[2]; 4795 searchForStr = args[1]; 4796 } 4797 4798 StringBuffer summary = new StringBuffer(); 4799 summary.append((recurseSubdirs?"Recursive search for\n ":"Search for\n ")); 4800 summary.append((regExp?"regular expression '":"")); 4801 summary.append(searchForStr); 4802 summary.append((regExp?"'\n":"\n")); 4803 summary.append("starting in directory:\n "); 4804 summary.append(directory); 4805 //System.out.println(summary.toString()); 4806 findFile(searchForStr, directory, recurseSubdirs, regExp, verbose ); 4807 } 4808 else 4809 { 4810 helpMsg.append("ERROR: The findFiles method requires"); 4811 helpMsg.append(" at least a filename to find from the recursed current dir.\n\n"); 4812 helpMsg.append(" You can optionally specify the following:\n"); 4813 helpMsg.append(" findFile filename [directoryToStart] [recurse] [regExp]\n"); 4814 helpMsg.append(" directoryToStart is the directory to start looking\n"); 4815 helpMsg.append(" recurse (true or false) to specify if the "); 4816 helpMsg.append("sub-dirs should be recursed\n"); 4817 helpMsg.append(" regExp (true or false) to specify if the "); 4818 helpMsg.append("filename parameter should be trerated as a regular expression\n"); 4819 helpMsg.append(SYSTEM_LINE_SEPERATOR); 4820 helpMsg.append(" - if using a regExp - the fileToFind param is a quoted Java regExp such as \"[*.png]\" or \"[a-zA-Z*.zip]\""); 4821 System.out.println(helpMsg.toString()); 4822 } 4823 } 4824 // ***************************************************** 4825 else if (args[0].equals("searchInFile")) 4826 { 4827 if (args.length > 2) 4828 { 4829 boolean recurseSubdirs = false; 4830 boolean fileRegExp = false; 4831 boolean verbose = true; 4832 String fileName = args[1]; 4833 String searchStr = args[2]; 4834 4835 recurseSubdirs = true; 4836 fileRegExp = false; 4837 verbose = true; 4838 fileName = args[1]; 4839 StringBuffer sb = new StringBuffer(args[2]); 4840 for (int i = 3; i < args.length; i++) 4841 { 4842 sb.append(" "); 4843 sb.append(args[i]); 4844 } 4845 searchStr = sb.toString(); 4846 /* 4847 else if (args.length <5 ) 4848 { 4849 recurseSubdirs = Boolean.valueOf(args[3]).booleanValue(); 4850 regExp = false; 4851 verbose = true; 4852 directory = args[2]; 4853 searchForStr = args[1]; 4854 } 4855 else if (args.length <6 ) 4856 { 4857 recurseSubdirs = Boolean.valueOf(args[3]).booleanValue(); 4858 regExp = Boolean.valueOf(args[4]).booleanValue(); 4859 verbose = true; 4860 directory = args[2]; 4861 searchForStr = args[1]; 4862 } 4863 */ 4864 File rootFile = new File(fileName); 4865 4866 StringBuffer summary = new StringBuffer(); 4867 summary.append((recurseSubdirs?"Recursive search for \"":"Search for \"")); 4868 summary.append(searchStr); 4869 summary.append("\" starting in file: "); 4870 summary.append(fileName); 4871 if (rootFile != null && !rootFile.isDirectory()) 4872 { 4873 if(rootFile.canRead()) 4874 { 4875 String [] ret = searchInFile(searchStr, fileName, true); 4876 summary.append("\nReturned Lines:"); 4877 for (int i = 0; i < ret.length; i++) 4878 { 4879 summary.append(ret[i]); 4880 summary.append("\n"); 4881 } 4882 } 4883 } 4884 else 4885 { 4886 Hashtable retVal = 4887 searchInFile(searchStr, fileName, recurseSubdirs, fileRegExp, verbose); 4888 if (retVal != null) 4889 { 4890 String currFilename = ""; 4891 Vector lineNums = null; 4892 summary.append("\nReturned Hashtable:"); 4893 for (Enumeration e = retVal.keys() ; e.hasMoreElements() ;) 4894 { 4895 currFilename = (String) e.nextElement(); 4896 summary.append("\n "); 4897 summary.append(currFilename); 4898 summary.append(" - "); 4899 lineNums = (Vector) retVal.get(currFilename); 4900 for (int i = 0; i < lineNums.size(); i++) 4901 { 4902 summary.append(((Integer)lineNums.get(i)).toString()); 4903 if ( (i + 1) < lineNums.size()) summary.append(", "); 4904 } 4905 } 4906 } 4907 } 4908 System.out.println(summary.toString()); 4909 } 4910 else 4911 { 4912 // print searchInFile ERROR msg 4913 } 4914 } 4915 // ***************************************************** 4916 else if (args[0].equals("renameFile")) 4917 { 4918 if (args.length > 2) 4919 { 4920 boolean verbose = true; 4921 String fromFilename = args[1]; 4922 String toFilename = args[2]; 4923 if(toFilename.contains(SYSTEM_FILE_SEPERATOR)) toFilename.substring(toFilename.lastIndexOf(SYSTEM_FILE_SEPERATOR)); 4924 4925 String retVal = renameFile(fromFilename, toFilename); 4926 if (retVal!=null && !"".equals(retVal)) 4927 { 4928 System.out.println("Successfully renamed file to: "+retVal); 4929 } 4930 else 4931 { 4932 System.out.println("Error reanming file: "+fromFilename + " to "+toFilename); 4933 } 4934 } 4935 else 4936 { 4937 // print searchInFile ERROR msg 4938 } 4939 } 4940 // ***************************************************** 4941 else if (args[0].equals("zipFile")) 4942 { 4943 if (args.length > 1) 4944 { 4945 boolean verbose = true; 4946 String fileName = args[1]; 4947 4948 String zipFilename = compressFileWithZip(fileName); 4949 if (zipFilename!=null) 4950 { 4951 System.out.println("Successfully compressed file: "+zipFilename); 4952 } 4953 else 4954 { 4955 System.out.println("Error compresing file: "+fileName); 4956 } 4957 } 4958 else 4959 { 4960 // print searchInFile ERROR msg 4961 } 4962 } 4963 // ***************************************************** 4964 else if (args[0].equals("removeOldFiles")) 4965 { 4966 if (args.length >2) 4967 { 4968 removeOldFiles(args[1], Integer.parseInt(args[2]), 4969 (args.length>3?(args[3]!=null&&args[3].equals(true)?true:false):false)); 4970 } 4971 else 4972 { 4973 helpMsg.append("ERROR: The removeOldFiles method requires 1"); 4974 helpMsg.append(" directory name, 1 number for thee days old and an optional true/false to recurse"); 4975 System.out.println(helpMsg.toString()); 4976 } 4977 } 4978 // ***************************************************** 4979 /* 4980 else if (args[0].equalsIgnoreCase("testGis")) 4981 { 4982 if (args.length >2) 4983 { 4984 System.out.println(" Looking Up x="+args[1]+" Y="+args[2]); 4985 getBCHAssetLatLong(Double.parseDouble(args[1]), Double.parseDouble(args[2])); 4986 } 4987 else 4988 { 4989 helpMsg.append("ERROR: The testGis method requires an x and a y"); 4990 System.out.println(helpMsg.toString()); 4991 } 4992 } 4993 */ 4994 // ***************************************************** 4995 else if (args[0].equals("createCurrentTimeStamp")) 4996 { 4997 System.out.println(createCurrentTimeStamp()); 4998 } 4999 else if (args[0].equals("createCurrentDateTimeStamp")) 5000 { 5001 System.out.println(createCurrentDateTimeStamp()); 5002 } 5003 else 5004 { 5005 System.out.println("Unknown Command: "+args[0]); 5006 } 5007 5008 } 5009 } 5010}