public static boolean testCommand(
     final Context context,
     final String command,
     final String contains,
     final List<String> arguments) {
   try {
     final List<String> commandAndArgs = new ArrayList<String>();
     commandAndArgs.add(command);
     commandAndArgs.addAll(arguments);
     final ProcessBuilder pb = new ProcessBuilder(commandAndArgs);
     logCommand(context, pb);
     final Process compilation = pb.start();
     final ConsumeStream result = ConsumeStream.start(compilation.getInputStream(), null);
     final ConsumeStream error = ConsumeStream.start(compilation.getErrorStream(), null);
     compilation.waitFor();
     result.join();
     error.join();
     return error.output.toString().contains(contains)
         || result.output.toString().contains(contains);
   } catch (IOException ex) {
     context.log(ex.getMessage());
     return false;
   } catch (InterruptedException ex) {
     context.log(ex.getMessage());
     return false;
   }
 }
 private static Process startSlaveProcess(int commPort) throws IOException {
   String separator = System.getProperty("file.separator");
   String javaProc = System.getProperty("java.home") + separator + "bin" + separator + "java";
   ProcessBuilder pb =
       new ProcessBuilder(
           javaProc,
           "-cp",
           "target/test-classes;.",
           CrashingSlave.class.getName(),
           String.valueOf(commPort));
   return pb.start();
 }
Example #3
0
 private void setExecutablePermissions(File gradleHome) {
   if (isWindows()) {
     return;
   }
   File gradleCommand = new File(gradleHome, "bin/gradle");
   String errorMessage = null;
   try {
     ProcessBuilder pb = new ProcessBuilder("chmod", "755", gradleCommand.getCanonicalPath());
     Process p = pb.start();
     if (p.waitFor() == 0) {
       System.out.println("Set executable permissions for: " + gradleCommand.getAbsolutePath());
     } else {
       BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
       errorMessage = "";
       String line;
       while ((line = is.readLine()) != null) {
         errorMessage += line + System.getProperty("line.separator");
       }
     }
   } catch (IOException e) {
     errorMessage = e.getMessage();
   } catch (InterruptedException e) {
     errorMessage = e.getMessage();
   }
   if (errorMessage != null) {
     System.out.println(
         "Could not set executable permissions for: " + gradleCommand.getAbsolutePath());
     System.out.println("Please do this manually if you want to use the Gradle UI.");
   }
 }
