Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.apache.helix;
  
  /*
   * Licensed to the Apache Software Foundation (ASF) under one
   * or more contributor license agreements.  See the NOTICE file
   * distributed with this work for additional information
   * regarding copyright ownership.  The ASF licenses this file
   * to you under the Apache License, Version 2.0 (the
   * "License"); you may not use this file except in compliance
  * with the License.  You may obtain a copy of the License at
  *
  *   http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing,
  * software distributed under the License is distributed on an
  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  * KIND, either express or implied.  See the License for the
  * specific language governing permissions and limitations
  * under the License.
  */
 
 import java.io.File;
 import java.util.List;
 import java.util.Map;
 
Wrapper for running commands outside of the JVM

 
 public class ExternalCommand {
   public static final String MODULE = ExternalCommand.class.getName();
   public static final Logger LOG = Logger.getLogger();
 
   private final ProcessBuilder _processBuilder;
 
   private Process _process;
   private InputReader _out;
   private InputReader _err;

  
Stream redirector
 
   private static class InputReader extends Thread {
     private static final int BUFFER_SIZE = 2048;
 
     private final InputStream _in;
     private final ByteArrayOutputStream _out;
     private boolean _running = false;
 
     InputReader(InputStream in) {
        = in;
        = new ByteArrayOutputStream();
     }
 
     @Override
     public void run() {
        = true;
 
       byte[] buf = new byte[];
       int n = 0;
       try {
         while ((n = .read(buf)) != -1)
           .write(buf, 0, n);
       } catch (IOException e) {
         .error("error while reading external command"e);
       }
 
        = false;
     }
 
     public byte[] getOutput() {
       if ()
         throw new IllegalStateException("wait for process to be completed");
 
       return .toByteArray();
     }
   }

  
Initialize with a java.lang.ProcessBuilder

Parameters:
processBuilder initialized java.lang.ProcessBuilder object
 
   public ExternalCommand(ProcessBuilder processBuilder) {
      = processBuilder;
   }

  
After creating the command, you have to start it...

  public void start() throws IOException {
    .start();
    .start();
  }

  
  public Map<StringStringgetEnvironment() {
    return .environment();
  }

  
  public File getWorkingDirectory() {
    return .directory();
  }

  
  public void setWorkingDirectory(File directory) {
    .directory(directory);
  }

  
  public boolean getRedirectErrorStream() {
  }

  
  public void setRedirectErrorStream(boolean redirectErrorStream) {
    .redirectErrorStream(redirectErrorStream);
  }

  
Get the contents of the output stream after completion

Returns:
bytes from the output stream
Throws:
java.lang.InterruptedException the process was interrupted before completion
  public byte[] getOutput() throws InterruptedException {
    waitFor();
    return .getOutput();
  }

  
Get the contents of the error stream after completion

Returns:
bytes from the error stream
Throws:
java.lang.InterruptedException the process was interrupted before completion
  public byte[] getError() throws InterruptedException {
    waitFor();
    return .getOutput();
  }

  
Returns the output as a string.

Parameters:
encoding string encoding scheme, e.g. "UTF-8"
Returns:
encoded string
Throws:
java.lang.InterruptedException the process was interrupted before completion
java.io.UnsupportedEncodingException the encoding scheme is invalid
  public String getStringOutput(String encodingthrows InterruptedException,
    return new String(getOutput(), encoding);
  }

  
Returns the output as a string. Uses encoding "UTF-8".

Returns:
utf8 encoded string
Throws:
java.lang.InterruptedException the process was interrupted before completion
    try {
      return getStringOutput("UTF-8");
    } catch (UnsupportedEncodingException e) {
      // should not happen
      throw new RuntimeException(e);
    }
  }

  
Returns the error as a string.

Parameters:
encoding the encoding scheme, e.g. "UTF-8"
Returns:
error as string
Throws:
java.lang.InterruptedException the process was interrupted before completion
java.io.UnsupportedEncodingException the encoding scheme is invalid
  public String getStringError(String encodingthrows InterruptedException,
    return new String(getError(), encoding);
  }

  
Returns the error as a string. Uses encoding "UTF-8".

Returns:
error as string
Throws:
java.lang.InterruptedException the process was interrupted before completion
  public String getStringError() throws InterruptedException {
    try {
      return getStringError("UTF-8");
    } catch (UnsupportedEncodingException e) {
      // should not happen
      throw new RuntimeException(e);
    }
  }

  
