KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > rcm > util > Exec


1 /*
2  * Copyright (c) 1998-2002 Carnegie Mellon University. All rights
3  * reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  * notice, this list of conditions and the following disclaimer in
14  * the documentation and/or other materials provided with the
15  * distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND
18  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
19  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY
21  * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  *
29  */

30
31 package rcm.util;
32
33 import java.io.*;
34
35 public abstract class Exec {
36     public static Debug debug = Debug.QUIET;
37
38     public static Process JavaDoc exec (String JavaDoc[] cmdarray) throws IOException {
39         return exec (cmdarray, null, null);
40     }
41
42     public static Process JavaDoc exec (String JavaDoc[] cmdarray, String JavaDoc[] envp) throws IOException {
43         return exec (cmdarray, envp, null);
44     }
45
46     public static Process JavaDoc exec (String JavaDoc[] cmdarray, String JavaDoc[] envp, File directory) throws IOException {
47     return
48         isWindows ()
49         ? execWindows (cmdarray, envp, directory)
50         : execUnix (cmdarray, envp, directory);
51     }
52
53     /*
54      * Unix
55      */

56
57     static Process JavaDoc execUnix (String JavaDoc[] cmdarray, String JavaDoc[] envp, File directory) throws IOException {
58         // instead of calling command directly, we'll call the shell to change
59
// directory and set environment variables.
60

61         // start constructing the sh command line.
62
StringBuffer JavaDoc buf = new StringBuffer JavaDoc ();
63
64         if (directory != null) {
65             // change to directory
66
buf.append ("cd '");
67             buf.append (escapeQuote (directory.toString ()));
68             buf.append ("'; ");
69         }
70
71         if (envp != null) {
72             // set environment variables. Quote the value (but not the name).
73
for (int i = 0; i < envp.length; ++i) {
74                 String JavaDoc nameval = envp[i];
75                 int equals = nameval.indexOf ('=');
76                 if (equals == -1)
77                     throw new IOException ("environment variable '" + nameval
78                                            + "' should have form NAME=VALUE");
79                 buf.append (nameval.substring (0, equals+1));
80                 buf.append ('\'');
81                 buf.append (escapeQuote (nameval.substring (equals+1)));
82                 buf.append ("\' ");
83             }
84         }
85         
86         // now that we have the directory and environment, run "which"
87
// to test if the command name is found somewhere in the path.
88
// If "which" fails, throw an IOException.
89
String JavaDoc cmdname = escapeQuote (cmdarray[0]);
90         Runtime JavaDoc rt = Runtime.getRuntime ();
91         String JavaDoc[] sharray = new String JavaDoc[] { "sh", "-c", buf.toString () + " which \'" + cmdname + "\'" };
92         Process JavaDoc which = rt.exec (sharray);
93         try {
94             which.waitFor ();
95         } catch (InterruptedException JavaDoc e) {
96             throw new IOException ("interrupted");
97         }
98
99         if (which.exitValue () != 0)
100             throw new IOException ("can't execute " + cmdname + ": bad command or filename");
101
102         // finish in
103
buf.append ("exec \'");
104         buf.append (cmdname);
105         buf.append ("\' ");
106
107         // quote each argument in the command
108
for (int i = 1; i < cmdarray.length; ++i) {
109             buf.append ('\'');
110             buf.append (escapeQuote (cmdarray[i]));
111             buf.append ("\' ");
112         }
113
114         debug.println ("executing " + buf);
115         sharray[2] = buf.toString ();
116         return rt.exec (sharray);
117     }
118
119     static String JavaDoc escapeQuote (String JavaDoc s) {
120         // replace single quotes with a bit of magic (end-quote, escaped-quote, start-quote)
121
// that works in a single-quoted string in the Unix shell
122
if (s.indexOf ('\'') != -1) {
123             debug.println ("replacing single-quotes in " + s);
124             s = Str.replace (s, "'", "'\\''");
125             debug.println ("to get " + s);
126         }
127         return s;
128     }
129
130     /*
131      * Windows
132      */

133
134      static boolean isWindows () {
135         String JavaDoc os = System.getProperty ("os.name");
136     return (os != null && os.startsWith ("Windows"));
137      }
138
139      static boolean isJview () {
140         String JavaDoc vendor = System.getProperty ("java.vendor");
141     return (vendor != null && vendor.startsWith ("Microsoft"));
142      }
143
144     static Process JavaDoc execWindows (String JavaDoc[] cmdarray, String JavaDoc[] envp, File directory) throws IOException {
145     if (envp != null || directory != null) {
146         if (isJview ())
147         // jview doesn't support JNI, so can't call putenv/chdir
148
throw new IOException
149             ("can't use Exec.exec() under Microsoft JVM");
150         
151         if (!linked) {
152         try {
153             System.loadLibrary ("win32exec");
154             linked = true;
155         } catch (LinkageError JavaDoc e) {
156             throw new IOException ("can't use Exec.exec(): "
157                        + e.getMessage ());
158         }
159         }
160         
161         if (envp != null) {
162         for (int i = 0; i < envp.length; ++i)
163             putenv (envp[i]);
164         }
165         
166         if (directory != null)
167         chdir (directory.toString ());
168     }
169
170         return Runtime.getRuntime ().exec (cmdarray);
171     }
172
173     static boolean linked = false; // true after System.loadLibrary() is called
174
static native boolean putenv (String JavaDoc env);
175     static native boolean chdir (String JavaDoc dir);
176 }
177
Popular Tags