001 package de.mospace.lang;
002
003 /* Mp3dings - manage mp3 meta-information
004 * Copyright (C) 2006 Moritz Ringler
005 * $Id: ProcessRunnable.java 69 2007-10-24 21:57:43Z ringler $
006 *
007 * This program is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU General Public License
009 * as published by the Free Software Foundation; either version 2
010 * of the License, or (at your option) any later version.
011 *
012 * This program is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
015 * GNU General Public License for more details.
016 *
017 * You should have received a copy of the GNU General Public License
018 * along with this program; if not, write to the Free Software
019 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
020 */
021
022 import java.io.BufferedOutputStream;
023 import java.io.File;
024 import java.io.FileInputStream;
025 import java.io.FileOutputStream;
026 import java.io.IOException;
027 import java.io.InputStream;
028 import java.io.OutputStream;
029 import java.util.logging.Level;
030 import java.util.logging.Logger;
031
032 /** A runnable whose {@link #run run} method executes a system command.
033 * The system command is either specified as a single string or as an
034 * array of string tokens.
035 * @see java.lang.Runtime#exec
036 */
037 public class ProcessRunnable implements RunnableQueue.Job{
038 private static final Logger logger = Logger.getLogger(ProcessRunnable.class.getPackage().getName());
039 private String command;
040 private String cmdarray[];
041 private File dir = null;
042 private String[] envp;
043
044 /** Where the error stream of this Runnable's system command
045 * will be redirected.
046 * By default this is a {@link NullStream}. */
047 protected Output errp = new StreamOutput(NullStream.getInstance());
048
049 /** Where the output stream of this Runnable's system command
050 * will be redirected.
051 * By default this is a {@link NullStream}. */
052 protected Output outp = errp;
053
054 /** Where this Runnable's system command will read its standard input from.
055 * By default this is <code>null</code>. */
056 protected Input inpt;
057
058 private transient Process process = null;
059 private transient int exitValue = 0;
060 private ExceptionHandler exceptionHandler;
061 private static ThreadGroup iothreads = new ThreadGroup("ProcessRunableIO");
062
063 /** Constructs a new ProcessRunnable whose {@link #run} method will execute
064 * the specified command.
065 * @param command the system command to execute
066 */
067 public ProcessRunnable(String command){
068 this.command = command;
069 }
070
071 /** Constructs a new ProcessRunnable whose {@link #run} method will execute
072 * the command made up of the specified tokens.
073 * @param cmdarray the tokens that together form the command line to execute
074 */
075 public ProcessRunnable(String[] cmdarray){
076 setCommandImpl(cmdarray);
077 }
078
079 /** Throws an IllegalStateException when this process runnable is
080 * currently running.
081 * @throws IllegalStateException when this process runnable is
082 * currently running.
083 */
084 private final void checkRunning()
085 throws IllegalStateException{
086 if(isRunning()){
087 throw new IllegalStateException("Process is running.");
088 }
089 }
090
091 /** Sets the command that will be executed when {@link #run} is called.
092 * @param cmd the system command to execute
093 * @throws IllegalStateException when this process runnable is
094 * currently running.
095 */
096 public void setCommand(String cmd)
097 throws IllegalStateException{
098 checkRunning();
099 cmdarray = null;
100 command = cmd;
101 }
102
103 /** Returns the command that will be executed
104 * when {@link #run} is called.
105 * @return the system command to execute or <code>null</code>
106 * if this process runnable's command has been specified as an array.
107 */
108 public String getCommand(){
109 return command;
110 }
111
112 private void setCommandImpl(String[] cmdarray)
113 throws IllegalStateException{
114 checkRunning();
115 command = null;
116 this.cmdarray = new String[cmdarray.length];
117 System.arraycopy(cmdarray, 0, this.cmdarray, 0, cmdarray.length);
118 }
119
120 /** Sets the command line that will be executed
121 * when {@link #run} is called.
122 * @param cmdarray the tokens that together form the command line to
123 * execute
124 * @throws IllegalStateException when this process runnable is
125 * currently running.
126 */
127 public void setCommand(String[] cmdarray)
128 throws IllegalStateException{
129 setCommandImpl(cmdarray);
130 }
131
132 /** Returns a copy of the command line that will be executed
133 * when {@link #run} is called.
134 * @return the command line to execute or <code>null</code>
135 * if this process runnable's command has been specified as a single string.
136 */
137 public String[] getCommandArray(){
138 String[] cmds = new String[cmdarray.length];
139 System.arraycopy(cmdarray,0,cmds,0,cmdarray.length);
140 return cmds;
141 }
142
143 /** Returns the command that will be executed
144 * when {@link #run} is called, independently of whether this command
145 * has been specified as a single string or as an array of string tokens.
146 * @return the system command to execute
147 */
148 public String getCommandAsString(){
149 String result = getCommand();
150 if(result == null){
151 String[] ca = getCommandArray();
152 if(ca == null){
153 result = "null";
154 } else {
155 result = Array.join(ca,' ');
156 }
157 }
158 return result;
159 }
160
161 /** Redirects output of this process runnable's system command to
162 * the specified stream.
163 * When <code>null</code> is passed output from the external process
164 * will be read and discarded (the default). The specified
165 * output stream will not be
166 * closed by this class.
167 * @param o the output stream the program should write its output to
168 * @throws IllegalStateException when this process runnable is
169 * currently running.
170 */
171 public void redirectOutputTo(OutputStream o)
172 throws IllegalStateException{
173 checkRunning();
174 outp = new StreamOutput(o);
175 }
176
177 /** Redirects output of this process runnable's system command to
178 * the specified file. The file will be opened for writing and
179 * closed when the system commands starts and stops
180 * executing, respectively.
181 * @param f the file the program should write its output to
182 * @throws IllegalStateException when this process runnable is
183 * currently running.
184 */
185 public void redirectOutputTo(File f)
186 throws IllegalStateException{
187 checkRunning();
188 outp = new FileOutput(f);
189 }
190
191 /** Redirects error output of this process runnable's system command to
192 * the specified stream.
193 * When <code>null</code> is passed output from the external process
194 * will be read and discarded (the default). The specified
195 * output stream will not be
196 * closed by this class.
197 * @param o the output stream the program should write its output to
198 * @throws IllegalStateException when this process runnable is
199 * currently running.
200 **/
201 public void redirectErrorsTo(OutputStream o)
202 throws IllegalStateException{
203 checkRunning();
204 errp = new StreamOutput(o);
205 }
206
207 /** Redirects error output of this process runnable's system command to
208 * the specified file. The file will be opened for writing and
209 * closed when the system commands starts and stops
210 * executing, respectively.
211 * @param f the file the program should write its output to
212 * @throws IllegalStateException when this process runnable is
213 * currently running.
214 **/
215 public void redirectErrorsTo(File f)
216 throws IllegalStateException{
217 checkRunning();
218 errp = new FileOutput(f);
219 }
220
221 /** Sets the environment for this process runnable's system command.
222 * @param envp the environment for this process runnable's system command
223 * specified as an array of <code>"key=value"</code> pairs.
224 * @throws IllegalStateException when this process runnable is
225 * currently running.
226 * @see java.lang.Runtime#exec(String[] cmd,String[] envp, File dir)
227 * @see #getEnvironment
228 **/
229 public void setEnvironment(String[] envp)
230 throws IllegalStateException{
231 checkRunning();
232 this.envp = new String[envp.length];
233 System.arraycopy(envp,0,this.envp,0,envp.length);
234 }
235
236 /** Returns the environment for this process runnable's system command.
237 * @return the environment for this process runnable's system command
238 * as an array of <code>"key=value"</code> pairs.
239 * @see java.lang.Runtime#exec(String[] cmd,String[] envp, File dir)
240 * @see #setEnvironment
241 **/
242 public String[] getEnvironment(){
243 String[] env = null;
244 if(envp != null){
245 env = new String[envp.length];
246 System.arraycopy(envp,0,env,0,envp.length);
247 return env;
248 }
249 return env;
250 }
251
252 /** Sets the working directory for this process runnable's system command.
253 * @param dir the working directory for this process runnable's system
254 * command
255 * @throws IllegalStateException when this process runnable is
256 * currently running.
257 * @see java.lang.Runtime#exec(String[] cmd,String[] envp, File dir)
258 * @see #getWorkingDirectory
259 */
260 public void setWorkingDirectory(File dir)
261 throws IllegalStateException{
262 checkRunning();
263 this.dir = dir;
264 }
265
266 /** Returns the working directory for this process runnable's system command.
267 * @return the working directory for this process runnable's system
268 * command
269 * @see #getWorkingDirectory
270 */
271 public File getWorkingDirectory(){
272 return dir;
273 }
274
275 /** Executes this process runnable's system command. If we are already
276 * running then we first wait until the process spawned on the last
277 * invocation terminates.*/
278 public void run(){
279 try{
280 if(isRunning()){
281 waitFor();
282 }
283 process = null;
284 if (cmdarray != null && cmdarray.length != 0){
285 process = Runtime.getRuntime().exec(cmdarray, envp, dir);
286 } else if (command != null){
287 process = Runtime.getRuntime().exec(command, envp, dir);
288 } else {
289 return;
290 }
291 if (process == null){
292 return;
293 }
294 final Input pout = new StreamInput(process.getInputStream());
295 final Input perr = new StreamInput(process.getErrorStream());
296 final Output pin = new StreamOutput(
297 new BufferedOutputStream(process.getOutputStream()));
298 /* redirect output stream of process to out */
299 (new PipeThread(this, pout, outp)).start();
300 /* redirect error stream of process to err */
301 (new PipeThread(this, perr, errp)).start();
302 /* redirect input to input stream of process */
303 if(inpt != null){
304 (new PipeThread(this, inpt, pin)).start();
305 }
306
307 /* monitor process state */
308 exitValue = waitFor();
309 /* this will make isRunning() return false */
310 process = null;
311 } catch (Exception ex){
312 stop();
313 if(exceptionHandler == null){
314 throw new RuntimeException(ex);
315 } else {
316 exceptionHandler.handleException(ex);
317 }
318 }
319 }
320
321 /** Registers an exception handler to deal with exceptions
322 * thrown within the {@link #run} method. By default any exceptions
323 * thrown within run will be re-thrown as RuntimeExceptions.
324 * @param xh an exception handler
325 */
326 public void registerExceptionHandler(ExceptionHandler xh){
327 exceptionHandler = xh;
328 }
329
330 /** Returns the exception handler that deals with exceptions
331 * thrown within the {@link #run} method.
332 * @return the exception handler registered with this ProcessRunnable if any
333 * @see #registerExceptionHandler
334 */
335 protected ExceptionHandler getExceptionHandler(){
336 return exceptionHandler;
337 }
338
339 /** Kills the system process spawned by the {@link #run} method if
340 * this process runnable is currently running. */
341 public void stop(){
342 if (isRunning()){
343 process.destroy();
344 process = null;
345 }
346 }
347
348 /** Waits for the system process spawned by the {@link #run} method to
349 * terminate if this process runnable is currently running. In this case
350 * the exit value of the currently running process is returned. Otherwise
351 * this method has the same effect as {@link #getExitStatus}.
352 * @return the exit value of the currently running process
353 * @throws InterruptedException if the system process is interrupted
354 */
355 public int waitFor() throws InterruptedException{
356 if (isRunning()){
357 return process.waitFor();
358 } else {
359 return exitValue;
360 }
361 }
362
363 /** Returns the exit status of the system process that returned last.
364 * @return the exit status of the system process that returned last or zero
365 * if this runnable has never run.
366 */
367 public int getExitStatus(){
368 return exitValue;
369 }
370
371 /** Returns whether this process runnable is currently running.
372 * @return whether this process runnable is currently running
373 */
374 public boolean isRunning(){
375 return (process != null);
376 }
377
378 /** Makes this process runnable's system command read input from the
379 * specified file. The file will be opened for reading and
380 * closed when the system commands starts and stops
381 * executing, respectively.
382 * @param f the file to read input from
383 */
384 public void readInputFrom(File f){
385 inpt = new FileInput(f);
386 }
387
388 /** Makes this process runnable's system command read input from the
389 * specified stream.
390 * @param i the stream to read input from
391 */
392 public void readInputFrom(InputStream i){
393 inpt = new StreamInput(i);
394 }
395
396 /** Returns whether this process runnable currently has a non-null input.
397 * @return whether this process runnable has a non-null input
398 * @see #readInputFrom(File)
399 * @see #readInputFrom(InputStream)
400 */
401 public boolean hasInput(){
402 return inpt != null;
403 }
404
405 /** Causes this process runnable to not provide any standard input
406 * to its system command. */
407 public void clearInput(){
408 inpt = null;
409 }
410
411 /** A thread that writes
412 * bytes from its input to its output as long as
413 * the associated ProcessRunnable is running. All pipe threads belong to the
414 * same thread group named ProcessRunableIO.
415 */
416 protected static class PipeThread extends Thread{
417 /** The input that this PipeThread reads from. */
418 protected Input inp;
419
420 /** The output that this PipeThread writes to. */
421 protected Output outp;
422
423 byte[] myBuff = new byte[1024];
424 private final ProcessRunnable owner;
425
426 /** The common ThreadGroup of all PipeThreads. */
427 private static ThreadGroup iothreads = new ThreadGroup("ProcessRunableIO");
428
429 /** Creates a new PipeThread with the specified owner, input, and
430 * output, and an auto-generated thread name.
431 * @param the ProcessRunnable whose input and output the new PipeThread
432 * will handle
433 * @param read the input that the new PipeThread reads from
434 * @param writep the output that the new PipeThread writes to
435 **/
436 PipeThread(ProcessRunnable owner, Input read,
437 Output writep){
438 this(owner, read, writep, null);
439 }
440
441 /** Creates a new PipeThread with the specified owner, input,
442 * output, and thread name.
443 * @param the ProcessRunnable whose input and output the new PipeThread
444 * will handle
445 * @param read the input that the new PipeThread reads from
446 * @param writep the output that the new PipeThread writes to
447 * @param id the thread name for the new PipeThread. If it is <code>
448 * null</code> or empty than a thread name is auto-generated.
449 **/
450 PipeThread(ProcessRunnable owner, Input read,
451 Output writep, String id){
452 super(iothreads, (id==null || id.equals(""))
453 ? "PipeThread: " + owner.getCommandAsString() + " " +
454 read.toString() + " " +
455 writep.toString() + " (Created " +
456 System.currentTimeMillis() +")"
457 : id);
458 outp = writep;
459 inp = read;
460 this.owner = owner;
461 };
462
463 /** Opens this pipe thread's input and output and writes any
464 * bytes that become available on the input to the output.
465 * When it encounters an End Of File on the input or when the
466 * process runnable associated with this PipeThread stops running
467 * the close methods of input and output will be called.
468 */
469 public void run(){
470 InputStream input = null;
471 OutputStream output = null;
472 try {
473 input = inp.openInputStream();
474 if(input == null){ /* treat null as empty input */
475 return;
476 }
477 output = outp.openOutputStream();
478
479 for (int i = 0; i > -1; i = input.read(myBuff)) {
480 synchronized (output){
481 output.write(myBuff,0,i);
482 output.flush();
483 output.notifyAll();
484 }
485 if(!owner.isRunning()){
486 break;
487 }
488 }
489 output.flush();
490 } catch (IOException ex) {
491 StackTraceElement elements[] = ex.getStackTrace();
492 logger.log(Level.SEVERE, ex.toString());
493 for (int i=0, n=elements.length; i<n; i++) {
494 logger.log(Level.SEVERE, elements[i].getMethodName());
495 }
496 } finally {
497 try{
498 if(output != null){
499 outp.closeOutputStream(output);
500 }
501 } catch (IOException ex) {
502 logger.warning("Error closing output " + output);
503 logger.warning(ex.toString());
504 }
505 try{
506 if(input != null){
507 inp.closeInputStream(input);
508 }
509 } catch (IOException ex) {
510 logger.warning("Error closing input " + input);
511 logger.warning(ex.toString());
512 }
513 }
514 }
515 }
516
517 /** A common interface for various kinds of byte sources. */
518 protected static interface Input{
519
520 /** Opens and/or returns this byte source as an input stream.
521 * @return the input stream for this byte source
522 */
523 public InputStream openInputStream() throws IOException;
524
525 /** Signals that no more bytes will be read from the specified
526 * input stream. Depending on the kind of input the input stream
527 * may or may not be closed by this method.
528 * @param stream an input stream obtained from a previous call to
529 * {@link #openInputStream}.
530 */
531 public void closeInputStream(InputStream stream) throws IOException;
532 }
533
534 /** Wraps a file as a {@link Input}. */
535 protected final static class FileInput implements Input{
536 private final File f;
537
538 /** Creates a new {@link Input} object from the specified file. **/
539 public FileInput(File f){
540 this.f = f;
541 }
542
543 /** Opens the file specified in the constructor for reading.
544 * @return a new {@link java.io.FileInputStream} object
545 */
546 public InputStream openInputStream() throws IOException{
547 return new FileInputStream(f);
548 }
549
550 /** Closes the specified stream.
551 * @param stream an input stream obtained from a previous call to
552 * {@link #openInputStream}.
553 */
554 public void closeInputStream(InputStream stream) throws IOException{
555 stream.close();
556 }
557
558 /** Returns a string representation of this object.
559 * @return a string representation of this object. */
560 public String toString(){
561 return (f==null)? "null" : "<"+f.getPath();
562 }
563 }
564
565 /** Wraps an input stream as a {@link Input}. */
566 protected final static class StreamInput implements Input{
567 private final InputStream inp;
568
569 /** Creates a new {@link Input} object from the specified stream.
570 * @param stream an InputStream or <code>null</code> for empty input. **/
571 public StreamInput(InputStream stream){
572 inp = stream;
573 }
574
575 /** Returns the input stream specified in the constructor.
576 * Clients should handle <code>null</code> gracefully
577 * treating it as empty input.
578 * @return an input stream or <code>null</code>
579 */
580 public InputStream openInputStream(){
581 return inp;
582 }
583
584 /** Does nothing. **/
585 public void closeInputStream(InputStream stream){
586 //does nothing
587 }
588
589 /** Returns a string representation of this object.
590 * @return a string representation of this object. */
591 public String toString(){
592 return "<"+String.valueOf(inp);
593 }
594 }
595
596 /** A common interface for various kinds of byte sinks. */
597 protected static interface Output{
598
599 /** Opens and/or returns this byte sink as an output stream.
600 * @return the output stream for this byte sink
601 */
602 public OutputStream openOutputStream() throws IOException;
603
604 /** Signals that no more bytes will be written to the specified
605 * output stream. Depending on the kind of output the output stream
606 * may or may not be closed by this method.
607 * @param out an output stream obtained from a previous call to
608 * {@link #openOutputStream}.
609 */
610 public void closeOutputStream(OutputStream out) throws IOException;
611 }
612
613 /** Wraps a file as a {@link Output}. */
614 protected static class FileOutput implements Output{
615 private final File f;
616
617 /** Creates a new {@link Output} object from the specified file. **/
618 public FileOutput(File f){
619 this.f = f;
620 }
621
622 /** Opens the file specified in the constructor for writing.
623 * @return a new {@link java.io.FileOutputStream} object
624 */
625 public OutputStream openOutputStream() throws IOException{
626 return new FileOutputStream(f);
627 }
628
629 /** Closes the specified stream.
630 * @param out an output stream obtained from a previous call to
631 * {@link #openOutputStream}.
632 */
633 public void closeOutputStream(OutputStream out) throws IOException{
634 out.close();
635 }
636
637 /** Returns a string representation of this object.
638 * @return a string representation of this object. */
639 public String toString(){
640 return (f==null)? "null" : ">"+f.getPath();
641 }
642 }
643
644 /** Wraps an input stream as a {@link Input}. */
645 protected static class StreamOutput implements Output{
646 private final OutputStream s;
647
648 /** Creates a new {@link Output} object from the specified stream.
649 * @param o an OutputStream or <code>null</code> for a
650 * {@link NullStream}. **/
651 public StreamOutput(OutputStream o){
652 s = (o==null)? NullStream.getInstance(): o;
653 }
654
655 /** Returns the output stream for this StreamOutput.
656 * @return a non-null output stream
657 */
658 public OutputStream openOutputStream(){
659 return s;
660 }
661
662 /** Does nothing */
663 public void closeOutputStream(OutputStream out){
664 //does nothing
665 }
666
667 /** Returns a string representation of this object.
668 * @return a string representation of this object. */
669 public String toString(){
670 return ">"+String.valueOf(s);
671 }
672 }
673
674 }