KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > core > misc > OSProcess


1 /* ====================================================================
2  * The Jcorporate Apache Style Software License, Version 1.2 05-07-2002
3  *
4  * Copyright (c) 1995-2002 Jcorporate Ltd. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by Jcorporate Ltd.
21  * (http://www.jcorporate.com/)."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. "Jcorporate" and product names such as "Expresso" must
26  * not be used to endorse or promote products derived from this
27  * software without prior written permission. For written permission,
28  * please contact info@jcorporate.com.
29  *
30  * 5. Products derived from this software may not be called "Expresso",
31  * or other Jcorporate product names; nor may "Expresso" or other
32  * Jcorporate product names appear in their name, without prior
33  * written permission of Jcorporate Ltd.
34  *
35  * 6. No product derived from this software may compete in the same
36  * market space, i.e. framework, without prior written permission
37  * of Jcorporate Ltd. For written permission, please contact
38  * partners@jcorporate.com.
39  *
40  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
41  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
42  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
43  * DISCLAIMED. IN NO EVENT SHALL JCORPORATE LTD OR ITS CONTRIBUTORS
44  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
45  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
46  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
47  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
48  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
49  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
50  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This software consists of voluntary contributions made by many
55  * individuals on behalf of the Jcorporate Ltd. Contributions back
56  * to the project(s) are encouraged when you make modifications.
57  * Please send them to support@jcorporate.com. For more information
58  * on Jcorporate Ltd. and its products, please see
59  * <http://www.jcorporate.com/>.
60  *
61  * Portions of this software are based upon other open source
62  * products and are subject to their respective licenses.
63  */

64 package com.jcorporate.expresso.core.misc;
65
66 import com.jcorporate.expresso.core.db.DBException;
67 import org.apache.log4j.Logger;
68
69 import java.io.BufferedReader JavaDoc;
70 import java.io.IOException JavaDoc;
71 import java.io.InputStreamReader JavaDoc;
72 import java.util.Enumeration JavaDoc;
73 import java.util.Vector JavaDoc;
74
75
76 /**
77  * This is a class that wraps another process in the machine. It is not like
78  * the ANT wrappers that can launch another java program with full environment
79  * of the parent, but you can launch other java programs through command line
80  * usage.
81  * <p/>
82  * Typical usage:
83  * <blockquote><pre>
84  * OSProcess process = new OSProcess(&quot;/usr/bin/perl /home/mydir/scripts/updatecounts.pl&quot;);
85  * process.runProcess();
86  * <p/>
87  * //Now print out the results to std out.
88  * Vector result = process.getStdout();
89  * for (Iterator i = result.iterator(); i.hasNext(); ) {
90  * System.out.println((String)i.next());
91  * }
92  * </pre></blockquote>
93  * <p/>
94  *
95  * @author Michael Nash
96  */

97 public class OSProcess
98         extends Thread JavaDoc {
99     private static final String JavaDoc thisClass = OSProcess.class.getName() + ".";
100     private String JavaDoc myCommandLine = null;
101     private long sleepInterval;
102     private int maxSleeps;
103     private int exitValue;
104     private Vector JavaDoc stderr = new Vector JavaDoc();
105     private Vector JavaDoc stdout = new Vector JavaDoc();
106     private DBException nested = null;
107     private static Logger log = Logger.getLogger(OSProcess.class);
108
109     /**
110      * Constructor
111      *
112      * @param commandLine The command line to execute on the server
113      */

114     public OSProcess(String JavaDoc commandLine) {
115         myCommandLine = commandLine;
116     } /* OSProcess(String) */
117
118     /**
119      * ??
120      *
121      * @return
122      */

123     public DBException getException() {
124         return nested;
125     } /* getException() */
126
127     /**
128      * Retrieve the operating system exit value.
129      *
130      * @return
131      */

132     public int getExitValue()
133             throws DBException {
134         return exitValue;
135     } /* getExitValue() */
136
137
138     /**
139      * Retrieve a vector of all lines printed to std error
140      *
141      * @return java.util.Vector of Strings
142      */

143     public Vector JavaDoc getStderr() {
144         synchronized (stderr) {
145             return (Vector JavaDoc) stderr.clone();
146         }
147     } /* getStderr() */
148
149
150     /**
151      * Retrieve a vector of all lines printed to std out
152      *
153      * @return java.util.Vector
154      */

155     public Vector JavaDoc getStdout() {
156         synchronized (stdout) {
157             return (Vector JavaDoc) stdout.clone();
158         }
159     } /* getStdout() */
160
161
162     /**
163      * Test-harness method to allow OSProcess to be run & tested
164      * from the command line
165      *
166      * @param args
167      */

168     public static void main(String JavaDoc[] args) {
169         System.out.println("OSProcess Test");
170
171         BufferedReader JavaDoc ds = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(System.in));
172
173         try {
174             System.out.print("Command Line:");
175
176             String JavaDoc commandLine = ds.readLine();
177             System.out.print("Timeout interval (milliseconds) (default 5000):");
178
179             String JavaDoc timeOut = ds.readLine();
180
181             if (timeOut.equals("")) {
182                 timeOut = ("5000");
183             }
184
185             System.out.print("Retry count (default 1):");
186
187             String JavaDoc retries = ds.readLine();
188
189             if (retries.equals("")) {
190                 retries = ("1");
191             }
192
193             OSProcess tp = new OSProcess(commandLine);
194             long sleep = new Long JavaDoc(timeOut).longValue();
195             int sleepCount = new Integer JavaDoc(retries).intValue();
196             tp.setTimeOut(sleep, sleepCount);
197             tp.runProcess();
198             System.out.println("Command '" + commandLine + "' completed.");
199             System.out.println("Exit value:" + tp.getExitValue());
200             System.out.println("Standard Output:");
201
202             for (Enumeration JavaDoc e = tp.getStdout().elements();
203                  e.hasMoreElements();) {
204                 System.out.println((String JavaDoc) e.nextElement());
205             }
206
207             System.out.println("Standard Error:");
208
209             for (Enumeration JavaDoc e2 = tp.getStderr().elements();
210                  e2.hasMoreElements();) {
211                 System.out.println((String JavaDoc) e2.nextElement());
212             }
213         } catch (Exception JavaDoc e) {
214             e.printStackTrace();
215         }
216     } /* main(String[]) */
217
218     /**
219      * Run the process - do not call this method directly! Call runProcess
220      * above and it will handle the timeouts correctly
221      */

