示例#1
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;
  }
示例#2
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);
    }
  }
 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;
 }
示例#4
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;
    }
  }
示例#5
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();
 }
  /*
   * (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);
    }
  }
  private void startProcess() throws IOException, SrvrMgrException {
    ProcessBuilder builder = new ProcessBuilder(runTimeCommand);
    this.lastCommandDate = System.currentTimeMillis();
    try {
      builder.redirectErrorStream(true);
      this.process = builder.start();
    } catch (Exception ex) {
      throw new SrvrMgrException("Can't start process " + Arrays.toString(runTimeCommand));
    }
    this.locked = false;
    this.processInput = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
    this.processOutputStream = process.getInputStream();
    this.PID = getProcessId(process);
    /*TODO: debug*/
    processLog(runTimeCommand, "Input Command");

    byte[] inputData = new byte[1024];
    String result = "";
    int numBytes;

    while ((numBytes = readInputStreamWithTimeout(processOutputStream, inputData, 1000)) > 0
        || !result.contains("srvrmgr>")) {
      if (numBytes > 0) result += new String(inputData, StandardCharsets.UTF_8);
      else {
        try {
          Thread.sleep(500);
        } catch (InterruptedException ex) {
        }
      }
      if (result.contains(("Fatal error"))) {
        this.process.destroy();
        throw new SrvrMgrException("Could not open connection to Siebel Gateway configuration");
      }
      //      System.out.println(result);
      inputData = new byte[1024];
    }
    /*TODO: debug*/
    processLog(result, "Output after process creation");
  }
  public static void main(String[] args) throws InterruptedException, IOException {
    final File INSTALLER = new File(args[0]);
    assert INSTALLER.exists();

    String directConsole = null;
    // windows specific
    if (isWindows()) {
      directConsole =
          INSTALLER.getName().contains("7.0.0")
              ? "-Dinstaller.direct.console=true"
              : "-Djline.WindowsTerminal.directConsole=false";
    }

    ProcessBuilder pb =
        new ProcessBuilder(
            buildArgs("java", directConsole, "-jar", INSTALLER.getAbsolutePath(), "-console"));
    pb.redirectErrorStream(true);

    // start process
    try {
      process = pb.start();
    } catch (IOException e) {
      System.err.println("Process failed to start.");
      System.exit(1);
    }

    // consume process input & error streams
    final InputStreamReader isr = new InputStreamReader(process.getInputStream());
    outPump = new CharPumper(isr);
    outPump.start();

    writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));

    waitFor("Please choose [0] :", "Failed to read the language dialogue.");
    sendLine("0");
    waitFor("press 1 to continue, 2 to quit, 3 to redisplay.", "Failed to read EULA");
    process.destroy();
  }
示例#9
0
  /**
   * This function is used to check if the java executable has the proper version.
   *
   * @param executable the path to the executable
   * @return {@code true} in case java meets the required specifications
   */
  private boolean isJavaExecutableWorking(@Nonnull final Path executable) {
    try {
      ProcessBuilder processBuilder = new ProcessBuilder(executable.toString(), "-version");
      processBuilder.redirectErrorStream(true);
      Process process = processBuilder.start();
      process.getOutputStream().close();

      try (BufferedReader reader =
          new BufferedReader(new InputStreamReader(process.getInputStream()))) {
        String line;
        while ((line = reader.readLine()) != null) {
          if (line.startsWith("java version")) {
            Matcher matcher = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)_(\\d+)").matcher(line);
            if (matcher.find()) {
              int mainVersion = Integer.parseInt(matcher.group(1));
              int majorVersion = Integer.parseInt(matcher.group(2));
              int minorVersion = Integer.parseInt(matcher.group(3));
              int buildNumber = Integer.parseInt(matcher.group(4));

              LOGGER.info(
                  "Matched Java version to {}.{}.{}_b{}",
                  mainVersion,
                  majorVersion,
                  minorVersion,
                  buildNumber);

              return mainVersion >= 1 && majorVersion >= 7 && buildNumber >= 21;
            }
          }
        }
      }
      process.destroy();
    } catch (IOException e) {
      LOGGER.error("Launching {} failed.", executable);
    }
    return false;
  }
