Java 类java.lang.ProcessBuilder 实例源码

项目:aamg    文件:GenerateAaMigration.java   
/**
 * Use the awk script to get the custom types declared as TypeSerializer in the target file
 */
private static Map<String, String> getCustomTypes(String file) throws IOException {
    ProcessBuilder builder = new ProcessBuilder("awk", AWK_GET_SOURCE_DESTINATION_TYPES, file);
    builder.redirectErrorStream(true);
    Process p = builder.start();

    Map<String, String> types = new HashMap<>();
    BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line;
    while (true) {
        line = r.readLine();
        if (line == null) {
            break;
        }
        String[] typeInfo = line.split(" ");
        if (typeInfo.length == 2) {
            types.put(typeInfo[0], typeInfo[1]);
        }
    }
    return types;
}
项目:aamg    文件:GenerateAaMigration.java   
/**
 * Use grep to see all the files that contain TypeSerializer, and collect them all
 */
private static Map<String, String> getCustomTypes() throws IOException {
    String line;
    Map<String, String> types = new HashMap<>();
    ProcessBuilder builder = new ProcessBuilder("grep", "-rlP", "extends\\s+TypeSerializer");
    builder.redirectErrorStream(true);
    Process p = builder.start();
    BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));

    // This grep command will output only the file names of the files that contain a TypeSerializer
    while (true) {
        line = r.readLine();
        if (line == null) {
            break;
        }
        // Add all the custom types contained in that file
        types.putAll(getCustomTypes(line));
    }

    return types;
}
项目:ca-iris    文件:OSUtils.java   
/**
 * Start a new process.
 *
 * @param cmd The cmd/arg list for execution
 * @param merge True to merge the process's error stream into its
 *              output stream
 * @return The new Process, or null upon failure
 */
