PageRenderTime 28ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/projects/joggplayer-1.1.4s/src/ca/bc/webarts/widgets/Util.java

https://gitlab.com/essere.lab.public/qualitas.class-corpus
Java | 1732 lines | 1071 code | 141 blank | 520 comment | 245 complexity | b786fbb645f858eb9a90dd0e6c214010 MD5 | raw file
  1. /*
  2. * $Source: /cvsroot2/open/projects/WebARTS/ca/bc/webarts/widgets/Util.java,v $
  3. * $Name: $
  4. *
  5. * $Revision: 1.21 $
  6. * $Date: 2005-04-10 11:53:16 -0700 (Sun, 10 Apr 2005) $
  7. * $Locker: $
  8. *
  9. *
  10. * Written by Tom Gutwin - WebARTS Design.
  11. * Copyright (C) 2001 WebARTS Design, North Vancouver Canada
  12. * http://www.webarts.bc.ca
  13. *
  14. * This program is free software; you can redistribute it and/or modify
  15. * it under the terms of the GNU General Public License as published by
  16. * the Free Software Foundation; either version 2 of the License, or
  17. * (at your option) any later version.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU General Public License
  25. * along with this program; if not, write to the Free Software
  26. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  27. */
  28. package ca.bc.webarts.widgets;
  29. import ca.bc.webarts.tools.Log;
  30. import ca.bc.webarts.tools.StreamGobbler;
  31. import gnu.regexp.RE;
  32. import gnu.regexp.REException;
  33. import java.awt.Component;
  34. import java.awt.Frame;
  35. import java.awt.Image;
  36. import java.awt.Toolkit;
  37. import java.io.BufferedReader;
  38. import java.io.File;
  39. import java.io.FileNotFoundException;
  40. import java.io.FileOutputStream;
  41. import java.io.FileReader;
  42. import java.io.IOException;
  43. import java.io.InputStream;
  44. import java.io.PrintStream;
  45. import java.net.InetAddress;
  46. import java.net.MalformedURLException;
  47. import java.net.URL;
  48. import java.net.UnknownHostException;
  49. import java.text.DecimalFormat;
  50. import java.util.Calendar;
  51. import java.util.Date;
  52. import java.util.Enumeration;
  53. import java.util.Hashtable;
  54. import java.util.Iterator;
  55. import java.util.List;
  56. import java.util.Vector;
  57. import java.util.jar.JarEntry;
  58. import java.util.jar.JarFile;
  59. import javax.swing.ImageIcon;
  60. import javax.swing.JFileChooser;
  61. import javax.swing.JFrame;
  62. import javax.swing.SwingUtilities;
  63. import javax.swing.UIManager;
  64. import java.io.*;
  65. import org.apache.tools.ant.util.FileUtils;
  66. import org.apache.tools.ant.taskdefs.Replace;
  67. /**
  68. * A set of useful utility methods/functions for reuse.
  69. *
  70. * @author Tom Gutwin P.Eng
  71. */
  72. public class Util
  73. {
  74. /** A holder for this clients System File Separator. */
  75. public final static String SYSTEM_FILE_SEPERATOR = File.separator;
  76. /** A holder for this clients System line termination separator. */
  77. public final static String SYSTEM_LINE_SEPERATOR =
  78. System.getProperty("line.separator");
  79. /**
  80. * A constant to specify which dialog to open with the chooseFileDialog.
  81. */
  82. public final static short OPEN_DIALOG = 0;
  83. /**
  84. * A constant to specify which dialog to open with the chooseFileDialog.
  85. */
  86. public final static short SAVE_DIALOG = 1;
  87. /** The VM classpath (used in some methods).. */
  88. public static String CLASSPATH = System.getProperty("class.path");
  89. /** The users home ditrectory. */
  90. public static String USERHOME = System.getProperty("user.home");
  91. /** The users pwd ditrectory. */
  92. public static String USERDIR = System.getProperty("user.dir");
  93. /** A holder This classes name (used when logging). */
  94. private static String CLASSNAME = "ca.bc.webarts.widgets.Util";
  95. /**
  96. * the Metal LookAndFeel CONSTANT.
  97. */
  98. public static final short METAL_LOOKANDFEEL = 0;
  99. /**
  100. * the Windoze LookAndFeel CONSTANT.
  101. */
  102. public static final short WINDOZE_LOOKANDFEEL = 1;
  103. /**
  104. * the Motif LookAndFeel CONSTANT.
  105. */
  106. public static final short MOTIF_LOOKANDFEEL = 2;
  107. /**
  108. * the Mac LookAndFeel CONSTANT.
  109. */
  110. public static final short MAC_LOOKANDFEEL = 3;
  111. /**
  112. * the Default LookAndFeel CONSTANT. DEFAULT_LOOKANDFEEL = METAL_LOOKANDFEEL
  113. */
  114. public static final short DEFAULT_LOOKANDFEEL = METAL_LOOKANDFEEL;
  115. /**
  116. * the Mac LookAndFeel class name
  117. */
  118. public static String macClassName =
  119. "com.sun.java.swing.plaf.mac.MacLookAndFeel";
  120. /**
  121. * the Java LookAndFeel class name
  122. */
  123. public static String metalClassName =
  124. "javax.swing.plaf.metal.MetalLookAndFeel";
  125. /**
  126. * the motif LookAndFeel class name
  127. */
  128. public static String motifClassName =
  129. "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
  130. /**
  131. * the Windoze LookAndFeel class name
  132. */
  133. public static String windowsClassName =
  134. "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
  135. /** Gets a Log instance in case any calling classes are using it. */
  136. private static Log log_ = Log.getInstance();
  137. /** Class flag signifying if the initUtil method has been called */
  138. private static boolean initUtil = false;
  139. /** Class flag for the threadWatchdog method to enable the calling user
  140. * to stop the watch. */
  141. public static boolean watchdogReset = false;
  142. /** Inits the log and some other vars.*/
  143. private static synchronized void initUtil()
  144. {
  145. final String methodName = CLASSNAME + ": initUtil()";
  146. if (!initUtil || log_ == null)
  147. {
  148. //System.out.println("Into the init block");
  149. log_ = Log.getInstance();
  150. if (log_ != null)
  151. {
  152. log_.setLogLevel(Log.MAJOR);
  153. log_.startMethod(methodName);
  154. }
  155. CLASSPATH = System.getProperty("java.class.path");
  156. //System.out.println("In "+methodName);
  157. initUtil = true;
  158. if (log_ != null)
  159. {
  160. log_.endMethod();
  161. }
  162. }
  163. }
  164. /**
  165. * Ensures that a folder exists.
  166. * <TABLEWIDTH="100%" BORDER="0" CELLSPACING="1" CELLPADDING="2">
  167. *
  168. * <TR>
  169. *
  170. * <TDCOLSPAN="2">
  171. * <H2>Ensures that a folder exists</H2>
  172. * </TD>
  173. *
  174. * </TR>
  175. *
  176. * <TR>
  177. *
  178. * <TDCOLSPAN="2">
  179. * &nbsp;<BR>
  180. * <B>Description:</B> <BR>
  181. * use it like this: <br>
  182. * ensureFolderExists(new File(fileName).getParentFile());
  183. * </TD>
  184. *
  185. * </TR>
  186. *
  187. * </TABLE>
  188. *
  189. *
  190. * @param folder The File object to check.
  191. */
  192. public static void ensureFolderExists(File folder)
  193. {
  194. //System.out.println(" 1 Making Dir: "+folder.getAbsolutePath());
  195. if ((folder != null) && !(folder.isDirectory() ))
  196. {
  197. //System.out.println(" 2 Making Dir: "+folder.getAbsolutePath());
  198. ensureFolderExists(folder.getParentFile());
  199. //System.out.print(" 3 Making Dir: "+folder.getAbsolutePath());
  200. boolean suc = folder.mkdir();
  201. //System.out.println(" -->"+(suc?"Successful":"Failed"));
  202. }
  203. }
  204. public static void ensureFolderExists(String foldername)
  205. {
  206. if (foldername != null && !foldername.equals(""))
  207. {
  208. File folder = new File(foldername);
  209. ensureFolderExists(folder);
  210. }
  211. }
  212. /**
  213. * Moves the specified file to the specified directory. It will create
  214. * the target dir if it does not exist.
  215. *
  216. * @param filename is the absoulte pathname of the file to move.
  217. * @param foldername is the directory to move it to.
  218. **/
  219. public static boolean moveFile(String filename, String foldername)
  220. {
  221. boolean retVal = false;
  222. if (foldername != null && !foldername.equals("") &&
  223. filename != null && !filename.equals(""))
  224. {
  225. File fromFile = new File(filename);
  226. if (fromFile != null && fromFile.exists())
  227. {
  228. File folder = new File(foldername);
  229. ensureFolderExists(folder);
  230. File toFile = new File(foldername+File.separator+fromFile.getName());
  231. retVal = fromFile.renameTo(toFile);
  232. if (!retVal)
  233. {
  234. // Try Native move call
  235. String [] ss = {filename,foldername};
  236. String ret = executeNativeApp("/bin/mv",ss,false);
  237. System.out.println(" Native mv: "+ ret);
  238. }
  239. }
  240. }
  241. return retVal;
  242. }
  243. /**
  244. * A simple byte to Hex String converter.
  245. *
  246. * @param b The byte to convert
  247. * @return The resultant Hex String
  248. */
  249. public static String toHEXString(byte b)
  250. {
  251. return ("" + "0123456789ABCDEF".charAt(0xf & b >> 4) +
  252. "0123456789ABCDEF".charAt(b & 0xF));
  253. }
  254. /**
  255. * SetsIcon for the passed in Frame
  256. *
  257. * @param imageFilename - is the filename for the new icon
  258. * @param appFrame The new iconForApp value
  259. */
  260. public static void setIconForApp(JFrame appFrame, String imageFilename)
  261. {
  262. setIconForApp(appFrame, Util.class.getResource(imageFilename));
  263. }
  264. // end of setIconForApp
  265. /**
  266. * SetsIcon for the passed in Frame
  267. *
  268. * @param imageUrl - is the URL for the new icon
  269. * @param appFrame The new iconForApp value
  270. */
  271. public static void setIconForApp(JFrame appFrame, URL imageUrl)
  272. {
  273. ImageIcon image = new ImageIcon(imageUrl);
  274. appFrame.setIconImage(image.getImage());
  275. image = null;
  276. }
  277. // end of setIconForApp
  278. /**
  279. * Creates a timestamp for the current date. It is in the form of 'year +
  280. * "-" + month "-" + date "-" + hour "-" + seconds<br>
  281. * For example: 2003-245
  282. *
  283. * @return The CurrentDateTime value.
  284. */
  285. public static String createCurrentDateTime()
  286. {
  287. Calendar calendar_ = Calendar.getInstance();
  288. return ""+ calendar_.get(Calendar.YEAR) + "-" +
  289. calendar_.get(Calendar.MONTH)+ "-" +
  290. calendar_.get(Calendar.DATE)+ "-" +
  291. calendar_.get(Calendar. HOUR_OF_DAY )+ "-" +
  292. calendar_.get(Calendar.MINUTE);
  293. }
  294. /**
  295. * Creates a timestamp for the current date. It is in the form of 'year +
  296. * "-" + dayNum <br>
  297. * For example: 2003-245
  298. *
  299. * @return The CurrentTimeStamp value.
  300. */
  301. public static String createCurrentDateStamp()
  302. {
  303. Calendar calendar_ = Calendar.getInstance();
  304. return ""+ calendar_.get(Calendar.YEAR) + "-" +
  305. calendar_.get(Calendar.DAY_OF_YEAR);
  306. }
  307. /**
  308. * Creates a timestamp for the current date and time. It is in the form of 'year +
  309. * "-" + dayNum + "-" + hour + "-" + min + "-" + sec + "-" + millis'.<br>
  310. * For example: 2003-245-14-34-52-224
  311. *
  312. * @return The CurrentTimeStamp value.
  313. */
  314. public static String createCurrentDateTimeStamp()
  315. {
  316. Calendar calendar_ = Calendar.getInstance();
  317. return ""+ calendar_.get(Calendar.YEAR) + "-" +
  318. calendar_.get(Calendar.DAY_OF_YEAR) + "-" +createCurrentTimeStamp();
  319. }
  320. /**
  321. * Creates a timestamp for the current time in the form of 'hour + "-" + min
  322. * + "-" + sec + "-" + millis'.
  323. *
  324. * @return The CurrentTimeStamp value.
  325. */
  326. public static String createCurrentTimeStamp()
  327. {
  328. String value = "";
  329. Calendar calendar_ = Calendar.getInstance();
  330. int currMillis = calendar_.get(calendar_.MILLISECOND);
  331. String millis = String.valueOf(currMillis);
  332. if (currMillis < 10)
  333. {
  334. millis = "00" + currMillis;
  335. }
  336. else if (currMillis < 100)
  337. {
  338. millis = "0" + currMillis;
  339. }
  340. int currSec = calendar_.get(calendar_.SECOND);
  341. String sec = String.valueOf(currSec);
  342. if (currSec < 10)
  343. {
  344. sec = "0" + currSec;
  345. }
  346. int currMin = calendar_.get(calendar_.MINUTE);
  347. String min = String.valueOf(currMin);
  348. if (currMin < 10)
  349. {
  350. min = "0" + currMin;
  351. }
  352. int currHr = calendar_.get(calendar_.HOUR_OF_DAY);
  353. String hour = String.valueOf(currHr);
  354. if (currHr < 10)
  355. {
  356. hour = "0" + currHr;
  357. }
  358. return (String) hour + "-" + min + "-" + sec + "-" + millis;
  359. }
  360. /**
  361. * Creates a Timer timestamp from the current time to the passed startTime
  362. * in the form of <BR>
  363. * 'hour + "-" + min + "-" + sec + "-" + millis'.
  364. *
  365. * THIS METHOD IS NOT COMPLETED. IT DOES NOT WORK YET.
  366. *
  367. * @return The Timer Timestamp value.
  368. */
  369. public static String createTimerTimeStamp(int startTimeMillis)
  370. {
  371. String value = "";
  372. Calendar calendar_ = Calendar.getInstance();
  373. int currMillis = calendar_.get(calendar_.MILLISECOND) - startTimeMillis;
  374. String millis = String.valueOf(currMillis);
  375. int currSec = calendar_.get(calendar_.SECOND);
  376. String sec = String.valueOf(currSec);
  377. int currMin = calendar_.get(calendar_.MINUTE);
  378. String min = String.valueOf(currMin);
  379. int currHr = calendar_.get(calendar_.HOUR_OF_DAY);
  380. String hour = String.valueOf(currHr);
  381. if (currMillis < 10)
  382. {
  383. millis = "00" + currMillis;
  384. }
  385. else if (currMillis < 100)
  386. {
  387. millis = "0" + currMillis;
  388. }
  389. if (currSec < 10)
  390. {
  391. sec = "0" + currSec;
  392. }
  393. if (currMin < 10)
  394. {
  395. min = "0" + currMin;
  396. }
  397. if (currHr < 10)
  398. {
  399. hour = "0" + currHr;
  400. }
  401. return (String) hour + "-" + min + "-" + sec + "-" + millis;
  402. }
  403. /**
  404. * A simple String token replacement routine. Replaces all occurences of the
  405. * token parameter with the replacement value in the passed in sentence
  406. * parameter.
  407. *
  408. * @param sentence The String to perform the token replacement on
  409. * @param token the token String to seartch for and replace
  410. * @param replacement the tokens replacement value
  411. * @return The new token replaced string
  412. */
  413. public static String tokenReplace(String sentence,
  414. String token,
  415. String replacement)
  416. {
  417. initUtil();
  418. final String methodName = CLASSNAME + ": tokenReplace(" +
  419. sentence + " " + token + " " + replacement;
  420. if (log_ != null)
  421. {
  422. log_.startMethod(methodName);
  423. }
  424. int a = 0;
  425. String retVal = "";
  426. while ((a = sentence.indexOf(token)) > -1)
  427. {
  428. retVal += sentence.substring(0, a) + replacement;
  429. sentence = sentence.substring(a + token.length());
  430. // System.out.println(wort);
  431. }
  432. // if a > -1
  433. retVal += sentence;
  434. if (log_ != null)
  435. {
  436. log_.endMethod();
  437. }
  438. return retVal;
  439. }
  440. /**
  441. * Recursively deletes all the files in the spec'd directory and
  442. * subdirectories, and then removes the dir.
  443. *
  444. * @param fileName The filename of the directory to delete.
  445. */
  446. public static boolean removeDir(String fileName)
  447. {
  448. initUtil();
  449. boolean retVal = false;
  450. File dirToDel = initDirFile(fileName);
  451. if (dirToDel != null)
  452. {
  453. String[] files = dirToDel.list();
  454. File tempFile;
  455. //loop through all the files in the dir DELETING them
  456. for (int i = 0; i < files.length; i++)
  457. {
  458. tempFile = new File(fileName + File.separator + files[i]);
  459. if (tempFile.isDirectory())
  460. {
  461. // recurse on the subdirectory
  462. removeDir(fileName + File.separator + files[i]);
  463. }
  464. else
  465. {
  466. // Delete all the files
  467. tempFile.delete();
  468. }
  469. }
  470. retVal = dirToDel.delete();
  471. }
  472. return retVal;
  473. }
  474. /**
  475. * Deletes a file.
  476. *
  477. * @param fileName The filename to delete.
  478. */
  479. public static boolean removeFile(String fileName)
  480. {
  481. initUtil();
  482. boolean retVal = false;
  483. if (fileName != null)
  484. {
  485. File tempFile = new File(fileName);
  486. if (tempFile != null && tempFile.exists())
  487. retVal = tempFile.delete();
  488. }
  489. return retVal;
  490. }
  491. /**
  492. * Deletes all files in the spec'd dir that are older than the spec'd
  493. * number of days.
  494. *
  495. * @param dirName The directory to parse for files to delete.
  496. * @param numDays The age of the files to delete.
  497. * @param recurse Do the removal recursively.
  498. */
  499. public static boolean removeOldFiles(String dirName,
  500. int numDays,
  501. boolean recurse)
  502. {
  503. initUtil();
  504. boolean retVal = false;
  505. final String methodName = CLASSNAME + ": removeOldFiles()";
  506. if (log_ != null)
  507. {
  508. log_.startMethod(methodName);
  509. }
  510. File dirFile = new File(dirName);
  511. if (dirFile.isDirectory() && dirFile.canRead())
  512. {
  513. String[] waste = dirFile.list();
  514. File tempFile = null;
  515. for (int i = 0; i < waste.length; i++)
  516. {
  517. tempFile = new File(dirName + File.separator + waste[i]);
  518. if (tempFile != null && !tempFile.isDirectory())
  519. {
  520. // if file is older than numDays... delete it
  521. long fileAge = tempFile.lastModified();
  522. Calendar rightNow = Calendar.getInstance();
  523. long rightNowInMillis = rightNow.getTimeInMillis();
  524. long numDaysInMillis = (new java.lang.Integer(numDays)).longValue() *
  525. 24l * 60l * 60l * 1000l;
  526. if (rightNowInMillis - fileAge > numDaysInMillis)
  527. {
  528. //delete the file
  529. System.out.println("Deleting file "+ tempFile.getPath());
  530. tempFile.delete();
  531. }
  532. }
  533. else if (tempFile != null && recurse)
  534. {
  535. removeOldFiles(dirName + File.separator + waste[i], numDays, recurse);
  536. }
  537. }
  538. }
  539. if (log_ != null)
  540. {
  541. log_.endMethod();
  542. }
  543. return retVal;
  544. }
  545. /**
  546. * Obtains the bytes of data contained in all files in this dir
  547. * (and subdirs).
  548. *
  549. * @param fileName The filename of the directory to delete.
  550. *
  551. * @return the size of the dir in bytes.
  552. */
  553. public static long dirSize(String fileName, boolean recurseSubdirs)
  554. {
  555. initUtil();
  556. long retVal = 0L;
  557. File dirToCalc = initDirFile(fileName);
  558. if (dirToCalc != null)
  559. {
  560. String[] files = dirToCalc.list();
  561. File tempFile;
  562. //loop through all the files in the dir
  563. if (files != null)
  564. {
  565. for (int i = 0; i < files.length; i++)
  566. {
  567. tempFile = new File(fileName + File.separator + files[i]);
  568. if (tempFile.isDirectory() && recurseSubdirs)
  569. {
  570. // recurse on the subdirectory
  571. retVal += dirSize(fileName + File.separator + files[i], true);
  572. }
  573. else
  574. {
  575. // add its size
  576. retVal += tempFile.length();
  577. }
  578. }
  579. }
  580. else
  581. log_.minor("Problem reading Directory "+fileName);
  582. }
  583. return retVal;
  584. }
  585. /**
  586. * Helper method to copy a file
  587. *
  588. * @param from the from filename
  589. * @param to the to filename
  590. **/
  591. public static void copyFile(String from, String to) throws IOException
  592. {
  593. File newFile = new File(to);
  594. if (newFile != null && newFile.exists())
  595. newFile.delete();
  596. (FileUtils.newFileUtils()).copyFile(from, to);
  597. }
  598. /**
  599. * Token replace method for a given filename and then saves the file with the
  600. * swapped tokens. If you don't want to overwrite the original file make a
  601. * copy 1st and then call this method on the copy.
  602. *
  603. * @param file The file(name) to act on
  604. * @param token The search token (that will get replaced)
  605. * @param value The replacement string.
  606. */
  607. public static void tokenReplaceInFile(String file, String token, String value)
  608. {
  609. Replace replace = new Replace();
  610. replace.setProject(new org.apache.tools.ant.Project());
  611. replace.setFile(new File(file));
  612. replace.setToken(token);
  613. replace.setValue(value);
  614. replace.execute();
  615. }// -- tokenReplaceInFile()
  616. /**
  617. * Abstracts the reading of a file and returns the contents as a String.
  618. *
  619. * @param fileName is the file naem to read into a String
  620. * @return the Text file contents as a String
  621. **/
  622. public static String readFileToString(String fileName)
  623. {
  624. String stringLine;
  625. BufferedReader in;
  626. StringBuffer stringOut = new StringBuffer();
  627. try
  628. {
  629. in = new BufferedReader(new FileReader(fileName));
  630. while ((stringLine = in.readLine()) != null)
  631. {
  632. stringOut.append(stringLine);
  633. stringOut.append(SYSTEM_LINE_SEPERATOR);
  634. }
  635. }
  636. catch (FileNotFoundException fnfEx)
  637. {
  638. System.out.println("Cannot find file: "+fileName);
  639. }
  640. catch (IOException ioEx)
  641. {
  642. System.out.println("Error Reading File to String: "+fileName);
  643. }
  644. return stringOut.toString();
  645. }
  646. /**
  647. * Searches the provided file for the search String.
  648. *
  649. * @param searchStr The searchString/regexp to search for.
  650. * @param filename The filename to search through.
  651. * @param verbose true will produce output to System.out just like the
  652. * UNIX find cmd
  653. *
  654. * @return an array of the matched lines
  655. */
  656. public static String [] searchInFile(String searchStr, String filename,
  657. boolean verbose)
  658. {
  659. initUtil();
  660. Vector retVal = new Vector();
  661. BufferedReader in;
  662. RE expression = null;
  663. String s;
  664. int regExFlags = RE.REG_ICASE;
  665. int numExtraBeforeLines = 2;
  666. String [] extraBeforeLines = new String [numExtraBeforeLines];
  667. int currLineNumber = 0;
  668. for (int i=0; i< numExtraBeforeLines ; i++)
  669. extraBeforeLines[i] = "";
  670. File rootFile = new File(filename);
  671. if (rootFile != null && !rootFile.isDirectory())
  672. {
  673. if(rootFile.canRead())
  674. {
  675. try
  676. {
  677. in = new BufferedReader(new FileReader(filename));
  678. currLineNumber = 0;
  679. while ((s = in.readLine()) != null)
  680. {
  681. currLineNumber++;
  682. expression = new RE(searchStr, regExFlags);
  683. if (expression.getMatch(s)!=null)
  684. {
  685. if ( verbose )
  686. {
  687. System.out.println("FILE: "+filename);
  688. for (int i=0; i< numExtraBeforeLines ; i++)
  689. System.out.println(" "+currLineNumber+extraBeforeLines[i]);
  690. System.out.println(" "+currLineNumber + " "+s);
  691. System.out.println();
  692. }
  693. retVal.addElement(s);
  694. }
  695. for (int i=0; i< numExtraBeforeLines-1 ; i++)
  696. extraBeforeLines[i] = extraBeforeLines[i+1];
  697. extraBeforeLines[numExtraBeforeLines-1] = s;
  698. }
  699. in.close();
  700. }
  701. catch (REException reEx)
  702. {
  703. reEx.printStackTrace();
  704. }
  705. catch (FileNotFoundException fEx)
  706. {
  707. fEx.printStackTrace();
  708. }
  709. catch (IOException ioEx)
  710. {
  711. ioEx.printStackTrace();
  712. }
  713. }
  714. }
  715. String [] rets = new String [retVal.size()];
  716. for (int i=0; i < retVal.size(); i++)
  717. {
  718. rets[i] = (String) retVal.elementAt(i);
  719. }
  720. return rets;
  721. }
  722. /**
  723. * Searches the provided file/directory (and subdirs) for the search String.
  724. *
  725. * @param searchStr The searchString/regexp to search for.
  726. * @param filename The filename/directoryName to search through.
  727. * @param recurseSubdirs Flags if the sub-dirs are searched.
  728. * @param fileRegExp Flags if 'fileName' should be regarded as a regular
  729. * expression.
  730. * @param verbose true will produce output to System.out just like the
  731. * UNIX find cmd
  732. *
  733. * @return a hash of the full cannoical paths/and a Vector of the lineNumbers
  734. * in that file
  735. */
  736. public static Hashtable searchInFile(String searchStr, String filename,
  737. boolean recurseSubdirs, boolean fileRegExp,
  738. boolean verbose)
  739. {
  740. initUtil();
  741. Hashtable retVal = new Hashtable();
  742. Vector fileLineNumbers = new Vector();
  743. BufferedReader in;
  744. RE expression = null;
  745. String s;
  746. int regExFlags = RE.REG_ICASE;
  747. int numExtraBeforeLines = 2;
  748. String [] extraBeforeLines = new String [numExtraBeforeLines];
  749. String currFilename;
  750. int currLineNumber = 0;
  751. for (int i=0; i< numExtraBeforeLines ; i++)
  752. extraBeforeLines[i] = "";
  753. File rootFile = new File(filename);
  754. if (rootFile != null && !rootFile.isDirectory())
  755. {
  756. if(rootFile.canRead())
  757. {
  758. currFilename = filename;
  759. try
  760. {
  761. in = new BufferedReader(new FileReader(currFilename));
  762. fileLineNumbers.clear();
  763. currLineNumber = 0;
  764. while ((s = in.readLine()) != null)
  765. {
  766. currLineNumber++;
  767. expression = new RE(searchStr, regExFlags);
  768. if (expression.getMatch(s)!=null)
  769. {
  770. if ( verbose )
  771. {
  772. System.out.println("FILE: "+currFilename);
  773. for (int i=0; i< numExtraBeforeLines ; i++)
  774. System.out.println(" "+currLineNumber+extraBeforeLines[i]);
  775. System.out.println(" "+currLineNumber + " "+s);
  776. System.out.println();
  777. }
  778. fileLineNumbers.add(new Integer(currLineNumber));
  779. }
  780. for (int i=0; i< numExtraBeforeLines-1 ; i++)
  781. extraBeforeLines[i] = extraBeforeLines[i+1];
  782. extraBeforeLines[numExtraBeforeLines-1] = s;
  783. }
  784. in.close();
  785. if (fileLineNumbers.size() > 0)
  786. retVal.put(currFilename, fileLineNumbers.clone());
  787. }
  788. catch (REException reEx)
  789. {
  790. reEx.printStackTrace();
  791. }
  792. catch (FileNotFoundException fEx)
  793. {
  794. fEx.printStackTrace();
  795. }
  796. catch (IOException ioEx)
  797. {
  798. ioEx.printStackTrace();
  799. }
  800. }
  801. }
  802. else
  803. {
  804. // it is a directory so recurse on files if recursing flag is set
  805. if (recurseSubdirs)
  806. {
  807. String[] files = rootFile.list();
  808. File tempFile;
  809. //if ( verbose )
  810. //{
  811. // System.out.println("Recursing into "+filename);
  812. //}
  813. //loop through all the files in the dir
  814. Hashtable recursedHash = null;
  815. for (int i = 0; files != null && i < files.length; i++)
  816. {
  817. recursedHash = null;
  818. recursedHash = searchInFile(searchStr,
  819. filename + File.separator + files[i],
  820. recurseSubdirs, fileRegExp, verbose);
  821. if (recursedHash != null ) retVal.putAll(recursedHash);
  822. }
  823. }
  824. }
  825. return retVal;
  826. }
  827. /**
  828. * Searches the provided directory (and subdirs) for the requested file.
  829. *
  830. * @param fileName The filename/regexp to search for.
  831. * @param directory The filename of the directory to delete.
  832. * @param recurseSubdirs Flags if the sub-dirs are searched.
  833. * @param regExp Flags if 'fileName' should be regarded as a regular
  834. * expression.
  835. * @param verbose true will produce output to System.out just like the
  836. * UNIX find cmd
  837. *
  838. * @return the full cannoical paths to the found files.
  839. */
  840. public static Vector findFile(String fileName, String directory,
  841. boolean recurseSubdirs, boolean regExp, boolean verbose)
  842. {
  843. initUtil();
  844. final String methodName = CLASSNAME + ": findFile(" +
  845. fileName + " " + directory + " " + recurseSubdirs+ " " + regExp+ " " + verbose+ " )";
  846. if (log_ != null) log_.startMethod(methodName);
  847. Vector retVal = new Vector();
  848. File dirToSearch = initDirFile(directory);
  849. if (dirToSearch != null)
  850. {
  851. String[] files = dirToSearch.list();
  852. File tempFile;
  853. if ( files!= null) log_.debug("Searching "+files.length +" files&dirs");
  854. //loop through all the files in the dir
  855. for (int i = 0; files != null && i < files.length; i++)
  856. {
  857. tempFile = new File(directory + File.separator + files[i]);
  858. if (tempFile.isDirectory() && recurseSubdirs)
  859. {
  860. // recurse on the subdirectory
  861. retVal.addAll(findFile(fileName, directory + File.separator + files[i],
  862. recurseSubdirs, regExp, verbose));
  863. }
  864. else if (!tempFile.isDirectory())
  865. {
  866. // does it match
  867. String absPath = tempFile.getAbsolutePath();
  868. log_.debug("Searching "+absPath);
  869. if (regExp)
  870. {
  871. try
  872. {
  873. RE expression = new RE(fileName);
  874. if (expression.isMatch(files[i]))
  875. {
  876. retVal.add(absPath);
  877. if (verbose) System.out.println(absPath);
  878. }
  879. }
  880. catch (REException reExp)
  881. {
  882. reExp.printStackTrace();
  883. break;
  884. }
  885. }
  886. else if (files[i].trim().indexOf(fileName) >= 0)
  887. {
  888. retVal.add(absPath);
  889. if (verbose)System.out.println(absPath);
  890. }
  891. }
  892. }
  893. }
  894. if (log_ != null) log_.endMethod(methodName);
  895. return retVal;
  896. }
  897. /**
  898. * Initisalizes File only if it is directory.It is represented by the passed
  899. * in String.
  900. *
  901. * @param s the directory name to init as a File
  902. * @return An instatiated File object if the passed string is a dir, null
  903. * if not
  904. */
  905. public static File initDirFile(String s)
  906. {
  907. initUtil();
  908. File retVal = null;
  909. File dirFile = new File(s);
  910. if (dirFile.isDirectory() && dirFile.canRead())
  911. {
  912. retVal = dirFile;
  913. }
  914. return retVal;
  915. }
  916. /**
  917. * Renames files to a more URL friendly format.
  918. * <P>It goes through each file in the specified directory and renames them
  919. * using the spacesToCapsInFileName method of renaming.
  920. *
  921. * @see #spacesToCapsInFileName(String)
  922. * @see #dirFile
  923. **/
  924. public static void spacesToCapsInDir(String dirName)
  925. {
  926. spacesToCapsInDir(dirName, true);
  927. }
  928. /**
  929. * Renames files to a more URL friendly format.
  930. * <P>It goes through each file in the specified directory and renames them
  931. * using the spacesToCapsInFileName method of renaming.
  932. *
  933. * @see #spacesToCapsInFileName(String)
  934. * @see #dirFile
  935. **/
  936. public static void spacesToCapsInDir(String dirName, boolean doUnderscores)
  937. {
  938. File dirFile = initDirFile(dirName);
  939. String newDirName = dirName;
  940. boolean succeeded = false;
  941. // check and rename the initial dir
  942. if (dirFile.toString().indexOf(" ") != -1 ||
  943. dirFile.toString().indexOf("_") != -1)
  944. {
  945. newDirName = spacesToCapsInString(dirFile.toString(), doUnderscores);
  946. System.out.println("Renaming "+dirFile.toString()+" -> "+newDirName);
  947. //System.out.println(" "+dirFile.getAbsolutePath()+" "+spacesToCapsInString(dirFile.toString(), true));
  948. succeeded = dirFile.renameTo(new File(newDirName));
  949. }
  950. if (succeeded)
  951. {
  952. succeeded = false;
  953. dirFile = initDirFile(newDirName);
  954. String [] fileName = dirFile.list();
  955. System.out.print("Formatting dir="+dirFile.toString());
  956. System.out.println(" It has "+fileName.length + " files.");
  957. if (dirFile != null &&
  958. dirFile.isDirectory() &&
  959. dirFile.canRead() &&
  960. newDirName != null )
  961. {
  962. File tempFile;
  963. for (int i=0;i< fileName.length;i++)
  964. {
  965. tempFile = new File(newDirName+File.separator+fileName[i]);
  966. // do a depth first file rename of the subdir files
  967. if (tempFile != null && tempFile.isDirectory())
  968. spacesToCapsInDir(tempFile.toString(), doUnderscores);
  969. String newName = spacesToCapsInString(fileName[i], doUnderscores);
  970. //System.out.println(fileName[i] +" .. " +newName);
  971. try
  972. {
  973. if (newName !="" && fileName[i].length() != newName.length())
  974. {
  975. //System.out.println(i+".1) "+tempFile.toString());
  976. //System.out.print(i+".2) "+newDirName+File.separator+newName);
  977. succeeded = tempFile.renameTo(
  978. new File(newDirName+File.separator+newName));
  979. if (succeeded)
  980. System.out.println(" succeeded.");
  981. else
  982. System.out.println("");
  983. File tempFile2 = new File(newDirName+File.separator+fileName[i]);
  984. if (tempFile2.exists() &&
  985. tempFile.exists() &&
  986. !newName.toUpperCase().equals(fileName[i].toUpperCase()))
  987. {
  988. tempFile2.delete();
  989. }
  990. }
  991. }
  992. catch (SecurityException ex)
  993. {
  994. System.err.println("SecurityException " + ex);
  995. }
  996. catch (NullPointerException ex)
  997. {
  998. System.err.println("NullPointerException " + ex);
  999. }
  1000. } //loop
  1001. }
  1002. }
  1003. else
  1004. {
  1005. System.err.println("Could not rename "+dirName +" to "+newDirName);
  1006. }
  1007. }
  1008. /**
  1009. * Removes any space chars ' ' from a filename and Capitalizes the next char.
  1010. * <P><B>NOTE:</B> The file is expected to be in
  1011. * the current working directorydirectory
  1012. *
  1013. * @param fName a string representing the file to perform the action
  1014. * @return the new filename representation
  1015. **/
  1016. public static String spacesToCapsInFileName(String fName)
  1017. {
  1018. String newName = "";
  1019. File tempFile;
  1020. if (fName != null){
  1021. tempFile = new File(USERDIR+File.separator+fName);
  1022. if(!tempFile.isDirectory())
  1023. {
  1024. newName = spacesToCapsInString(fName);
  1025. }
  1026. }
  1027. return newName;
  1028. }
  1029. /**
  1030. * Removes any space chars ' ' from a String and Capitalizes the next char.
  1031. *
  1032. * @param fName a string perform the action
  1033. * @return the new representation
  1034. **/
  1035. public static String spacesToCapsInString(String fName)
  1036. {
  1037. return spacesToCapsInString(fName, false);
  1038. }
  1039. /**
  1040. * Removes any space chars ' ' from a String and Capitalizes the next char.
  1041. *
  1042. * @param fName a string perform the action
  1043. * @param includeUnderscoreflag if '_' are also removed
  1044. * @return the new representation
  1045. **/
  1046. public static String spacesToCapsInString(String fName, boolean includeUnderscore)
  1047. {
  1048. initUtil();
  1049. String newName = "";
  1050. boolean space = false;
  1051. for (int j=0; j< fName.length(); j++)
  1052. {
  1053. char newChar = fName.charAt(j);
  1054. if (newChar == ' ' || (newChar == '_' && includeUnderscore))
  1055. {
  1056. // set the space flag so the next char can be cap'd
  1057. space = true;
  1058. }
  1059. else
  1060. {
  1061. if (space) // was the last char a space???
  1062. {
  1063. newName += String.valueOf(Character.toUpperCase(newChar));
  1064. }
  1065. else
  1066. {
  1067. newName += String.valueOf(newChar);
  1068. }
  1069. space = false;
  1070. }
  1071. }
  1072. return newName;
  1073. }
  1074. /**
  1075. * Takes a string and adds a space in front of any capitalized char.
  1076. * Basically the reverse of the method spacesToCapsInString.
  1077. *
  1078. * @param fName a string perform the action
  1079. * @return the new representation
  1080. **/
  1081. public static String capsToSpacesInString(String fName)
  1082. {
  1083. initUtil();
  1084. StringBuffer newName = new StringBuffer();
  1085. char newChar;
  1086. for (int j=0; j< fName.length(); j++)
  1087. {
  1088. newChar = fName.charAt(j);
  1089. if (Character.isLetter(newChar) && Character.isUpperCase(newChar))
  1090. {
  1091. newName.append(" ");
  1092. }
  1093. newName.append(String.valueOf(newChar));
  1094. }
  1095. return newName.toString();
  1096. }
  1097. /**
  1098. * Takes a string and adds a space in front of any capitalized char.
  1099. * Basically the reverse of the method spacesToCapsInString.
  1100. *
  1101. * @param fName a string perform the action
  1102. * @return the new representation
  1103. **/
  1104. public static String capsToUndersInString(String fName)
  1105. {
  1106. initUtil();
  1107. StringBuffer newName = new StringBuffer();
  1108. char newChar;
  1109. for (int j=0; j< fName.length(); j++)
  1110. {
  1111. newChar = fName.charAt(j);
  1112. if (Character.isLetter(newChar) && Character.isUpperCase(newChar))
  1113. {
  1114. newName.append("_");
  1115. }
  1116. newName.append(String.valueOf(newChar));
  1117. }
  1118. return newName.toString();
  1119. }
  1120. /**
  1121. * Searches the classpath for the specified filename and then returns the
  1122. * full path that is used for it.
  1123. *
  1124. * @param filename to look for in the classpath
  1125. * @param fallBack if the file is not found in classpath
  1126. * @return the path description of the passed filename as found in
  1127. * the classpath.
  1128. */
  1129. public static String getFilePathFromClasspath(String filename, String fallBack)
  1130. {
  1131. initUtil();
  1132. final String methodName = CLASSNAME +
  1133. ": getFilePathFromClasspath(String, String)";
  1134. if (log_ != null)
  1135. {
  1136. log_.startMethod(methodName);
  1137. }
  1138. String retVal = getFilePathFromClasspath(filename);
  1139. //System.out.println("File In Classpath="+retVal);
  1140. if (retVal == null || retVal.equals(""))
  1141. {
  1142. retVal = fallBack;
  1143. }
  1144. if (log_ != null)
  1145. {
  1146. log_.endMethod();
  1147. }
  1148. //System.out.println("File In Classpath="+retVal);
  1149. return retVal;
  1150. }
  1151. /**
  1152. * Searches the classpath for the specified filename and then returns the
  1153. * full path that is used for it.
  1154. *
  1155. * @param filename the filename to look for
  1156. * @return the path description of the passed filename as found in
  1157. * the classpath.
  1158. */
  1159. public static String getFilePathFromClasspath(String filename)
  1160. {
  1161. initUtil();
  1162. final String methodName = CLASSNAME + ": getFilePathFromClasspath";
  1163. if (log_ != null)
  1164. {
  1165. log_.startMethod(methodName);
  1166. }
  1167. String retVal = "";
  1168. String pathSep = System.getProperty("path.separator");
  1169. if (CLASSPATH == null)
  1170. {
  1171. return "";
  1172. }
  1173. int fileIndex = CLASSPATH.indexOf(filename);
  1174. if (log_ != null)
  1175. {
  1176. log_.debug("Searching the Classpath for " + filename +
  1177. " " + fileIndex);
  1178. }
  1179. if (fileIndex >= 0)
  1180. {
  1181. int startSpot = 0;
  1182. int nextSpot = CLASSPATH.indexOf(pathSep);
  1183. // the fileName is in the classpath
  1184. if (log_ != null)
  1185. {
  1186. log_.debug("Start Looking at (" + startSpot + "," + nextSpot + ")");
  1187. }
  1188. while ((nextSpot < fileIndex) && nextSpot != -1)
  1189. {
  1190. startSpot = nextSpot;
  1191. nextSpot = CLASSPATH.indexOf(pathSep, startSpot + 1);
  1192. if (log_ != null)
  1193. {
  1194. log_.debug(", (" + startSpot + "," + nextSpot + ")");
  1195. }
  1196. }
  1197. if (startSpot <= 0)
  1198. {
  1199. startSpot = -1;
  1200. }
  1201. if (nextSpot <= 0)
  1202. {
  1203. nextSpot = CLASSPATH.length();
  1204. }
  1205. retVal = CLASSPATH.substring(startSpot + 1, nextSpot);
  1206. }
  1207. else
  1208. if (log_ != null)
  1209. {
  1210. log_.minor(filename + " cannot be found in classpath.");
  1211. }
  1212. if (log_ != null)
  1213. {
  1214. log_.endMethod();
  1215. }
  1216. return retVal;
  1217. }
  1218. /**
  1219. * This method seeks out and returns the Parent Frame for a given component.
  1220. *
  1221. * @param c The Component to be used as the basis of the frame search
  1222. * @return Frame The Frame that eventually holds the giuven Component.
  1223. */
  1224. public static Frame getAncestorFrame(Component c) {
  1225. Frame retVal = null;
  1226. while ((c = c.getParent()) != null)
  1227. if (c instanceof Frame) {
  1228. retVal = (Frame) c;
  1229. }
  1230. return retVal;
  1231. }
  1232. /**
  1233. * Calls the User Interface Manager and sets the look and feel setting based
  1234. * on the parameter it is passed.
  1235. *
  1236. * @param i The new TheLookAndFeel value
  1237. */
  1238. public static void setTheLookAndFeel(short i, Component comp) {
  1239. /* Force SwingSet to come up in the Cross Platform L&F */
  1240. try {
  1241. switch ((int)i){
  1242. case METAL_LOOKANDFEEL:
  1243. // If you want the Java L&F
  1244. UIManager.setLookAndFeel(metalClassName);
  1245. log_.debug("Setting the Java L&F");
  1246. break;
  1247. case WINDOZE_LOOKANDFEEL:
  1248. // If you want the System L&F
  1249. UIManager.setLookAndFeel(windowsClassName);//UIManager.getSystemLookAndFeelClassName());
  1250. log_.debug("Setting the System L&F");
  1251. break;
  1252. case MOTIF_LOOKANDFEEL:
  1253. // If you want the Motif L&F
  1254. UIManager.setLookAndFeel(motifClassName);
  1255. log_.debug("Setting the Motif L&F");
  1256. break;
  1257. case MAC_LOOKANDFEEL:
  1258. // If you want the Mac L&F
  1259. UIManager.setLookAndFeel(macClassName);
  1260. log_.debug("Setting the Mac L&F");
  1261. break;
  1262. default:
  1263. // defaults to Java L&F
  1264. UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
  1265. log_.debug("Setting the Java L&F");
  1266. }
  1267. SwingUtilities.updateComponentTreeUI(Util.getAncestorFrame(comp));
  1268. }
  1269. catch (Exception exc)
  1270. {
  1271. System.err.println("Error loading L&F: " + exc);
  1272. }
  1273. }
  1274. /**
  1275. * Loads the requested Image filename from the specified jarfile.
  1276. *
  1277. * @param imageFilename the filename in the jarfile to use as the basis for
  1278. * the Image to retrieve.
  1279. * @param jarFilename the jar file to look through for the image.
  1280. * @return Image the Image loaded from the filename spec'd as
  1281. * an imput param, It returns null if it cannot retrieve the Image.
  1282. */
  1283. public static Image loadImage(String imageFilename, String jarFilename)
  1284. {
  1285. initUtil();
  1286. final String methodName = CLASSNAME + ": loadImage(String, String)";
  1287. if (log_ != null)
  1288. {
  1289. log_.startMethod(methodName);
  1290. }
  1291. if (log_ != null)
  1292. {
  1293. log_.debug("Loading Imagename " + imageFilename);
  1294. }
  1295. Image retVal = (new ImageIcon(Util.class.getResource("/" + imageFilename))).
  1296. getImage();
  1297. /*
  1298. * String iconJarFileName = jarFilename; //getFilePathFromClasspath(jarFilename);
  1299. * if(log_!=null) log_.debug("Loading Imagename "+imageFilename+" from Jarfile "+jarFilename);
  1300. * InputStream in = null;
  1301. * JarEntry tempJarEntry = null;
  1302. * byte [] imageBytes;
  1303. * long imageFileSize = 0l;
  1304. * int bytesRead = 0;
  1305. * try
  1306. * {
  1307. * JarFile jar = new JarFile(iconJarFileName, false);
  1308. * tempJarEntry = jar.getJarEntry(imageFilename);
  1309. * in = jar.getInputStream(tempJarEntry);
  1310. * imageFileSize = tempJarEntry.getSize();
  1311. * imageBytes = new byte[(int)imageFileSize];
  1312. * for (int j=0;j<imageFileSize;j++)
  1313. * imageBytes[j] = new Integer(in.read()).byteValue();
  1314. * if(log_!=null) log_.debug("Loaded "+imageFileSize+" Bytes.");
  1315. * retVal = (Toolkit.getDefaultToolkit()).createImage(imageBytes);
  1316. * }
  1317. * catch (NullPointerException fEx)
  1318. * {
  1319. * System.out.println("No graphicJarEntry NullPointerException " +
  1320. * imageFilename);
  1321. * }
  1322. * catch (FileNotFoundException fEx)
  1323. * {
  1324. * System.out.println("graphic FileNotFoundException " +imageFilename);
  1325. * }
  1326. * catch (IOException ioEx)
  1327. * {
  1328. * System.out.println("graphic FileNotFoundException " +imageFilename);
  1329. * }
  1330. * catch (SecurityException secEx)
  1331. * {
  1332. * System.out.println("graphic SecurityException " +imageFilename);
  1333. * }
  1334. */
  1335. if (log_ != null)
  1336. {
  1337. log_.endMethod();
  1338. }
  1339. return retVal;
  1340. }
  1341. /**
  1342. * Loads the requested Image filename from the classpath.
  1343. *
  1344. * @param imageFilename the filename in the jarfile to use as the basis for
  1345. * the Image to retrieve.
  1346. * @return Image the Image loaded from the filename spec'd as
  1347. * an imput param, It returns null if it cannot retrieve the Image.
  1348. */
  1349. public static Image loadImage(String imageFilename)
  1350. {
  1351. initUtil();
  1352. final String methodName = CLASSNAME + ": loadImage()";
  1353. if (log_ != null)
  1354. {
  1355. log_.startMethod(methodName);
  1356. }
  1357. if (log_ != null)
  1358. {
  1359. log_.debug("Loading Imagename " + imageFilename);
  1360. }
  1361. //System.out.println("Loading Imagename "+imageFilename);
  1362. URL resourceUrl = Util.class.getResource(imageFilename);
  1363. Image retVal = null;
  1364. if (resourceUrl != null)
  1365. {
  1366. retVal = (new ImageIcon(resourceUrl)).getImage();
  1367. }
  1368. else
  1369. if (log_ != null)
  1370. {
  1371. log_.minor("DID NOT Got the Resource URL for :" + imageFilename);
  1372. }
  1373. if (retVal == null)
  1374. {
  1375. if (log_ != null)
  1376. {
  1377. log_.minor("Could NOT create Image for " + imageFilename);
  1378. }
  1379. }
  1380. if (log_ != null)
  1381. {
  1382. log_.endMethod();
  1383. }
  1384. return retVal;
  1385. }
  1386. /**
  1387. * A method to simply abstract the Try/Catch required to put the current
  1388. * thread to sleep for the specified time in ms.
  1389. *
  1390. * @param waitTime the sleep time in milli seconds (ms).
  1391. * @return boolean value specifying if the sleep completed (true) or
  1392. * was interupted (false).
  1393. */
  1394. public static boolean sleep(long waitTime)
  1395. {
  1396. final String methodName = CLASSNAME + ": sleep(Long)";
  1397. if (log_ != null)
  1398. {
  1399. log_.startMethod(methodName);
  1400. }
  1401. boolean retVal = true;
  1402. /*
  1403. * BLOCK for the spec'd time
  1404. */
  1405. try
  1406. {
  1407. Thread.sleep(waitTime);
  1408. }
  1409. catch (InterruptedException iex)
  1410. {
  1411. retVal = false;
  1412. }
  1413. if (log_ != null)
  1414. {
  1415. log_.endMethod();
  1416. }
  1417. return retVal;
  1418. }
  1419. /**
  1420. * Encapsulates the showing of the FileChooser dialog and returns a String
  1421. * representing the absolute path. <P>
  1422. *
  1423. * NO file filters will be used and NO directory selection is allowed.
  1424. *
  1425. * @param parent the owner of this dialog (generally just send this)
  1426. * @param startPath the dir to start the file chooser dialog from
  1427. * @return the absolute path of the chosen file.
  1428. */
  1429. public static String chooseAFilename(Component parent, String startPath)
  1430. {
  1431. initUtil();
  1432. final String methodName = CLASSNAME + ": chooseAFilename(String)";
  1433. if (log_ != null)
  1434. {
  1435. log_.startMethod(methodName);
  1436. }
  1437. if (log_ != null)
  1438. {
  1439. log_.endMethod();
  1440. }
  1441. return chooseAFilename(parent, startPath, null, false);
  1442. }
  1443. /**
  1444. * Encapsulates the showing of the FileChooser dialog and returns a String
  1445. * representing the absolute path.<P>
  1446. *
  1447. * This method requires all the config parms specified by the
  1448. * ExampleFileFilter.
  1449. *
  1450. * @param parent the owner of this dialog (generally just send this)
  1451. * @param startPath the dir to start the file chooser dialog from
  1452. * @param filters an array holding the Filters to use in the dialog
  1453. * @param filesAndDirs specs if the user will be allowed to choose both
  1454. * files or dirs.
  1455. * @return the absolute path of the chosen file.
  1456. */
  1457. public static String chooseAFilename(Component parent,
  1458. String startPath,
  1459. ExampleFileFilter[] filters,
  1460. boolean filesAndDirs
  1461. )
  1462. {
  1463. return chooseAFilename(parent, startPath, filters,
  1464. filesAndDirs, Util.OPEN_DIALOG);
  1465. }
  1466. /**
  1467. * Encapsulates the showing of the FileChooser dialog and returns a String
  1468. * representing the absolute path.<P>
  1469. *
  1470. * This method requires all the config parms specified by the
  1471. * ExampleFileFilter.
  1472. *
  1473. * @param parent the owner of this dialog (generally just send this)
  1474. * @param startPath the dir to start the file chooser dialog from
  1475. * @param filters an array holding the Filters to use in the dialog
  1476. * @param filesAndDirs specs if the user will be allowed to choose both
  1477. * files or dirs.
  1478. * @param openOrClose Description of the Parameter
  1479. * @return the absolute path of the chosen file.
  1480. */
  1481. public static String chooseAFilename(Component parent,
  1482. String startPath,
  1483. ExampleFileFilter[] filters,
  1484. boolean filesAndDirs,
  1485. short openOrClose)
  1486. {
  1487. initUtil();
  1488. final String methodName = CLASSNAME +
  1489. ": chooseAFilename(String,ExampleFileFilter[],boolean)";
  1490. if (log_ != null)
  1491. {
  1492. log_.startMethod(methodName);
  1493. }
  1494. String retVal = "";
  1495. JFileChooser chooser = new JFileChooser();
  1496. if (filters != null && filters.length > 0)
  1497. {
  1498. for (int i = 0; i < filters.length; i++)
  1499. {
  1500. chooser.addChoosableFileFilter(filters[i]);
  1501. }
  1502. chooser.setFileFilter(filters[0]);
  1503. }
  1504. if (filesAndDirs)
  1505. {
  1506. chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
  1507. }
  1508. if (openOrClose == SAVE_DIALOG)
  1509. {
  1510. if (chooser.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION)
  1511. {
  1512. retVal = chooser.getSelectedFile().getAbsolutePath();
  1513. System.out.println("You chose this file: " + retVal);
  1514. }
  1515. }
  1516. else
  1517. {
  1518. if (chooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION)
  1519. {
  1520. retVal = chooser.getSelectedFile().getAbsolutePath();
  1521. System.out.println("You chose this file: " + retVal);
  1522. }
  1523. }
  1524. if (log_ != null)
  1525. {
  1526. log_.endMethod();
  1527. }
  1528. return retVal;
  1529. }
  1530. /**
  1531. * Converts an Absolute path to a relative path from the VM Working Dir.
  1532. *
  1533. * @param absPath is the File to use to to convert
  1534. * @return null if can't be done, otherwise it returns the relative path.
  1535. */
  1536. public static String absoluteToPwdRelativePath(File absPath)
  1537. {
  1538. String retVal = null;
  1539. if (absPath !=null)
  1540. retVal = absoluteToPwdRelativePath(absPath.getAbsolutePath());
  1541. return retVal;
  1542. }
  1543. /**
  1544. * Converts an Absolute path to a relative path from the VM Working Dir.
  1545. *
  1546. * @param absPath is the absolute path to convert
  1547. * @return null if can't be done, otherwise it returns the relative path.
  1548. */
  1549. public static String absoluteToPwdRelativePath(String absPath)
  1550. {
  1551. initUtil();
  1552. final String methodName = CLASSNAME + ": getFileDir(String)";
  1553. if (log_ != null)
  1554. {
  1555. log_.startMethod(methodName);
  1556. }
  1557. String retVal = null;
  1558. String pwd = System.getProperty("user.dir");
  1559. if (absPath != null && absPath.indexOf(pwd) != -1)
  1560. {
  1561. // Found It
  1562. retVal = absPath.substring(pwd.length()+1);
  1563. }
  1564. if (log_ != null)
  1565. {
  1566. log_.endMethod();
  1567. }
  1568. return retVal;
  1569. }
  1570. /**
  1571. * Removes a '/..' from the filename string and returns the corrected dir
  1572. * name reference. For Example : pass it "/a/b/c/../d" it returns "/a/b/d".
  1573. *
  1574. * @param path is the absolute path to convert
  1575. * @return null if can't be done, otherwise it returns the corrected path.
  1576. */
  1577. public static String removeParentRelativeReference(String path)
  1578. {
  1579. initUtil();
  1580. final String methodName = CLASSNAME + ": removeParentRelativeReference(String)";
  1581. if (log_ != null)
  1582. {
  1583. log_.startMethod(methodName);
  1584. }
  1585. String retVal = path;
  1586. String parentRefString = SYSTEM_FILE_SEPERATOR+"..";
  1587. int spot = -1;
  1588. int removeSpot = -1;
  1589. //System.out.println("Path = "+path);
  1590. //System.out.println("parentRef = "+parentRefString);
  1591. if