Properly waits until everything is complete: joins on the thread that reads the output, joins on the thread that reads the error and finally wait for the process to be finished.

Returns:
the status code of the process.
Throws:
java.lang.InterruptedException the process was interrupted before completion
  public int waitFor() throws InterruptedException {
    if ( == null)
      throw new IllegalStateException("you must call start first");
    .join();
    .join();
    return .waitFor();
  }

  
Properly waits until everything is complete: joins on the thread that reads the output, joins on the thread that reads the error and finally wait for the process to be finished. If the process has not completed before the timeout, throws a java.util.concurrent.TimeoutException

Returns:
the status code of the process.
Throws:
java.util.concurrent.TimeoutException the process timed out
java.lang.InterruptedException the process was interrupted before completion
  public int waitFor(long timeoutthrows InterruptedExceptionTimeoutException {
    if ( == null)
      throw new IllegalStateException("you must call start first");
    // Chronos c = new Chronos();
    .join(timeout);
    // timeout -= c.tick();
    if (timeout <= 0)
      throw new TimeoutException("Wait timed out");
    .join(timeout);
    // timeout -= c.tick();
    if (timeout <= 0)
      throw new TimeoutException("Wait timed out");
    // there is no timeout in this API, not much we can do here
    // waiting on the other two threads should give us some safety
    return .waitFor();
  }

  

Returns:
the return code of the process
See also:
java.lang.Process.exitValue()
  public int exitValue() {
    if ( == null)
      throw new IllegalStateException("you must call start first");
    return .exitValue();
  }

  
  public void destroy() {
    if ( == null)
      throw new IllegalStateException("you must call start first");
    .destroy();
  }

  
Creates an external process from the command. It is not started and you have to call start on it!

Parameters:
commands the command to execute
Returns:
the process
  public static ExternalCommand create(String... commands) {
    ExternalCommand ec = new ExternalCommand(new ProcessBuilder(commands));
    return ec;
  }

  
Creates an external process from the command. It is not started and you have to call start on it!

Parameters:
commands the command to execute
Returns:
the process
  public static ExternalCommand create(List<Stringcommands) {
    ExternalCommand ec = new ExternalCommand(new ProcessBuilder(commands));
    return ec;
  }

  
Creates an external process from the command. The command is executed.

Parameters:
commands the commands to execute
Returns:
the process
Throws:
java.io.IOException if there is an error
  public static ExternalCommand start(String... commandsthrows IOException {
    ExternalCommand ec = new ExternalCommand(new ProcessBuilder(commands));
    ec.start();
    return ec;
  }

  
Executes the external command in the given working directory and waits for it to be finished.

Parameters:
workingDirectory the root directory from where to run the command
command the command to execute (should be relative to the working directory
args the arguments to the command
Returns:
the process
  public static ExternalCommand execute(File workingDirectoryString commandString... args)
      throws IOExceptionInterruptedException {
    try {
      return executeWithTimeout(workingDirectorycommand, 0, args);
    } catch (TimeoutException e) {
      // Can't happen!
      throw new IllegalStateException( + ".execute: Unexpected timeout occurred!");
    }
  }

  
Executes the external command in the given working directory and waits (until timeout is elapsed) for it to be finished.

Parameters:
workingDirectory the root directory from where to run the command
command the command to execute (should be relative to the working directory
timeout the maximum amount of time to wait for this external command (in ms). If this value is less than or equal to 0, timeout is ignored
args the arguments to the command
Returns:
the process
  public static ExternalCommand executeWithTimeout(File workingDirectoryString command,
      long timeoutString... argsthrows IOExceptionInterruptedExceptionTimeoutException {
    List<Stringarguments = new ArrayList<String>(args.length + 1);
    arguments.add(new File(workingDirectorycommand).getAbsolutePath());
    arguments.addAll(Arrays.asList(args));
    ExternalCommand cmd = ExternalCommand.create(arguments);
    cmd.setWorkingDirectory(workingDirectory);
    cmd.setRedirectErrorStream(true);
    cmd.start();
    /* Use timeout if it is a valid value! */
    if (timeout <= 0)
      cmd.waitFor();
    else
      cmd.waitFor(timeout);
    if (.isDebugEnabled())
      .debug(cmd.getStringOutput());
    return cmd;
  }
New to GrepCode? Check out our FAQ X