static private Process startProcess(List<String> cmd, boolean merge) {
    if (cmd == null)
        return null;
    ProcessBuilder pb = new ProcessBuilder(cmd);
    if (merge)
        pb = pb.redirectErrorStream(true);
    Process proc = null;
    try {
        proc = pb.start();
    }
    catch(IOException e) {
        e.printStackTrace();
    }
    return proc;
}
项目:umple    文件:RuntimeErrorUtil.java   
public static void AssertRuntimeError(String javaClass, String expectedOutputFile) {
    // Construct a sub-process to run the generated java file
    ProcessBuilder pb = new ProcessBuilder("java", "-cp", SOURCE_FOLDER, PACKAGE_NAME + javaClass);
    try {
        Process p = pb.start();

        BufferedReader actualReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        BufferedReader expectedReader = new BufferedReader(new FileReader(Paths.get(EXPECTED_FOLDER + expectedOutputFile).toFile()));

        CompareOutputToExpected(actualReader, expectedReader);

        actualReader.close();
        expectedReader.close();
    }
    catch(Exception e) {
        Assert.fail(e.getMessage());
    }
}
项目:umple    文件:CompilerErrorUtil.java   
public static void AssertCompileError(String umpleFile, String expectedOutputFile) {
    // Construct a sub-process to build the umple file and compile the resulting Java
    ProcessBuilder pb = new ProcessBuilder("java", "-jar", UMPLE_JAR, "-c-", SOURCE_FOLDER + umpleFile);
    try {
        Process p = pb.start();

        BufferedReader actualReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        BufferedReader expectedReader = new BufferedReader(new FileReader(Paths.get(EXPECTED_FOLDER + expectedOutputFile).toFile()));

        CompareCompiledOutputToExpected(actualReader, expectedReader);

        actualReader.close();
        expectedReader.close();
    }
    catch(Exception e) {
        Assert.fail(e.getMessage());
    }
}
项目:https-github.com-h2oai-h2o-3    文件:H2OBuildVersion.java   
private String calcBranch() {
  try {
    Process p = new ProcessBuilder("git", "branch").start();
    p.waitFor();
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = br.readLine();
    while (line != null) {
      if (!line.startsWith("*")) {
        line = br.readLine();
        continue;
      }

      String branch = line.substring(2);
      return branch;
    }
    return "(unknown)";
  }
  catch (Exception e) {
    return "(unknown)";
  }
}
项目:h2o-3    文件:H2OBuildVersion.java   
private String calcBranch() {
  try {
    Process p = new ProcessBuilder("git", "branch").start();
    p.waitFor();
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = br.readLine();
    while (line != null) {
      if (!line.startsWith("*")) {
        line = br.readLine();
        continue;
      }

      String branch = line.substring(2);
      return branch;
    }
    return "(unknown)";
  }
  catch (Exception e) {
    return "(unknown)";
  }
}
项目:h2o-3    文件:H2OBuildVersion.java   
private String calcDescribe() {
  try {
    Process p = new ProcessBuilder("git", "describe", "--always", "--dirty").start();
    p.waitFor();
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = br.readLine();
    return line;
  }
  catch (Exception e) {
    return "(unknown)";
  }
}
项目:Clash-Royale    文件:Commands.java   
public static void Command(String[] command)
{
    try
    {
        builder = new ProcessBuilder(command).start();
        builder.waitFor();
    } catch (IOException | InterruptedException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    builder.destroy();

}
项目:postgres-tools    文件:ResolveAddress.java   
/**
 * Resolve address
 * @param binary The binary
 * @param address The address
 * @return The resolved address
 */
private static String resolveAddress(String binary, String address) throws Exception
{
   int offset = address.indexOf("+0x");

   if (offset != -1)
   {
      String function = address.substring(0, offset);

      List<String> command = new ArrayList<>();
      command.add("eu-addr2line");
      command.add("-e");
      command.add(binary);
      command.add(address);

      ProcessBuilder pb = new ProcessBuilder(command);
      Process p = pb.start();

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      InputStream is = p.getInputStream();
      int c = is.read();
      while (c != -1)
      {
         baos.write(c);
         c = is.read();
      }

      is.close();
      p.waitFor();

      String output = baos.toString();
      if (output.startsWith("/"))
      {
         return function + "|" + output.substring(output.lastIndexOf("/") + 1, output.length() - 1);
      }
   }

   return address;
}
项目:https-github.com-h2oai-h2o-3    文件:H2OBuildVersion.java   
private String calcLastCommitHash() {
  try {
    Process p = new ProcessBuilder("git", "log", "-1", "--format=%H").start();
    p.waitFor();
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = br.readLine();
    return line;
  }
  catch (Exception e) {
    return "(unknown)";
  }
}
项目:https-github.com-h2oai-h2o-3    文件:H2OBuildVersion.java   
private String calcDescribe() {
  try {
    Process p = new ProcessBuilder("git", "describe", "--always", "--dirty").start();
    p.waitFor();
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = br.readLine();
    return line;
  }
  catch (Exception e) {
    return "(unknown)";
  }
}
项目:h2o-3    文件:H2OBuildVersion.java   
private String calcLastCommitHash() {
  try {
    Process p = new ProcessBuilder("git", "log", "-1", "--format=%H").start();
    p.waitFor();
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = br.readLine();
    return line;
  }
  catch (Exception e) {
    return "(unknown)";
  }
}
项目:heapSpank    文件:GarbageSpankSampler.java   
private String executeJStat(long pidToMonitor, SampleResult result) throws IOException, InterruptedException {
    // String javaHome = System.getenv("JAVA_HOME");
    // String fullCmdPath = javaHome + File.separator + "bin" +
    // File.separator + "jstat";
    // log.info("JAVA_HOME: [" + javaHome + "]");
    // log.info("full [" + fullCmdPath + "]");

    List<String> processArgs = new ArrayList<String>();

    String fullCmdPath = "jstat";
    processArgs.add(fullCmdPath);

    // String pidToMonitor = arg0.getParameter("PID");
    //String pidToMonitor = JMeterUtils.getPropDefault("PID", null);
    //String pidToMonitor = "15350";

    processArgs.add( "-" + this.garbageSpank.getJStatOption() );
    processArgs.add( String.valueOf(pidToMonitor)); // process id

    this.getLogger().debug(LOG_PREFIX+
            "Args for invoking jmap: [" + processArgs.toString() + "]");
    ProcessBuilder processBuilder = new ProcessBuilder(processArgs);

    processBuilder.redirectErrorStream(true);

    Process process = processBuilder.start();
    StringBuilder processOutput = new StringBuilder();

    BufferedReader processOutputReader = new BufferedReader(
            new InputStreamReader(process.getInputStream()));

    String readLine;

    int lineCount = 0;
    while ((readLine = processOutputReader.readLine()) != null) {
        if (lineCount > 0)
            processOutput.append(readLine + System.lineSeparator());
        lineCount++;
    }

    process.waitFor();
    return processOutput.toString();
}
项目:heapSpank    文件:LeakySpankSampler.java   
private String executeJMapHisto(String pidToMonitor, SampleResult result) throws IOException, InterruptedException {
    // String javaHome = System.getenv("JAVA_HOME");
    // String fullCmdPath = javaHome + File.separator + "bin" +
    // File.separator + "jstat";
    // log.info("JAVA_HOME: [" + javaHome + "]");
    // log.info("full [" + fullCmdPath + "]");

    List<String> processArgs = new ArrayList<String>();

    String fullCmdPath = "jmap";
    processArgs.add(fullCmdPath);

    // String pidToMonitor = arg0.getParameter("PID");
    //String pidToMonitor = JMeterUtils.getPropDefault("PID", null);
    //String pidToMonitor = "15350";

    if (pidToMonitor == null || pidToMonitor.trim().length()==0) {
        String error = "Could not find JMeter variable named 'PID', which must have a value of the process id (pid); of the process you want to detect leaks in.";
        getLogger().error(error);
        result.setResponseData(error, "UTF-8");
        result.setResponseCode("500");
        result.sampleEnd();// time for all transformations
        return LEAKY_SPANKY + "_MISSING_PID=99<BR>\n";
    }
    processArgs.add("-histo");
    processArgs.add(pidToMonitor); // process id

    this.getLogger().info(
            "Args for invoking jmap: [" + processArgs.toString() + "]");
    ProcessBuilder processBuilder = new ProcessBuilder(processArgs);

    processBuilder.redirectErrorStream(true);

    Process process = processBuilder.start();
    StringBuilder processOutput = new StringBuilder();

    BufferedReader processOutputReader = new BufferedReader(
            new InputStreamReader(process.getInputStream()));

    String readLine;

    int lineCount = 0;
    while ((readLine = processOutputReader.readLine()) != null) {
        if (lineCount > 0)
            processOutput.append(readLine + System.lineSeparator());
        lineCount++;
    }

    process.waitFor();
    return processOutput.toString();
}
项目:semanticvectors    文件:MyTestUtils.java   
/**
 * Spawn a child to execute the main method in Class childMain
 * using the same args and environment as the current runtime.
 * This method prevents a child processes from hanging
 * when its output buffers saturate by creating threads to
 * empty the output buffers.
 * @return The process, already started. Consider using waitForAndDestroy() to clean up afterwards.
 * @param childMain The Class to spawn, must contain main function
 * @param inputArgs arguments for the main class. Use null to pass no arguments.
 * @param in The child process will read input from this stream. Use null to avoid reading input. Always close() your stream when you are done or you may deadlock.
 * @param out The child process will write output to this stream. Use null to avoid writing output.
 * @param err The child process will write errors to this stream. Use null to avoid writing output.
 */
public static Process spawnChildProcess(
    Class<?> childMain, String[] inputArgs, InputStream in, OutputStream out, OutputStream err)
    throws IOException {
  //get the same arguments as used to start this JRE
  RuntimeMXBean rmxb = ManagementFactory.getRuntimeMXBean();
  List<String> arglist = rmxb.getInputArguments();
  String cp = rmxb.getClassPath();

  //construct "java <arguments> <main-class-name>"
  ArrayList<String> arguments = new ArrayList<String>(arglist);
  arguments.add(0, "java");
  arguments.add("-classpath");
  arguments.add(cp);
  arguments.add(childMain.getCanonicalName());
  for (String arg : inputArgs) arguments.add(arg);

  //using ProcessBuilder initializes the child process with parent's env.
  ProcessBuilder pb = new ProcessBuilder(arguments);

  //redirecting STDERR to STDOUT needs to be done before starting
  if (err == out) {
    pb.redirectErrorStream(true);
  }

  Process proc;
  proc = pb.start(); //Might throw an IOException to calling method

  //setup stdin
  if (in != null) {
    new OutputReader(in, proc.getOutputStream()).start();
  }

  //setup stdout
  if (out == null) {
    out = new NullOutputStream();
  }
  new OutputReader(proc.getInputStream(), out).start();

  //setup stderr
  if (!pb.redirectErrorStream()) {
    if (err == null) {
      err = new NullOutputStream();
    }
    new OutputReader(proc.getErrorStream(), err).start();
  }

  return proc;
}
项目:SLAMon    文件:SystemTests.java   
public AFM()
{
    processBuilder = new ProcessBuilder();
    processBuilder.directory(new File("/home/vagrant/SLAMon/"));
}
项目:SLAMon    文件:SystemTests.java   
public Agent()
{
    processBuilder = new ProcessBuilder();
    processBuilder.directory(new File("/home/vagrant/SLAMon/"));
}
项目:jAudioGIT    文件:JAudioFile.java   
public static void main(String[] args) throws Exception{
    processor = new AudioStreamProcessor(args[0],args[1]);

String base_prefix =args[2];
base_prefix += args[4];

ProcessBuilder gstreamerBuilder = new ProcessBuilder("gst-launch-1.0", "-q", "filesrc", "location="+args[3], "!", "decodebin", "!", "audioconvert", "!", "audio/x-raw,format=F32LE", "!", "fdsink");
Process gstreamer =  gstreamerBuilder.start();
       DataInputStream input = new DataInputStream(gstreamer.getInputStream());
ByteBuffer buffer = ByteBuffer.allocateDirect(1000000000);
buffer.order(java.nio.ByteOrder.LITTLE_ENDIAN);
       byte[] b = new byte[1000000];
int read=0;
int total=0;
while((read = input.read(b))>-1){
    total += read;
    if(read > 0)
        buffer.put(b,0,read);
}
System.out.println();
buffer.flip();
FloatBuffer db = buffer.asFloatBuffer();

       double[] samples = new double[total / 8];
for(int i=0;i<samples.length;++i){
    samples[i] = (db.get()+db.get()) / 2.0;
}   
db = null;
       buffer = null;
double max=0.0;
double min=0.0;
boolean okay = false;
if(samples.length < 512){
    throw new Exception("File is too small to analyze - "+samples.length+" samples");
}
for(int i=0;i<samples.length;++i){
        if((samples[i] > 1.0) || (samples[i] < -1.0)){
        throw new Exception("Badly formatted data "+i+" "+samples[i]);
    }
    if((samples[i] > 0.7)){
        okay = true;
    }
}
if(!okay){
    throw new Exception("Data is artificially small - probable endianess problem");
}
processor.process(samples);

Date date = new Date();
       String attach = date.toString();
       attach = Pattern.compile("\\s").matcher(attach).replaceAll("_");
       base_prefix += Pattern.compile(":").matcher(attach).replaceAll("-");
       processor.output(base_prefix);
   }
项目:semanticvectors-googlecode    文件:MyTestUtils.java   
/**
 * Spawn a child to execute the main method in Class childMain
 * using the same args and environment as the current runtime.
 * This method prevents a child processes from hanging
 * when its output buffers saturate by creating threads to
 * empty the output buffers.
 * @return The process, already started. Consider using waitForAndDestroy() to clean up afterwards.
 * @param childMain The Class to spawn, must contain main function
 * @param inputArgs arguments for the main class. Use null to pass no arguments.
 * @param in The child process will read input from this stream. Use null to avoid reading input. Always close() your stream when you are done or you may deadlock.
 * @param out The child process will write output to this stream. Use null to avoid writing output.
 * @param err The child process will write errors to this stream. Use null to avoid writing output.
 */
public static Process spawnChildProcess(
    Class<?> childMain, String[] inputArgs, InputStream in, OutputStream out, OutputStream err)
    throws IOException {
  //get the same arguments as used to start this JRE
  RuntimeMXBean rmxb = ManagementFactory.getRuntimeMXBean();
  List<String> arglist = rmxb.getInputArguments();
  String cp = rmxb.getClassPath();

  //construct "java <arguments> <main-class-name>"
  ArrayList<String> arguments = new ArrayList<String>(arglist);
  arguments.add(0, "java");
  arguments.add("-classpath");
  arguments.add(cp);
  arguments.add(childMain.getCanonicalName());
  for (String arg : inputArgs) arguments.add(arg);

  //using ProcessBuilder initializes the child process with parent's env.
  ProcessBuilder pb = new ProcessBuilder(arguments);

  //redirecting STDERR to STDOUT needs to be done before starting
  if (err == out) {
    pb.redirectErrorStream(true);
  }

  Process proc;
  proc = pb.start(); //Might throw an IOException to calling method

  //setup stdin
  if (in != null) {
    new OutputReader(in, proc.getOutputStream()).start();
  }

  //setup stdout
  if (out == null) {
    out = new NullOutputStream();
  }
  new OutputReader(proc.getInputStream(), out).start();

  //setup stderr
  if (!pb.redirectErrorStream()) {
    if (err == null) {
      err = new NullOutputStream();
    }
    new OutputReader(proc.getErrorStream(), err).start();
  }

  return proc;
}