Example #4
0
  /** Run new Maven os process with given arguments and commands. */
  public void execute() {
    Process process = null;
    BufferedReader br = null;
    try {
      ProcessBuilder processBuilder = getProcessBuilder();
      processBuilder.redirectErrorStream(true);
      log.info("Starting process: " + processBuilder.command());

      process = processBuilder.start();

      // Read output
      br = new BufferedReader(new InputStreamReader(process.getInputStream()));
      String line;
      while ((line = br.readLine()) != null) {
        System.out.println(line);
      }

      process.waitFor();
    } catch (Exception e) {
      throw new RuntimeException(e);
    } finally {
      close(br);
      destroyProcess(process);
    }
  }
 public static Either<CommandResult> runCommand(
     final Context context, final String command, final File path, final List<String> arguments) {
   try {
     final List<String> commandAndArgs = new ArrayList<String>();
     commandAndArgs.add(command);
     commandAndArgs.addAll(arguments);
     final ProcessBuilder pb = new ProcessBuilder(commandAndArgs);
     if (path != null) {
       pb.directory(path);
     }
     logCommand(context, pb);
     final Process compilation = pb.start();
     final ConsumeStream result = ConsumeStream.start(compilation.getInputStream(), context);
     final ConsumeStream error = ConsumeStream.start(compilation.getErrorStream(), context);
     final int exitCode = compilation.waitFor();
     result.join();
     error.join();
     if (result.exception != null) {
       return Either.fail(result.exception);
     }
     if (error.exception != null) {
       return Either.fail(error.exception);
     }
     return Either.success(
         new CommandResult(result.output.toString(), error.output.toString(), exitCode));
   } catch (IOException ex) {
     return Either.fail(ex);
   } catch (InterruptedException ex) {
     return Either.fail(ex);
   }
 }
  public static ArrayList<String> callSimString(String[] command) {

    ArrayList<String> result = new ArrayList<String>();

    try {

      // System.out.println("calling: "+command);

      ProcessBuilder processBuilder = new ProcessBuilder(command);

      Process p = processBuilder.start();

      p.waitFor();

      BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
      String line = "";
      while (((line = reader.readLine()) != null)) {
        result.add(line);
        System.out.println(line);
      }

      p.destroy();

    } catch (Exception exc) {
      System.out.println(exc.getMessage());
    }

    return result;
  }
 public boolean findDeviceTypeADB() throws Exception {
   log("trying to find device type ...");
   log("------------------------------");
   if (platformName.equalsIgnoreCase("iOS")) {
     // TO Be added
   } else {
     String adb = "adb";
     String[] adbCommand = {adb, "shell", "getprop", "ro.build.characteristics"};
     try {
       ProcessBuilder p = new ProcessBuilder(adbCommand);
       Process proc = p.start();
       InputStream stdin = proc.getInputStream();
       InputStreamReader isr = new InputStreamReader(stdin);
       BufferedReader br = new BufferedReader(isr);
       String line = null;
       String[] size = null;
       while ((line = br.readLine()) != null) {
         if (line.contains("tablet")) {
           return true;
         }
       }
     } catch (Throwable t) {
       t.printStackTrace();
     }
   }
   return false;
 }
    // Creates a new thread, runs the program in that thread, and reports any errors as needed.
    private void run(String clazz) {
      try {
        // Makes sure the JVM resets if it's already running.
        if (JVMrunning) kill();

        // Some String constants for java path and OS-specific separators.
        String separator = System.getProperty("file.separator");
        String path = System.getProperty("java.home") + separator + "bin" + separator + "java";

        // Tries to run compiled code.
        ProcessBuilder builder = new ProcessBuilder(path, clazz);

        // Should be good now! Everything past this is on you. Don't mess it up.
        println(
            "Build succeeded on " + java.util.Calendar.getInstance().getTime().toString(), progErr);
        println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", progErr);

        JVM = builder.start();

        // Note that as of right now, there is no support for input. Only output.
        Reader errorReader = new InputStreamReader(JVM.getErrorStream());
        Reader outReader = new InputStreamReader(JVM.getInputStream());
        // Writer inReader = new OutputStreamWriter(JVM.getOutputStream());

        redirectErr = redirectIOStream(errorReader, err);
        redirectOut = redirectIOStream(outReader, out);
        // redirectIn = redirectIOStream(null, inReader);
      } catch (Exception e) {
        // This catches any other errors we might get.
        println("Some error thrown", progErr);
        logError(e.toString());
        displayLog();
        return;
      }
    }
 private String getIPAndroid() {
   String host = "localhost";
   try {
     ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "adb shell netcfg");
     builder.redirectErrorStream(true);
     Process p = builder.start();
     BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
     String line;
     while (true) {
       line = r.readLine();
       if (line == null) {
         break;
       }
       if (line.contains("0x00001043")) {
         //                    wlan0    UP                                192.168.1.79/24
         // 0x00001043 b4:52:7d:c5:8b:69
         int index = line.indexOf("/24");
         line = line.substring(0, index);
         index = line.lastIndexOf(" ");
         host = line.substring(index + 1);
         break;
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
     Notifications.Bus.notify(
         new Notification(
             Constant.GROUND_ID, "Error getIPAndroid", e.toString(), NotificationType.ERROR));
   }
   return host;
 }
Example #10
0
  public static String test123() {
    String r = "";

    try {
      // System.setSecurityManager(null);

      // String[] callArgs = {"mkdir", "/home/alexis/test123"};
      String[] callArgs = {"ls"};
      ProcessBuilder pb = new ProcessBuilder(callArgs);
      pb.redirectErrorStream(true);
      Process p = pb.start();
      p.waitFor();

      // BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream() ));
      BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
      String line = "";
      System.out.println("Start Output");
      while ((line = br.readLine()) != null) r += line + "\n";
      System.out.println("End Output");

      /*Process p = Runtime.getRuntime().exec(callArgs);
      p.waitFor();
      System.out.println("Test Complete");*/
      r = line;
    } catch (IOException e) {
      System.out.println(e);
      r = "Test failed";
    } catch (Exception e) {
    }

    return r;
  }
  // Uses adb commands to tap at relative coordinates. To be used when appium methods fail. Only
  // works on Android devices.
  public void tapAtRelativeCoordinatesADB(double x_offset, double y_offset) throws Exception {
    if (platformName.equalsIgnoreCase("iOS")) {
      tapAtRelativeCoordinates(x_offset, y_offset);
    } else {
      Dimension size = getScreenSizeADB();
      log("Size of device as seen by ADB is - width: " + size.width + " height: " + size.height);
      String x = String.valueOf(size.width * x_offset);
      String y = String.valueOf(size.height * y_offset);
      log("ADB: x and y: " + x + ", " + y);
      String[] adbCommand = {"adb", "shell", "input", "tap", x, y};
      //            String[] adbCommand = {"adb", "shell", "input", "touchscreen", "swipe", x, y, x,
      // y, "2000"};

      try {
        ProcessBuilder p = new ProcessBuilder(adbCommand);
        Process proc = p.start();
        InputStream stdin = proc.getInputStream();
        InputStreamReader isr = new InputStreamReader(stdin);
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        while ((line = br.readLine()) != null) System.out.print(line);

        proc.waitFor();

      } catch (Throwable t) {
        t.printStackTrace();
      }
    }
  }
  /**
   * ======================================================================================
   * TESSERACT GRAB TEXT FROM IMAGE
   * ======================================================================================
   */
  public String grabText(String image) throws Exception {
    findAndCropImageFromScreen(image);
    String imageInput =
        screenshotsFolder
            + getScreenshotsCounter()
            + "_"
            + image
            + "_screenshot"
            + getRetryCounter()
            + "_"
            + timeDifferenceStartTest
            + "sec"
            + ".png";
    String[] tesseractCommand = {"tesseract", imageInput, "stdout"};
    String value = "";
    try {
      ProcessBuilder p = new ProcessBuilder(tesseractCommand);
      Process proc = p.start();
      InputStream stdin = proc.getInputStream();
      InputStreamReader isr = new InputStreamReader(stdin);
      BufferedReader br = new BufferedReader(isr);
      String line;
      String[] size = null;
      String[] splitLines;
      while ((line = br.readLine()) != null) {
        value += line;
      }

    } catch (Throwable t) {
      t.printStackTrace();
    }
    return value;
  }
Example #13
0
  /** @param directory Directory where we list tags */
  @Override
  protected void buildTagList(File directory) {
    this.tagList = new TreeSet<TagEntry>();
    ArrayList<String> argv = new ArrayList<String>();
    ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK);
    argv.add(cmd);
    argv.add("tags");
    ProcessBuilder pb = new ProcessBuilder(argv);
    pb.directory(directory);
    Process process = null;
    BufferedReader in = null;

    try {
      process = pb.start();
      in = new BufferedReader(new InputStreamReader(process.getInputStream()));
      String line;
      while ((line = in.readLine()) != null) {
        String parts[] = line.split("  *");
        if (parts.length < 2) {
          throw new HistoryException("Tag line contains more than 2 columns: " + line);
        }
        // Grrr, how to parse tags with spaces inside?
        // This solution will loose multiple spaces;-/
        String tag = parts[0];
        for (int i = 1; i < parts.length - 1; ++i) {
          tag += " " + parts[i];
        }
        TagEntry tagEntry = new BazaarTagEntry(Integer.parseInt(parts[parts.length - 1]), tag);
        // Bazaar lists multiple tags on more lines. We need to merge those into single TagEntry
        TagEntry higher = this.tagList.ceiling(tagEntry);
        if (higher != null && higher.equals(tagEntry)) {
          // Found in the tree, merge tags
          this.tagList.remove(higher);
          tagEntry.setTags(higher.getTags() + ", " + tag);
        }
        this.tagList.add(tagEntry);
      }
    } catch (IOException e) {
      OpenGrokLogger.getLogger().log(Level.WARNING, "Failed to read tag list: {0}", e.getMessage());
      this.tagList = null;
    } catch (HistoryException e) {
      OpenGrokLogger.getLogger()
          .log(Level.WARNING, "Failed to parse tag list: {0}", e.getMessage());
      this.tagList = null;
    }

    IOUtils.close(in);
    if (process != null) {
      try {
        process.exitValue();
      } catch (IllegalThreadStateException e) {
        // the process is still running??? just kill it..
        process.destroy();
      }
    }
  }
  private void initLogstash(String testName) {

    initLogstashHost();

    String pathToLogstash =
        SGTestHelper.getSGTestRootDir().replace("\\", "/") + "/src/main/resources/logstash";
    String confFilePath = pathToLogstash + "/logstash-shipper-client.conf";
    String fixedTestName = testName.substring(0, testName.length() - 2);
    String backupFilePath = pathToLogstash + "/logstash-shipper-client-" + fixedTestName + ".conf";

    if (process == null) {

      try {

        LogUtils.log("copying file " + confFilePath + " to " + backupFilePath);
        IOUtils.copyFile(confFilePath, backupFilePath);
        //                backupFilePath = IOUtils.backupFile(confFilePath);
        IOUtils.replaceTextInFile(
            backupFilePath,
            "<path_to_test_folder>",
            SGTestHelper.getSGTestRootDir().replace("\\", "/")
                + "/../"
                + suiteName
                + "/"
                + testName);
        IOUtils.replaceTextInFile(backupFilePath, "<suite_name>", suiteName);
        IOUtils.replaceTextInFile(backupFilePath, "<test_name>", testName);
        IOUtils.replaceTextInFile(backupFilePath, "<build_number>", buildNumber);
        IOUtils.replaceTextInFile(backupFilePath, "<version>", version);
        IOUtils.replaceTextInFile(backupFilePath, "<host>", logstashHost);

        String logstashJarPath =
            DeploymentUtils.getLocalRepository() + "net/logstash/1.2.2/logstash-1.2.2.jar";
        logstashLogPath = pathToLogstash + "/logstash-" + fixedTestName + ".txt";
        String cmdLine =
            "java -jar "
                + logstashJarPath
                + " agent -f "
                + backupFilePath
                + " -l "
                + logstashLogPath;

        final String[] parts = cmdLine.split(" ");
        final ProcessBuilder pb = new ProcessBuilder(parts);
        LogUtils.log("Executing Command line: " + cmdLine);

        TimeUnit.SECONDS.sleep(1);
        process = pb.start();

      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
 @Override
 public Object apply(List<Object> args, Context context) throws ParseException {
   File outFile = null;
   String editor = getEditor();
   try {
     outFile = File.createTempFile("stellar_shell", "out");
     if (args.size() > 0) {
       String arg = (String) args.get(0);
       try (PrintWriter pw = new PrintWriter(outFile)) {
         IOUtils.write(arg, pw);
       }
     }
   } catch (IOException e) {
     String message = "Unable to create temp file: " + e.getMessage();
     LOG.error(message, e);
     throw new IllegalStateException(message, e);
   }
   Optional<Object> console = context.getCapability(CONSOLE, false);
   try {
     PausableInput.INSTANCE.pause();
     // shut down the IO for the console
     ProcessBuilder processBuilder = new ProcessBuilder(editor, outFile.getAbsolutePath());
     processBuilder.redirectInput(ProcessBuilder.Redirect.INHERIT);
     processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
     processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
     try {
       Process p = processBuilder.start();
       // wait for termination.
       p.waitFor();
       try (BufferedReader br = new BufferedReader(new FileReader(outFile))) {
         String ret = IOUtils.toString(br).trim();
         return ret;
       }
     } catch (Exception e) {
       String message = "Unable to read output: " + e.getMessage();
       LOG.error(message, e);
       return null;
     }
   } finally {
     try {
       PausableInput.INSTANCE.unpause();
       if (console.isPresent()) {
         ((Console) console.get()).pushToInputStream("\b\n");
       }
     } catch (IOException e) {
       LOG.error("Unable to unpause: " + e.getMessage(), e);
     }
     if (outFile.exists()) {
       outFile.delete();
     }
   }
 }
Example #16
0
  /**
   * Launch the specified call list.
   *
   * @param callList launch the call list
   * @return {@code true} in case the launch was successful
   */
  private boolean launchCallList(final List<String> callList) {
    try {
      final ProcessBuilder pBuilder = new ProcessBuilder(callList);

      File workingDirectory = DirectoryManager.getInstance().getWorkingDirectory();
      if (workingDirectory != null) {
        pBuilder.directory(workingDirectory);
      }
      pBuilder.redirectErrorStream(true);
      final Process proc = pBuilder.start();
      proc.getOutputStream().close();

      final StringBuilder outputBuffer = new StringBuilder();
      outputReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));

      launchTimer.start();
      cancelExecution = false;

      while (true) {
        if (cancelExecution) {
          throw new IOException("Response Timeout.");
        }
        final String line = outputReader.readLine();
        if (line == null) {
          errorData = outputBuffer.toString().trim();
          return false;
        }
        if (line.endsWith("Startup done.")) {
          outputReader.close();
          return true;
        }
        outputBuffer.append(line);
        outputBuffer.append('\n');
      }
    } catch (@Nonnull final Exception e) {
      final StringWriter sWriter = new StringWriter();
      final PrintWriter writer = new PrintWriter(sWriter);
      e.printStackTrace(writer);
      writer.flush();
      errorData = sWriter.toString();
      return false;
    } finally {
      if (outputReader != null) {
        try {
          outputReader.close();
        } catch (@Nonnull final IOException e) {
          // nothing
        }
      }
      outputReader = null;
    }
  }
Example #17
0
 private void execAndWait(String s) throws InterruptedException {
   ProcessBuilder pb = new ProcessBuilder(s, "convert_xml_to_js.js");
   pb.directory(new File("/Users/josh/projects/compilerclass/guitest2/"));
   try {
     Process proc = pb.start();
     proc.waitFor();
     p("processing");
   } catch (IOException e) {
     e
         .printStackTrace(); // To change body of catch statement use File | Settings | File
                             // Templates.
   }
 }
Example #18
0
 private static String run(String... cmds) throws IOException {
   ProcessBuilder pb = new ProcessBuilder(cmds);
   pb.redirectErrorStream(true);
   Process process = pb.start();
   StringWriter sw = new StringWriter();
   char[] chars = new char[1024];
   try (Reader r = new InputStreamReader(process.getInputStream())) {
     for (int len; (len = r.read(chars)) > 0; ) {
       sw.write(chars, 0, len);
     }
   }
   return sw.toString();
 }
  /**
   * This method invokes wmic outside of the normal environment collection routines.
   *
   * <p>An initial call to wmic can be costly in terms of time. <code>
   * Details of why the first call is costly can be found at:
   *
   * http://support.microsoft.com/kb/290216/en-us
   *
   * "When you run the Wmic.exe utility for the first time, the utility
   * compiles its .mof files into the repository. To save time during
   * Windows installation, this operation takes place as necessary."
   * </code>
   */
  private String getWmicResult(String alias, String verb, String property) {
    String res = "";
    BufferedReader in = null;
    BufferedWriter bw = null;
    try {
      ProcessBuilder pb = new ProcessBuilder("cmd", "/C", "WMIC", alias, verb, property);
      Process p = pb.start();
      // need this for executing windows commands (at least
      // needed for executing wmic command)
      bw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
      bw.write(13);

      p.waitFor();
      if (p.exitValue() == 0) {
        in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = null;
        while ((line = in.readLine()) != null) {
          line = line.trim();
          if (line.length() == 0) {
            continue;
          }
          res = line;
        }
        // return the *last* line read
        return res;
      }

    } catch (Exception e) {
      // ignore the exception
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
          // ignore
        }
      }
      if (bw != null) {
        try {
          bw.flush();
        } catch (Exception ex) { // ignore...
        }
        try {
          bw.close();
        } catch (Exception ex) { // ignore...
        }
      }
    }
    return res.trim();
  }
  private String getFullWmicResult(String alias, String verb, String property) {
    StringBuilder res = new StringBuilder();
    BufferedReader in = null;
    BufferedWriter bw = null;
    try {
      ProcessBuilder pb = new ProcessBuilder("cmd", "/C", "WMIC", alias, verb, property);
      Process p = pb.start();
      // need this for executing windows commands (at least
      // needed for executing wmic command)
      bw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
      bw.write(13);
      bw.flush();

      p.waitFor();
      if (p.exitValue() == 0) {
        in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = null;
        while ((line = in.readLine()) != null) {
          line = line.trim();
          if (line.length() == 0) {
            continue;
          }
          if (line.toLowerCase(Locale.US).indexOf(property.toLowerCase(Locale.US)) != -1) {
            continue;
          }
          res.append(line).append("\n");
        }
      }

    } catch (Exception e) {
      // ignore the exception
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
          // ignore
        }
      }

      if (bw != null) {
        try {
          bw.close();
        } catch (IOException e) {
          // ignore
        }
      }
    }
    return res.toString();
  }
 private static void logCommand(final Context context, final ProcessBuilder builder) {
   final StringBuilder description = new StringBuilder("Running: ");
   for (final String arg : builder.command()) {
     description.append(arg).append(" ");
   }
   context.log(description.toString());
 }
