KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > test > Handle


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.test;
5
6 import com.tc.util.runtime.Os;
7
8 import java.io.BufferedReader JavaDoc;
9 import java.io.File JavaDoc;
10 import java.io.IOException JavaDoc;
11 import java.io.InputStreamReader JavaDoc;
12
13 /*
14  * To be used for Windows only.
15  *
16  * Get java processes that are holding locks on a given file.
17  *
18  * This class depends on 2 free programs
19  * - Handle from http://www.sysinternals.com and
20  * - PrcView from http://www.prcview.com
21  *
22  * Author: Hung Huynh
23  */

24 public class Handle {
25
26   private static String JavaDoc runProcess(String JavaDoc[] args) throws IOException JavaDoc {
27     Process JavaDoc p = Runtime.getRuntime().exec(args);
28     BufferedReader JavaDoc reader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(p.getInputStream()));
29     String JavaDoc line;
30     StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
31     while ((line = reader.readLine()) != null) {
32       buffer.append(line + "\n");
33     }
34     reader.close();
35     return buffer.toString();
36   }
37
38   private static String JavaDoc getPathFor(String JavaDoc path, String JavaDoc cmd) {
39     String JavaDoc[] dirs = path.split(File.pathSeparator);
40     String JavaDoc thePath = "";
41     for (int i = 0; i < dirs.length; i++) {
42       File JavaDoc test = new File JavaDoc(dirs[i] + File.separator + cmd);
43       if (test.exists()) {
44         thePath = dirs[i];
45         break;
46       }
47     }
48     return thePath;
49   }
50
51   /**
52    * @param file observed file
53    * @param path global path that contains path to handle.exe and pv.exe
54    * @return java processes that holding lock on the given file.
55    * @throws IOException
56    */

57   public static String JavaDoc getJavaProcessFileHandles(File JavaDoc file) throws IOException JavaDoc {
58     if (!Os.isWindows())
59       return "Not a Windows box";
60
61     String JavaDoc searchPath = TestConfigObject.getInstance().executableSearchPath();
62     String JavaDoc thePath = getPathFor(searchPath, "handle.exe") + File.separator;
63
64     String JavaDoc[] args = new String JavaDoc[] { thePath + "handle.exe", "-p", "java", file.getAbsolutePath() };
65     String JavaDoc handleResult = runProcess(args);
66
67     String JavaDoc processResult = "";
68     // if "No matching handles found" from handle.exe, no need to display java processes
69
if (handleResult.indexOf("No matching handles found") < 0)
70     {
71       args = new String JavaDoc[] { thePath + "pv.exe", "-l", "java.exe" };
72       processResult = runProcess(args);
73     }
74
75     return handleResult + "\n" + processResult;
76   }
77
78 }
79
Popular Tags