示例#10
0
  public int compileJava() {
    try {
      //    create new bin directory
      boolean createBin = new File(classPath).mkdir();

      //    create new javac ProcessBuilder
      //      ProcessBuilder pb =
      //      new ProcessBuilder("javac", "-d", classPath, "./" + studentPath + "/*.java");

      ProcessBuilder pbDir = new ProcessBuilder("dir");
      //    Determine current working directory
      File srcAbsPath = new File(sourcePath);
      srcAbsPathName = srcAbsPath.getAbsolutePath();
      System.out.println("Compiler.java line 69 source path: " + sourcePath);
      System.out.println("Compiler.java line 69 source absolute path: " + srcAbsPathName);

      File cwd = pbDir.directory();
      //    debug code - to confirm correct directory
      //    TestTools.dir(cwd);
      //    NB - ProcessBuilder default is to return a null
      //    pointer for the abstract path to indicate that it
      //    is using System.Properties "user.dir", i.e., the
      //    current system working directory; hence the
      //    critical need to handle a NullPointerException.
      //    Also returns a null pointer if the directory
      //    doesn't exist.

      // all this is doing is changing the dir, can we approach this in a different way using a
      // value in our Data Object? -mh
      File nwd = TestTools.cd(cwd, studentPath);

      System.out.println("(Compiler.java line 88)new working directory: " + nwd.toString());
      String studentPathName = nwd.getAbsolutePath();
      File nwdPath = new File(studentPath);
      System.out.println("(Compiler.java line 91)new working directory path: " + studentPathName);
      //    debug code to test new working directory
      //    TestTools.dir(nwd);

      FileFilter filter = new FileFilter() {};

      String[] javaFileList = nwdPath.list(filter);
      //    set up output file
      File outputFile = new File(outputFileName);
      //    System.out.println(outputFileName);
      outputFile.delete();

      for (int k = 0; k < javaFileList.length; k++) {
        try {
          if (filter.accept(nwdPath, javaFileList[k]) == true) {
            System.out.println("COMPILER.JAVA (line 111)  Compiling: " + javaFileList[k]);

            String compilePath =
                "javac" + "-d" + classPath + ".\\" + studentPath + "\\" + javaFileList[k];
            System.out.println("Compiler.java 117 compile path: " + compilePath);
            ProcessBuilder pb =
                // new ProcessBuilder("javac ", "-d", classPath, ".\\" + studentPath + "\\" +
                // javaFileList[k]);
                new ProcessBuilder(compilePath);

            // System.out.println(pb.environment().toString());  <-- THIS IS VERY INTERESTING

            //          Create environment map and set environmental variables
            Map<String, String> env = pb.environment();
            env.clear();
            env.put("PATH", path);
            env.put("CLASSPATH", classPath);
            //          env.put("SOURCEPATH", sourcePath);
            //          env.remove("OTHERVAR");

            pb.redirectErrorStream(true);
            pb.redirectOutput(Redirect.appendTo(outputFile));

            //          start javac process
            Process p = pb.start();

            //          need other processes to wait for compilation to finish
            //          basically joins the thread to the javac process to force sequential
            //          execution - need to be careful - if any process hangs, whole run hangs
            success =
                p
                    .waitFor(); // Returns the exit value of the process. By convention, 0 indicates
                                // normal termination.
                                // http://docs.oracle.com/javase/6/docs/api/java/lang/Process.html#waitFor%28%29

            assert pb.redirectInput() == Redirect.PIPE;
            assert pb.redirectOutput().file() == outputFile;
            assert p.getInputStream().read() == -1;
            System.out.println("COMPILER.JAVA (line 138)  end of loop, success = " + success);
          }
        } catch (Exception e) {
          System.out.println(" Compiler.java FOR LOOP Compile Exception: " + javaFileList[k]);
        }
      }
    } catch (Exception e) {
      System.out.println("Compile Exception, PROBABLY DUE TO FILE PATH");
      System.out.println("source absolute path: " + srcAbsPathName);
    }

    return success;
  }
  public void run() {
    if (!new File(m_generatorPy).exists()) {
      Base.showMessage(
          "ERROR", String.format("Could not find generator python script at %s", m_generatorPy));
    }
    Sketch sketch = m_editor.getSketch();
    if (sketch.isModified()) {
      try {
        sketch.save();
      } catch (java.io.IOException ex) {
        // Base.showMessage("ERROR", "Could not save sketch before trying to generate." );
      }
    }

    // String sketchName = sketch.getName();
    // SketchCode codeObject = sketch.getCurrentCode();
    // String code = codeObject.getProgram();
    try {
      String code = m_editor.getCurrentTab().getText();
      // String code = m_editor.getText();
      int start = code.indexOf("BEGIN AUTOMATION");
      if (start != -1) {
        int end = code.indexOf("END AUTOMATION", start);
        if (end != -1) {
          String automationCode = code.substring(start + "BEGIN AUTOMATION".length(), end);
          automationCode = automationCode.replaceAll("\\*\\s+", "");
          // SketchData sketchData = new MySketchData(sketch.getMainFilePath());
          // File buildFolder = BaseNoGui.getBuildFolder(sketchData);
          File buildFolder = getBuildFolder(sketch);
          // File codeFolder = sketchData.getCodeFolder();
          File codeFolder = new File(sketch.getFolder(), "code");
          Files.createDirectories(codeFolder.toPath());
          File automationFileName = new File(buildFolder, "automation.automation");
          FileWriter writer = new FileWriter(automationFileName);
          writer.write("name automation\n");
          writer.write("import " + sketch.getMainFilePath().toString() + "\n");
          writer.write(automationCode);
          writer.close();

          try {
            ProcessBuilder processBuilder = null;
            if (m_isWindows) {
              processBuilder =
                  new ProcessBuilder(
                      m_pythonPath.getAbsolutePath(),
                      m_generatorPy,
                      "-s",
                      "--arduino",
                      automationFileName.getAbsolutePath());
            } else {
              processBuilder =
                  new ProcessBuilder(
                      m_generatorPy, "-s", "--arduino", automationFileName.getAbsolutePath());
            }
            processBuilder.directory(codeFolder);
            processBuilder.redirectErrorStream(true);
            Process process = processBuilder.start();
            inheritIO(process.getInputStream(), System.out);
            int result = process.waitFor();

            String includeLibLine = "#include \"SequantoAutomation.h\"\n";
            if (!code.contains(includeLibLine)) {
              code = includeLibLine + code;
            }

            /*
              File generatedFileName = new File(codeFolder, "automation_automation.c" );
              String includeLine = String.format("#include \"%s\"\n", generatedFileName.getAbsolutePath());
              if ( !code.contains(includeLine) )
              {
              int i = code.indexOf(includeLibLine);
              code = code.substring(0, i + includeLibLine.length()) +
              includeLine +
              code.substring ( i + includeLibLine.length(), code.length() );
              }
            */

            String includeLine = String.format("#include \"code/automation_automation.h\"\n");
            if (!code.contains(includeLine)) {
              int i = code.indexOf(includeLibLine);
              code =
                  code.substring(0, i + includeLibLine.length())
                      + includeLine
                      + code.substring(i + includeLibLine.length(), code.length());
            }

            String includeCodeLine = String.format("\n#include \"code/automation_automation.c\"\n");
            if (!code.contains(includeCodeLine)) {
              code = code + includeCodeLine;
            }

            if (m_editor.getCurrentTab().getText() != code) {
              // System.out.println ( "Setting code to" );
              // System.out.println ( code );
              // System.out.println ( "Current text was" );
              // System.out.println ( m_editor.getText() );
              m_editor.getCurrentTab().setText(code);
            }

            if (result == 0) {
              System.out.println("Sequanto automation code generated successfully!");
            } else {
              System.out.println("ERROR!!!");
            }
          } catch (Exception ex) {
            Base.showMessage("ERROR", String.format("Could not start generator script: %s", ex));
          }
        } else {
          Base.showMessage("ERROR", "Can not find END AUTOMATION.");
        }
      } else {
        Base.showMessage("ERROR", "Can not find BEGIN AUTOMATION.");
      }
    } catch (java.io.IOException ex) {
      Base.showMessage("ERROR", String.format("IO Error: %s.", ex));
    }
  }