View Javadoc
1   package org.codehaus.plexus.util.cli;
2   
3   /*
4    * Copyright The Codehaus Foundation.
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  import java.io.InputStream;
20  import java.util.Locale;
21  import java.util.Map;
22  import java.util.Properties;
23  import java.util.StringTokenizer;
24  import java.util.Vector;
25  
26  import org.codehaus.plexus.util.Os;
27  import org.codehaus.plexus.util.StringUtils;
28  
29  /**
30   * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l </a>
31   *
32   */
33  public abstract class CommandLineUtils {
34  
35      /**
36       * A {@code StreamConsumer} providing consumed lines as a {@code String}.
37       *
38       * @see #getOutput()
39       */
40      public static class StringStreamConsumer implements StreamConsumer {
41  
42          private StringBuffer string = new StringBuffer();
43  
44          private String ls = System.getProperty("line.separator");
45  
46          @Override
47          public void consumeLine(String line) {
48              string.append(line).append(ls);
49          }
50  
51          public String getOutput() {
52              return string.toString();
53          }
54      }
55  
56      /**
57       * Number of milliseconds per second.
58       */
59      private static final long MILLIS_PER_SECOND = 1000L;
60  
61      /**
62       * Number of nanoseconds per second.
63       */
64      private static final long NANOS_PER_SECOND = 1000000000L;
65  
66      public static int executeCommandLine(Commandline cl, StreamConsumer systemOut, StreamConsumer systemErr)
67              throws CommandLineException {
68          return executeCommandLine(cl, null, systemOut, systemErr, 0);
69      }
70  
71      public static int executeCommandLine(
72              Commandline cl, StreamConsumer systemOut, StreamConsumer systemErr, int timeoutInSeconds)
73              throws CommandLineException {
74          return executeCommandLine(cl, null, systemOut, systemErr, timeoutInSeconds);
75      }
76  
77      public static int executeCommandLine(
78              Commandline cl, InputStream systemIn, StreamConsumer systemOut, StreamConsumer systemErr)
79              throws CommandLineException {
80          return executeCommandLine(cl, systemIn, systemOut, systemErr, 0);
81      }
82  
83      /**
84       * @param cl The command line to execute
85       * @param systemIn The input to read from, must be thread safe. {@link System#in} is polled for available data, so
86       *            the call does not wait for it once the process has ended
87       * @param systemOut A consumer that receives output, must be thread safe
88       * @param systemErr A consumer that receives system error stream output, must be thread safe
89       * @param timeoutInSeconds Positive integer to specify timeout, zero and negative integers for no timeout.
90       * @return A return value, see {@link Process#exitValue()}
91       * @throws CommandLineException or CommandLineTimeOutException if time out occurs
92       */
93      public static int executeCommandLine(
94              Commandline cl,
95              InputStream systemIn,
96              StreamConsumer systemOut,
97              StreamConsumer systemErr,
98              int timeoutInSeconds)
99              throws CommandLineException {
100         final CommandLineCallable future =
101                 executeCommandLineAsCallable(cl, systemIn, systemOut, systemErr, timeoutInSeconds);
102         return future.call();
103     }
104 
105     /**
106      * Immediately forks a process, returns a callable that will block until process is complete.
107      *
108      * @param cl The command line to execute
109      * @param systemIn The input to read from, must be thread safe. {@link System#in} is polled for available data, so
110      *            the call does not wait for it once the process has ended
111      * @param systemOut A consumer that receives output, must be thread safe
112      * @param systemErr A consumer that receives system error stream output, must be thread safe
113      * @param timeoutInSeconds Positive integer to specify timeout, zero and negative integers for no timeout.
114      * @return A CommandLineCallable that provides the process return value, see {@link Process#exitValue()}. "call"
115      *         must be called on this to be sure the forked process has terminated, no guarantees is made about any
116      *         internal state before after the completion of the call statements
117      * @throws CommandLineException or CommandLineTimeOutException if time out occurs
118      */
119     public static CommandLineCallable executeCommandLineAsCallable(
120             final Commandline cl,
121             final InputStream systemIn,
122             final StreamConsumer systemOut,
123             final StreamConsumer systemErr,
124             final int timeoutInSeconds)
125             throws CommandLineException {
126         if (cl == null) {
127             throw new IllegalArgumentException("cl cannot be null.");
128         }
129 
130         final Process p = cl.execute();
131 
132         final Thread processHook = new Thread() {
133 
134             {
135                 this.setName("CommandLineUtils process shutdown hook");
136                 this.setContextClassLoader(null);
137             }
138 
139             @Override
140             public void run() {
141                 p.destroy();
142             }
143         };
144 
145         ShutdownHookUtils.addShutDownHook(processHook);
146 
147         return new CommandLineCallable() {
148 
149             @Override
150             public Integer call() throws CommandLineException {
151                 StreamFeeder inputFeeder = null;
152                 StreamPumper outputPumper = null;
153                 StreamPumper errorPumper = null;
154                 boolean success = false;
155                 try {
156                     if (systemIn != null) {
157                         if (systemIn == System.in) {
158                             // may never deliver data nor end, so poll it instead of blocking in a read
159                             inputFeeder = new StreamPollFeeder(systemIn, p.getOutputStream());
160                         } else {
161                             inputFeeder = new StreamFeeder(systemIn, p.getOutputStream());
162                         }
163                         inputFeeder.start();
164                     }
165 
166                     outputPumper = new StreamPumper(p.getInputStream(), systemOut);
167                     outputPumper.start();
168 
169                     errorPumper = new StreamPumper(p.getErrorStream(), systemErr);
170                     errorPumper.start();
171 
172                     int returnValue;
173                     if (timeoutInSeconds <= 0) {
174                         returnValue = p.waitFor();
175                     } else {
176                         final long now = System.nanoTime();
177                         final long timeout = now + NANOS_PER_SECOND * timeoutInSeconds;
178 
179                         while (isAlive(p) && (System.nanoTime() < timeout)) {
180                             // The timeout is specified in seconds. Therefore we must not sleep longer than one second
181                             // but we should sleep as long as possible to reduce the number of iterations performed.
182                             Thread.sleep(MILLIS_PER_SECOND - 1L);
183                         }
184 
185                         if (isAlive(p)) {
186                             throw new InterruptedException(
187                                     String.format("Process timed out after %d seconds.", timeoutInSeconds));
188                         }
189 
190                         returnValue = p.exitValue();
191                     }
192 
193                     // TODO Find out if waitUntilDone needs to be called using a try-finally construct. The method may
194                     // throw an
195                     // InterruptedException so that calls to waitUntilDone may be skipped.
196                     // try
197                     // {
198                     // if ( inputFeeder != null )
199                     // {
200                     // inputFeeder.waitUntilDone();
201                     // }
202                     // }
203                     // finally
204                     // {
205                     // try
206                     // {
207                     // outputPumper.waitUntilDone();
208                     // }
209                     // finally
210                     // {
211                     // errorPumper.waitUntilDone();
212                     // }
213                     // }
214                     if (inputFeeder != null) {
215                         inputFeeder.waitUntilDone();
216                     }
217 
218                     outputPumper.waitUntilDone();
219                     errorPumper.waitUntilDone();
220 
221                     if (inputFeeder != null) {
222                         inputFeeder.close();
223                         handleException(inputFeeder, "stdin");
224                     }
225 
226                     outputPumper.close();
227                     handleException(outputPumper, "stdout");
228 
229                     errorPumper.close();
230                     handleException(errorPumper, "stderr");
231 
232                     success = true;
233                     return returnValue;
234                 } catch (InterruptedException ex) {
235                     throw new CommandLineTimeOutException(
236                             "Error while executing external command, process killed.", ex);
237 
238                 } finally {
239                     if (inputFeeder != null) {
240                         inputFeeder.disable();
241                     }
242                     if (outputPumper != null) {
243                         outputPumper.disable();
244                     }
245                     if (errorPumper != null) {
246                         errorPumper.disable();
247                     }
248 
249                     try {
250                         ShutdownHookUtils.removeShutdownHook(processHook);
251                         processHook.run();
252                     } finally {
253                         try {
254                             if (inputFeeder != null) {
255                                 inputFeeder.close();
256 
257                                 if (success) {
258                                     success = false;
259                                     handleException(inputFeeder, "stdin");
260                                     success = true; // Only reached when no exception has been thrown.
261                                 }
262                             }
263                         } finally {
264                             try {
265                                 if (outputPumper != null) {
266                                     outputPumper.close();
267 
268                                     if (success) {
269                                         success = false;
270                                         handleException(outputPumper, "stdout");
271                                         success = true; // Only reached when no exception has been thrown.
272                                     }
273                                 }
274                             } finally {
275                                 if (errorPumper != null) {
276                                     errorPumper.close();
277 
278                                     if (success) {
279                                         handleException(errorPumper, "stderr");
280                                     }
281                                 }
282                             }
283                         }
284                     }
285                 }
286             }
287         };
288     }
289 
290     private static void handleException(final StreamPumper streamPumper, final String streamName)
291             throws CommandLineException {
292         if (streamPumper.getException() != null) {
293             throw new CommandLineException(
294                     String.format("Failure processing %s.", streamName), streamPumper.getException());
295         }
296     }
297 
298     private static void handleException(final StreamFeeder streamFeeder, final String streamName)
299             throws CommandLineException {
300         if (streamFeeder.getException() != null) {
301             throw new CommandLineException(
302                     String.format("Failure processing %s.", streamName), streamFeeder.getException());
303         }
304     }
305 
306     /**
307      * Gets the shell environment variables for this process. Note that the returned mapping from variable names to
308      * values will always be case-sensitive regardless of the platform, i.e. <code>getSystemEnvVars().get("path")</code>
309      * and <code>getSystemEnvVars().get("PATH")</code> will in general return different values. However, on platforms
310      * with case-insensitive environment variables like Windows, all variable names will be normalized to upper case.
311      *
312      * @return The shell environment variables, can be empty but never <code>null</code>.
313      * @see System#getenv() System.getenv() API, new in JDK 5.0, to get the same result <b>since 2.0.2 System#getenv()
314      *      will be used if available in the current running jvm.</b>
315      */
316     public static Properties getSystemEnvVars() {
317         return getSystemEnvVars(!Os.isFamily(Os.FAMILY_WINDOWS));
318     }
319 
320     /**
321      * Return the shell environment variables. If <code>caseSensitive == true</code>, then envar keys will all be
322      * upper-case.
323      *
324      * @param caseSensitive Whether environment variable keys should be treated case-sensitively.
325      * @return Properties object of (possibly modified) envar keys mapped to their values.
326      * @see System#getenv() System.getenv() API, new in JDK 5.0, to get the same result <b>since 2.0.2 System#getenv()
327      *      will be used if available in the current running jvm.</b>
328      */
329     public static Properties getSystemEnvVars(boolean caseSensitive) {
330         Properties envVars = new Properties();
331         Map<String, String> envs = System.getenv();
332         for (String key : envs.keySet()) {
333             String value = envs.get(key);
334             if (!caseSensitive) {
335                 key = key.toUpperCase(Locale.ENGLISH);
336             }
337             envVars.put(key, value);
338         }
339         return envVars;
340     }
341 
342     public static boolean isAlive(Process p) {
343         if (p == null) {
344             return false;
345         }
346 
347         try {
348             p.exitValue();
349             return false;
350         } catch (IllegalThreadStateException e) {
351             return true;
352         }
353     }
354 
355     public static String[] translateCommandline(String toProcess) throws Exception {
356         if ((toProcess == null) || (toProcess.length() == 0)) {
357             return new String[0];
358         }
359 
360         // parse with a simple finite state machine
361 
362         final int normal = 0;
363         final int inQuote = 1;
364         final int inDoubleQuote = 2;
365         int state = normal;
366         StringTokenizer tok = new StringTokenizer(toProcess, "\"\' \t\n\r", true);
367         Vector<String> v = new Vector<String>();
368         StringBuilder current = new StringBuilder();
369 
370         while (tok.hasMoreTokens()) {
371             String nextTok = tok.nextToken();
372             switch (state) {
373                 case inQuote:
374                     if ("\'".equals(nextTok)) {
375                         state = normal;
376                     } else {
377                         current.append(nextTok);
378                     }
379                     break;
380                 case inDoubleQuote:
381                     if ("\"".equals(nextTok)) {
382                         state = normal;
383                     } else {
384                         current.append(nextTok);
385                     }
386                     break;
387                 default:
388                     if ("\'".equals(nextTok)) {
389                         state = inQuote;
390                     } else if ("\"".equals(nextTok)) {
391                         state = inDoubleQuote;
392                     } else if (" ".equals(nextTok)
393                             || "\t".equals(nextTok)
394                             || "\n".equals(nextTok)
395                             || "\r".equals(nextTok)) {
396                         if (current.length() != 0) {
397                             v.addElement(current.toString());
398                             current.setLength(0);
399                         }
400                     } else {
401                         current.append(nextTok);
402                     }
403                     break;
404             }
405         }
406 
407         if (current.length() != 0) {
408             v.addElement(current.toString());
409         }
410 
411         if ((state == inQuote) || (state == inDoubleQuote)) {
412             throw new CommandLineException("unbalanced quotes in " + toProcess);
413         }
414 
415         String[] args = new String[v.size()];
416         v.copyInto(args);
417         return args;
418     }
419 
420     /**
421      * <p>
422      * Put quotes around the given String if necessary.
423      * </p>
424      * <p>
425      * If the argument doesn't include spaces or quotes, return it as is. If it contains double quotes, use single
426      * quotes - else surround the argument by double quotes.
427      * </p>
428      * @param argument the argument
429      * @return the transformed command line
430      * @throws CommandLineException if the argument contains both, single and double quotes.
431      * @deprecated Use {@link StringUtils#quoteAndEscape(String, char, char[], char[], char, boolean)},
432      *             {@link StringUtils#quoteAndEscape(String, char, char[], char, boolean)}, or
433      *             {@link StringUtils#quoteAndEscape(String, char)} instead.
434      */
435     @Deprecated
436     @SuppressWarnings({"JavaDoc"})
437     public static String quote(String argument) throws CommandLineException {
438         return quote(argument, false, false, true);
439     }
440 
441     /**
442      * <p>
443      * Put quotes around the given String if necessary.
444      * </p>
445      * <p>
446      * If the argument doesn't include spaces or quotes, return it as is. If it contains double quotes, use single
447      * quotes - else surround the argument by double quotes.
448      * </p>
449      * @param argument see name
450      * @param wrapExistingQuotes see name
451      * @return the transformed command line
452      * @throws CommandLineException if the argument contains both, single and double quotes.
453      * @deprecated Use {@link StringUtils#quoteAndEscape(String, char, char[], char[], char, boolean)},
454      *             {@link StringUtils#quoteAndEscape(String, char, char[], char, boolean)}, or
455      *             {@link StringUtils#quoteAndEscape(String, char)} instead.
456      */
457     @Deprecated
458     @SuppressWarnings({"JavaDoc", "UnusedDeclaration"})
459     public static String quote(String argument, boolean wrapExistingQuotes) throws CommandLineException {
460         return quote(argument, false, false, wrapExistingQuotes);
461     }
462 
463     /**
464      * @param argument the argument
465      * @param escapeSingleQuotes see name
466      * @param escapeDoubleQuotes see name
467      * @param wrapExistingQuotes see name
468      * @return the transformed command line
469      * @throws CommandLineException some trouble
470      * @deprecated Use {@link StringUtils#quoteAndEscape(String, char, char[], char[], char, boolean)},
471      *             {@link StringUtils#quoteAndEscape(String, char, char[], char, boolean)}, or
472      *             {@link StringUtils#quoteAndEscape(String, char)} instead.
473      */
474     @Deprecated
475     @SuppressWarnings({"JavaDoc"})
476     public static String quote(
477             String argument, boolean escapeSingleQuotes, boolean escapeDoubleQuotes, boolean wrapExistingQuotes)
478             throws CommandLineException {
479         if (argument.contains("\"")) {
480             if (argument.contains("\'")) {
481                 throw new CommandLineException("Can't handle single and double quotes in same argument");
482             } else {
483                 if (escapeSingleQuotes) {
484                     return "\\\'" + argument + "\\\'";
485                 } else if (wrapExistingQuotes) {
486                     return '\'' + argument + '\'';
487                 }
488             }
489         } else if (argument.contains("\'")) {
490             if (escapeDoubleQuotes) {
491                 return "\\\"" + argument + "\\\"";
492             } else if (wrapExistingQuotes) {
493                 return '\"' + argument + '\"';
494             }
495         } else if (argument.contains(" ")) {
496             if (escapeDoubleQuotes) {
497                 return "\\\"" + argument + "\\\"";
498             } else {
499                 return '\"' + argument + '\"';
500             }
501         }
502 
503         return argument;
504     }
505 
506     public static String toString(String[] line) {
507         // empty path return empty string
508         if ((line == null) || (line.length == 0)) {
509             return "";
510         }
511 
512         // path containing one or more elements
513         final StringBuilder result = new StringBuilder();
514         for (int i = 0; i < line.length; i++) {
515             if (i > 0) {
516                 result.append(' ');
517             }
518             try {
519                 result.append(StringUtils.quoteAndEscape(line[i], '\"'));
520             } catch (Exception e) {
521                 System.err.println("Error quoting argument: " + e.getMessage());
522             }
523         }
524         return result.toString();
525     }
526 }