Example #22
0
  public void restartApplication() {

    try {

      final String javaBin =
          System.getProperty("java.home") + File.separator + "bin" + File.separator + "javaw";
      final File currentJar =
          new File(network.class.getProtectionDomain().getCodeSource().getLocation().toURI());

      System.out.println("javaBin " + javaBin);
      System.out.println("currentJar " + currentJar);
      System.out.println("currentJar.getPath() " + currentJar.getPath());

      /* is it a jar file? */
      // if(!currentJar.getName().endsWith(".jar")){return;}

      try {

        // xmining = 0;
        // systemx.shutdown();

      } catch (Exception e) {
        e.printStackTrace();
      }

      /* Build command: java -jar application.jar */
      final ArrayList<String> command = new ArrayList<String>();
      command.add(javaBin);
      command.add("-jar");
      command.add("-Xms256m");
      command.add("-Xmx1024m");
      command.add(currentJar.getPath());

      final ProcessBuilder builder = new ProcessBuilder(command);
      builder.start();

      // try{Thread.sleep(10000);} catch (InterruptedException e){}

      // close and exit
      SystemTray.getSystemTray().remove(network.icon);
      System.exit(0);

    } // try
    catch (Exception e) {
      JOptionPane.showMessageDialog(null, e.getCause());
    }
  } // ******************************
  public void processBuilder(String[] adbCommand) {
    try {
      found = true;
      ProcessBuilder p = new ProcessBuilder(adbCommand);
      Process proc = p.start();
      InputStream stdin = proc.getInputStream();
      InputStreamReader isr = new InputStreamReader(stdin);
      BufferedReader br = new BufferedReader(isr);
      String line = null;
      while ((line = br.readLine()) != null) System.out.print(line);

      proc.waitFor();

    } catch (Throwable t) {
      found = false;
      t.printStackTrace();
    }
  }
