KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opensubsystems > core > util > ProcessExec


1 /*
2  * Copyright (c) 2003 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
3  *
4  * Project: OpenSubsystems
5  *
6  * $Id: ProcessExec.java,v 1.5 2007/01/07 06:14:00 bastafidli Exp $
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; version 2 of the License.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  */

21
22 package org.opensubsystems.core.util;
23
24 import java.io.File JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.util.logging.Level JavaDoc;
27 import java.util.logging.Logger JavaDoc;
28
29 import org.opensubsystems.core.error.OSSException;
30
31 /**
32  * Utility class for correct executing external processes. This class was insipred
33  * by article http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
34  *
35  * @version $Id: ProcessExec.java,v 1.5 2007/01/07 06:14:00 bastafidli Exp $
36  * @author Miro Halas
37  * @code.reviewer Miro Halas
38  * @code.reviewed Initial revision
39  */

40 public final class ProcessExec
41 {
42    // Constants ////////////////////////////////////////////////////////////////
43

44    /**
45     * Return value used when waiting for process to finish was interrupted.
46     */

47    public static final int INTERRUPTED_PROCESS_RETURN_VALUE = -1;
48    
49    /**
50     * Return value used when waiting for process to finish was interrupted.
51     */

52    public static final Integer JavaDoc INTERRUPTED_PROCESS_RETURN_VALUE_OBJ
53                                   = new Integer JavaDoc(INTERRUPTED_PROCESS_RETURN_VALUE);
54
55    // Cached values ////////////////////////////////////////////////////////////
56

57    /**
58     * Logger for this class
59     */

60    private static Logger JavaDoc s_logger = Log.getInstance(ProcessExec.class);
61
62    // Constructors /////////////////////////////////////////////////////////////
63

64    /**
65     * Private constructor since this class cannot be instantiated
66     */

67    private ProcessExec(
68    )
69    {
70       // Do nothing
71
}
72
73    // Public methods ///////////////////////////////////////////////////////////
74

75    /**
76     * Execute specified command or process and returns immidiately even before
77     * the command finished.
78     *
79     * @param commandline - array containing the command to call and its arguments,
80     * see Runtime.exec for more description
81     * @param bCapture - if true then the output and error will be captured
82     * (carefull about memory) and can be read
83     * @return Object[] - index 0 - Integer value of the exit code
84     * - index 1 - StreamGobbler for the output stream
85     * - index 2 - StreamGobbler for the error stream
86     * @throws IOException - error in function
87     * @throws OSSException - error in function
88     */

89    public static Object JavaDoc[] executeAndWait(
90       String JavaDoc commandline,
91       boolean bCapture
92    ) throws IOException JavaDoc,
93             OSSException
94    {
95       Object JavaDoc[] returnValue;
96       
97       s_logger.log(Level.FINEST, "Executing command " + commandline);
98       returnValue = execute(commandline, bCapture);
99       // any error???
100
int exitVal;
101       
102       try
103       {
104          exitVal = ((Process JavaDoc)returnValue[0]).waitFor();
105          returnValue[0] = new Integer JavaDoc(exitVal);
106       }
107       catch (InterruptedException JavaDoc ieExc)
108       {
109          // We don't know what has happened so return default value
110
returnValue[0] = INTERRUPTED_PROCESS_RETURN_VALUE_OBJ;
111       }
112       
113       return returnValue;
114    }
115    
116    /**
117     * Execute specified command or process and returns immidiately even before
118     * the command finished.
119     *
120     * @param commandline - array containing the command to call and its arguments,
121     * see Runtime.exec for more description
122     * @param environment - array containing the environment for the process
123     * or just null to inherit environment,
124     * see Runtime.exec for more description
125     * @param workingDir - current working directory for the process or just null
126     * to inherit from parent
127     * see Runtime.exec for more description
128     * @param bCapture - if true then the output and error will be captured
129     * (carefull about memory) and can be read
130     * @param lMaxCaptureSize - maximal size of EACH output to be held in memory.
131     * @return Object[] - index 0 - Integer value of the exit code
132     * - index 1 - StreamGobbler for the output stream
133     * - index 2 - StreamGobbler for the error stream
134     * @throws IOException - error in function
135     */

136    public static Object JavaDoc[] executeAndWait(
137       String JavaDoc[] commandline,
138       String JavaDoc[] environment,
139       File JavaDoc workingDir,
140       boolean bCapture,
141       long lMaxCaptureSize
142    ) throws IOException JavaDoc
143    {
144       Object JavaDoc[] returnValue;
145       
146       returnValue = execute(commandline, environment, workingDir, bCapture,
147                             lMaxCaptureSize);
148    
149       // any error???
150
int exitVal;
151       
152       try
153       {
154          exitVal = ((Process JavaDoc)returnValue[0]).waitFor();
155          returnValue[0] = new Integer JavaDoc(exitVal);
156       }
157       catch (InterruptedException JavaDoc ieExc)
158       {
159          // We don't know what has happened so return default value
160
returnValue[0] = INTERRUPTED_PROCESS_RETURN_VALUE_OBJ;
161       }
162       
163       return returnValue;
164    }
165
166    /**
167     * Execute specified command or process and returns immidiately even before
168     * the command finished.
169     *
170     * @param commandline - String containing the command to call and its arguments
171     * it will be parsed to follow requirements of Runtime.exec
172     * @param bCapture - if true then the output and error will be captured
173     * (carefull about memory) and can be read
174     * @return Object[] - index 0 - Process object for the executed process
175     * - index 1 - StreamGobbler for the output stream
176     * - index 2 - StreamGobbler for the error stream
177     * @throws IOException - error in function
178     * @throws OSSException - error in function
179     */

180    public static Object JavaDoc[] execute(
181       String JavaDoc commandline,
182       boolean bCapture
183    ) throws IOException JavaDoc,
184             OSSException
185    {
186       Object JavaDoc[] returnValue;
187       
188       s_logger.log(Level.FINEST, "Executing command " + commandline);
189       returnValue = execute(StringUtils.parseQuotedStringToStringArray(
190                                commandline, " ", true, true),
191                             null, null, bCapture, Long.MAX_VALUE);
192       
193       return returnValue;
194    }
195    
196    
197    /**
198     * Execute specified command or process and returns immidiately even before
199     * the command finished.
200     *
201     * @param commandline - array containing the command to call and its arguments,
202     * see Runtime.exec for more description
203     * @param environment - array containing the environment for the process
204     * or just null to inherit environment,
205     * see Runtime.exec for more description
206     * @param workingDir - current working directory for the process or just null
207     * to inherit from parent
208     * see Runtime.exec for more description
209     * @param bCapture - if true then the output and error will be captured
210     * (carefull about memory) and can be read
211     * @param lMaxCaptureSize - maximal size of EACH output to be held in memory.
212     * @return Object[] - index 0 - Process object for the executed process
213     * - index 1 - StreamGobbler for the output stream
214     * - index 2 - StreamGobbler for the error stream
215     * @throws IOException - error in function
216     */

217    public static Object JavaDoc[] execute(
218       String JavaDoc[] commandline,
219       String JavaDoc[] environment,
220       File JavaDoc workingDir,
221       boolean bCapture,
222       long lMaxCaptureSize
223    ) throws IOException JavaDoc
224    {
225       String JavaDoc[] cmd = new String JavaDoc[3];
226       Object JavaDoc[] returnValue = new Object JavaDoc[3];
227
228       if (GlobalConstants.isWindows9x())
229       {
230          cmd = new String JavaDoc[3];
231          cmd[0] = "command.com";
232          cmd[1] = "/C";
233          cmd[2] = StringUtils.concat(commandline, " ", null);
234       }
235       else if (GlobalConstants.isWindows())
236       {
237          cmd = new String JavaDoc[3];
238          cmd[0] = "cmd.exe";
239          cmd[1] = "/C";
240          cmd[2] = StringUtils.concat(commandline, " ", null);
241       }
242       else
243       {
244          cmd = commandline;
245       }
246       
247       Runtime JavaDoc rt = Runtime.getRuntime();
248       s_logger.log(Level.FINEST, "Executing command "
249                             + StringUtils.concat(cmd, " ", null));
250       Process JavaDoc proc = rt.exec(cmd);
251       
252       // any error message?
253
StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(),
254                                                      "ERROR", bCapture,
255                                                      lMaxCaptureSize);
256       
257       // any output?
258
StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(),
259                                                       "OUTPUT", bCapture,
260                                                       lMaxCaptureSize);
261       
262       // kick them off
263
errorGobbler.start();
264       outputGobbler.start();
265       
266       returnValue[0] = proc;
267       returnValue[1] = outputGobbler;
268       returnValue[2] = errorGobbler;
269       
270       return returnValue;
271    }
272 }
273
Popular Tags