01: /*
02: * Copyright 2004-2006 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: package org.compass.core.util;
18:
19: import java.io.BufferedReader;
20: import java.io.File;
21: import java.io.InputStreamReader;
22:
23: /**
24: * @author kimchy
25: */
26: public class FileHandlerMonitor {
27:
28: private File file;
29:
30: public FileHandlerMonitor(String filePath) {
31: file = new File(filePath);
32: }
33:
34: public FileHandlerMonitor(File file) {
35: this .file = file;
36: }
37:
38: public FileHandlers handlers() throws Exception {
39: String osName = System.getProperty("os.name");
40: if (osName.toLowerCase().startsWith("windows")) {
41: throw new UnsupportedOperationException(
42: "File handlers not supported on windows");
43: }
44: String command = "lsof | grep " + file.getAbsolutePath();
45: Process process = Runtime.getRuntime().exec(command);
46: BufferedReader reader = new BufferedReader(
47: new InputStreamReader(process.getInputStream()));
48: StringBuilder sb = new StringBuilder();
49: try {
50: int val = reader.read();
51: while (val != -1) {
52: sb.append((char) val);
53: val = reader.read();
54: try {
55: process.exitValue();
56: // process died, bail
57: break;
58: } catch (IllegalThreadStateException e) {
59: // all is well, process still alive
60: }
61: }
62: } finally {
63: try {
64: process.getInputStream().close();
65: } catch (Exception e1) {
66: // do nothing
67: }
68: try {
69: process.getOutputStream().close();
70: } catch (Exception e1) {
71: // do nothing
72: }
73: try {
74: process.getErrorStream().close();
75: } catch (Exception e1) {
76: // do nothing
77: }
78: process.destroy();
79: }
80: return new FileHandlers(sb.toString());
81: }
82:
83: public static class FileHandlers {
84:
85: private String output;
86:
87: public FileHandlers(String output) {
88: this .output = output;
89: }
90:
91: public boolean hasHandlers() {
92: return StringUtils.hasLength(output);
93: }
94:
95: public String getRawOutput() {
96: return output;
97: }
98: }
99: }
|