Example #24
0
  /**
   * Get Java process builder with basic command line execution based on given os nature.
   *
   * @return
   */
  private ProcessBuilder getProcessBuilder() {
    List<String> commands = new ArrayList<String>();
    if (SystemUtils.IS_OS_UNIX) {
      commands.add(BASH);
      commands.add(BASH_OPTION_C);
    } else {
      commands.add(CMD);
      commands.add(CMD_OPTION_C);
    }

    commands.add(buildCommand());

    ProcessBuilder pb = new ProcessBuilder(commands);
    pb.directory(Paths.get("").toFile().getAbsoluteFile());

    log.trace("Returning ProcessBuilder for command:" + commands);
    return pb;
  }
Example #25
0
  public void runNGramCount(String inputFile, String outputFile, int nSize) {
    File f = new File(outputFile);
    if (f.exists() && !forceRun) {
      //			System.out.println("Output file "+outputFile+" already exists. Ngram will not run");
      Logger.log("Output file " + outputFile + " already exists. Ngram will not run");
      return;
    }
    long start = System.currentTimeMillis();
    Logger.log("Running ngram on input file:" + inputFile);
    String execProcess =
        path
            + "ngram-count -order "
            + nSize
            + " -interpolate -text "
            + inputFile
            + " -lm "
            + outputFile;
    //		System.out.println(execProcess);
    Logger.log("Executing: " + execProcess);
    try {
      String[] args =
          new String[] {
            path + "ngram-count",
            "-order",
            nSize + "",
            "-interpolate",
            "-text",
            inputFile,
            "-lm",
            outputFile
          };
      ProcessBuilder pb = new ProcessBuilder(args);

      //			pb.redirectErrorStream(true);
      Process process = pb.start();
      process.waitFor();
    } catch (Exception e) {
      e.printStackTrace();
      Logger.log(e.getStackTrace().toString());
    }
    long end = System.currentTimeMillis() - start;
    Logger.log("Finished computing perplexities in " + end / 1000f + " sec");
  }