222     public void run() {
223         String JavaDoc myName = (thisClass + "run()");
224
225         /* Run command line as a seperate thread */
226         Runtime JavaDoc rt = Runtime.getRuntime();
227
228         try {
229             Process JavaDoc myProcess = rt.exec(myCommandLine);
230
231             /* Wait until process exits */
232             myProcess.waitFor();
233
234             BufferedReader JavaDoc i = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(myProcess.getInputStream()));
235             BufferedReader JavaDoc ie = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(myProcess.getErrorStream()));
236             String JavaDoc inLine = i.readLine();
237
238             while (inLine != null) {
239                 synchronized (stdout) {
240                     stdout.addElement(inLine);
241                 }
242                 inLine = i.readLine();
243             }
244
245             inLine = ie.readLine();
246
247             while (inLine != null) {
248                 synchronized (stderr) {
249                     stderr.addElement(inLine);
250                 }
251                 inLine = ie.readLine();
252             }
253
254             exitValue = myProcess.exitValue();
255         } catch (InterruptedException JavaDoc ie) {
256             nested = new DBException(myName,
257                     "Process '" + myCommandLine +
258                     "' was interrupted before it completed successfully:" +
259                     ie.getMessage());
260         } catch (IOException JavaDoc ie) {
261             nested = new DBException(myName,
262                     "Unable to launch '" + myCommandLine +
263                     "' on server:" + ie.getMessage());
264         }
265     } /* run() */
266
267     /**
268      * Run the process on the server, timing out when required
269      *
270      * @throws DBException If the process times out
271      */

272     public void runProcess()
273             throws DBException {
274         String JavaDoc myName = (thisClass + "runProcess()");
275         OSProcess myProcess = new OSProcess(myCommandLine);
276         int currentSleep = 1;
277
278         try {
279             myProcess.start();
280
281             while (currentSleep < maxSleeps) {
282                 sleep(sleepInterval);
283
284                 if (myProcess.isAlive()) {
285                     if (log.isInfoEnabled()) {
286                         log.info("Note: Process '" + myCommandLine +
287                                 "' has taken " +
288                                 (sleepInterval * currentSleep) / 1000 +
289                                 " seconds and is still running");
290                     }
291                 } else {
292                     break;
293                 }
294
295                 currentSleep++;
296             }
297         } catch (InterruptedException JavaDoc ie) {
298             throw new DBException(myName + ":Process '" + myCommandLine +
299                     "' interrupted", ie);
300         }
301         if (myProcess.isAlive()) {
302             throw new DBException(myName + ":Process '" + myCommandLine +
303                     "' did not complete within specified timeout interval");
304         }
305
306         stderr = myProcess.getStderr();
307         stdout = myProcess.getStdout();
308         exitValue = myProcess.getExitValue();
309
310         if (myProcess.getException() != null) {
311             throw myProcess.getException();
312         }
313     } /* runProcess() */
314
315
316     /**
317      * Set a timeout for the command
318      *
319      * @param newSleepInterval Number of seconds to sleep between checks
320      * @param newMaxSleeps Number of times to check before timing out
321      */

322     public void setTimeOut(long newSleepInterval, int newMaxSleeps) {
323         sleepInterval = newSleepInterval;
324         maxSleeps = newMaxSleeps;
325     } /* setTimeOut(long, int) */
326
327 } /* OSProcess */
328
Popular Tags