Example #26
0
  private Process openMediaFile_inLinux(MediaFile mf) {
    ProcessBuilder p;
    List<String> path = new ArrayList<String>();
    path.add("vlc");

    if (mf.isMediaType(TypeX.MEDIA_DIR)
        && mf.isDirContainsType(TypeX.VIDEO)) // open videos in queue
    {
      MediaFile[] medFold = mf.listMediaFiles();

      for (MediaFile f : medFold) {

        if (f.isMediaType(TypeX.VIDEO)) {
          path.add(f.getAbsoluteFilePath());
        }
      }
    } else if (mf.isMediaType(TypeX.VIDEO)) {
      path.add(mf.getAbsoluteFilePath());
    }

    if (mf.isMediaType(TypeX.MEDIA_DIR) && !mf.isDirContainsType(TypeX.VIDEO)) {
      System.out.println("******Can't open none video files****");
      for (MediaFile f : mf.listMediaFiles()) {

        System.out.println("" + f.getName());
      }
      return null;
    } else if (!mf.isMediaType(TypeX.MEDIA_DIR) && !mf.isMediaType(TypeX.VIDEO)) {
      System.out.println("******Can't open none video files****");
      System.out.println("" + mf.getName());
      return null;
    }

    p = new ProcessBuilder(path);

    try {

      return p.start();
    } catch (IOException e) {
      System.out.println("Runtime error : " + e);
      return null;
    }
  }
 /**
  * Requires a map of environment variables (P4USER, P4CLIENT, P4PORT, etc)
  *
  * @param environment
  */
 public CmdLineExecutor(Map<String, String> environment) {
   args = new ArrayList<String>();
   builder = new ProcessBuilder(args);
   Map<String, String> env = builder.environment();
   for (Map.Entry<String, String> entry : environment.entrySet()) {
     // if(key.equals("P4PASSWD"))
     // continue;
     // logger.warn("Settin env: " + key + " = " + environment.get(key));
     env.put(entry.getKey(), entry.getValue());
   }
 }
  /*
   * (non-Javadoc)
   *
   * @see com.tek42.perforce.process.P4Executor#exec(java.lang.String[])
   */
  public void exec(String[] args) throws PerforceException {
    this.args.clear();
    StringBuilder debug = new StringBuilder();
    for (String arg : args) {
      debug.append(arg + " ");
      this.args.add(arg);
    }
    logger.info("Executing: " + debug);
    builder.redirectErrorStream(true);
    try {
      currentProcess = builder.start();
      input = currentProcess.getInputStream();
      output = currentProcess.getOutputStream();
      reader = new BufferedReader(new InputStreamReader(currentProcess.getInputStream()));
      writer = new BufferedWriter(new OutputStreamWriter(currentProcess.getOutputStream()));

    } catch (IOException e) {
      throw new PerforceException("Failed to open connection to: " + args[0], e);
    }
  }
  public static void main(String args[]) throws InterruptedException, IOException {
    List<String> command = new ArrayList<String>();
    command.add(System.getenv("windir") + "\\system32\\" + "tree.com");
    command.add("/A");

    ProcessBuilder builder = new ProcessBuilder(command);
    Map<String, String> environ = builder.environment();
    builder.directory(new File(System.getenv("temp")));

    System.out.println("Directory : " + System.getenv("temp"));
    final Process process = builder.start();
    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;
    while ((line = br.readLine()) != null) {
      System.out.println(line);
    }
    System.out.println("Program terminated!");
  }
Example #30
0
  public static void main(String args[]) {

    //        ProcessBuilder pb = new
    // ProcessBuilder("/Users/musictechnology/Documents/Kinect/OpenNI-Bin-Dev-MacOSX-v1.5.7.10/Samples/Bin/x64-Release/Sample-NiSimpleRead");
    //        pb.directory(new
    // File("/Users/musictechnology/Documents/Kinect/OpenNI-Bin-Dev-MacOSX-v1.5.7.10/Samples/Bin/x64-Release/"));
    ProcessBuilder pb =
        new ProcessBuilder(
            "/Users/musictechnology/Documents/Kinect/NITE-Bin-Dev-MacOSX-v1.5.2.21/Samples/Bin/x64-Release/Sample-Players");
    pb.directory(
        new File(
            "/Users/musictechnology/Documents/Kinect/NITE-Bin-Dev-MacOSX-v1.5.2.21/Samples/Bin/x64-Release/"));
    try {
      Process process = pb.start();
      String line;

      BufferedReader is = new BufferedReader(new InputStreamReader(process.getInputStream()));
      //            while ((line = is.readLine()) != null) {
      //                System.out.println(line);
      //            }
      //            while (is.readLine() != null) {
      //                System.out.println(is.readLine());
      //            }
      //            System.out.flush();

      // Maybe use event listener to listen, then do something

      OutputStream output = process.getOutputStream();
      //            BufferedWriter bufferedWriter = new BufferedWriter(stderr);
      PrintWriter pw = new PrintWriter(output);
      while (true) {
        pw.flush();
        Thread.sleep(1000);
      }

    } catch (IOException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }