private boolean repoExists(File targetDir) throws Exception {
    validateExecutableInstance(EXECUTABLE);

    CommandLine command = CommandLine.parse(EXECUTABLE);

    command.addArgument("status");

    CommandResults commandResults;
    try {
      commandResults = commandLineExecutor.executeCommandForOutput(log, command, targetDir);
    } catch (Exception e) {
      log.error("Failure executing SVN Command", e);
      commandResults = null;
    }

    if (commandResults != null && commandResults.getStatus() == 0) {

      // warning message of form "svn: warning: W155007: 'C:\SVNFiles' is
      // not a working copy" only
      // printed when repository is not checked out to directory
      if (commandResults.getOutput().trim().contains("warning")) {
        log.info("repository does not exist in directory: " + targetDir.getAbsolutePath());
        return false;
      }

      log.info("repository exists in directory: " + targetDir.getAbsolutePath());

      return true;
    } else {
      log.info("repository does not exist in directory: " + targetDir.getAbsolutePath());
      return false;
    }
  }
  public static ExecuteResult executeCmd(String cmd, String tempShellFilePath) {
    ExecuteResult result = new ExecuteResult();
    PrintWriter out = null;
    int exitValue = -1;
    File shellFile =
        new File(
            tempShellFilePath); // 将这个命令写入shell,然后执行sh temp.sh,这样就可以避免不能执行cd /home/mac && python
    // test.py的问题了
    boolean fileChanged = true;
    ByteArrayOutputStream stdout = null;
    try {
      if (shellFile.exists()) {
        String content = FileUtils.readFileToString(shellFile, charCode);
        if (cmd.equals(content)) {
          fileChanged = false;
        }
      }
      if (fileChanged) {
        out =
            new PrintWriter(
                new OutputStreamWriter(new FileOutputStream(tempShellFilePath), charCode));
        out.write(cmd);
        out.flush();
        out.close();
      }

      CommandLine commandLine = CommandLine.parse("sh " + tempShellFilePath); // 执行那个temp的shell文件
      DefaultExecutor executor = new DefaultExecutor();
      // add return string ,stdout
      stdout = new ByteArrayOutputStream(); // 先放入ByteArrayOutputStream内部的toByteArray()方法返回的byte[]中
      ExecuteStreamHandler stream =
          new PumpStreamHandler(stdout, stdout); // 这样就把标准输出和标准错误输出都定向到stream里了,以供内存里返回给远程
      executor.setStreamHandler(stream);
      result.setOriginalCmd(cmd);
      result.setRealReplacedCmd(ReplaceRealCmdUtils.replaceCmdFromOriginalToReal(cmd));
      result.setStartTime(new Date());
      exitValue = executor.execute(commandLine); // 得到运行返回"结果码",0 -- 成功, 其他 -- 失败s
    } catch (Exception e) {
      e.printStackTrace();
      // System.out.println("GOD,ERROR!");
    } finally {
      result.setReturnString(stdout.toString()); // 这一句话就将 运行后的返回结果字符串放入了result的ReturnString里
      result.setExitCode(exitValue); //
      result.setSuccess(exitValue == ParamCommons.SUCCESS_EXIT_CODE ? true : false);
      result.setEndTime(new Date());
      result.setExecuteTempFilePath(tempShellFilePath);
      if (null != stdout) {
        try {
          stdout.close();

        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      ;
    }
    return result;
  }
示例#3
0
  /**
   * Executes <code>commandLine</code>. Sometimes (especially observed on MacOS) the commandLine
   * isn't executed properly. In that cases another exec-method is to be used. To accomplish this
   * please use the special delimiter '<code>@@</code>'. If <code>commandLine</code> contains this
   * delimiter it is split into a String[] array and the special exec-method is used.
   *
   * <p>A possible {@link IOException} gets logged but no further processing is done.
   *
   * @param commandLine the command line to execute
   * @param timeout timeout for execution in milliseconds
   * @return response data from executed command line
   */
  public static String executeCommandLineAndWaitResponse(String commandLine, int timeout) {
    String retval = null;

    CommandLine cmdLine = null;

    if (commandLine.contains(CMD_LINE_DELIMITER)) {
      String[] cmdArray = commandLine.split(CMD_LINE_DELIMITER);
      cmdLine = new CommandLine(cmdArray[0]);

      for (int i = 1; i < cmdArray.length; i++) {
        cmdLine.addArgument(cmdArray[i], false);
      }
    } else {
      cmdLine = CommandLine.parse(commandLine);
    }

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    Executor executor = new DefaultExecutor();

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(stdout);

    executor.setExitValue(1);
    executor.setStreamHandler(streamHandler);
    executor.setWatchdog(watchdog);

    try {
      executor.execute(cmdLine, resultHandler);
      logger.debug("executed commandLine '{}'", commandLine);
    } catch (ExecuteException e) {
      logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    } catch (IOException e) {
      logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    }

    // some time later the result handler callback was invoked so we
    // can safely request the exit code
    try {
      resultHandler.waitFor();
      int exitCode = resultHandler.getExitValue();
      retval = StringUtils.chomp(stdout.toString());
      if (resultHandler.getException() != null) {
        logger.warn(resultHandler.getException().getMessage());
      } else {
        logger.debug("exit code '{}', result '{}'", exitCode, retval);
      }

    } catch (InterruptedException e) {
      logger.error("Timeout occured when executing commandLine '" + commandLine + "'", e);
    }

    return retval;
  }
示例#4
0
  public void startProcess(final String cmd) throws IOException {
    final DefaultExecutor pe = new DefaultExecutor();
    processExecutor = pe;
    pe.setWatchdog(new ExecuteWatchdog(60000));

    processExecutor.setStreamHandler(
        new ExecuteStreamHandler() {

          private final Set<StreamLogger> loggers = new HashSet<StreamLogger>();

          public void stop() throws IOException {}

          public void start() throws IOException {}

          public void setProcessOutputStream(final InputStream is) throws IOException {
            loggers.add(
                new StreamLogger(
                    is,
                    LoggerFactory.getLogger(
                        FastCGIHandler.class.getName() + ".externalprocess.stdout")));
          }

          public void setProcessInputStream(final OutputStream os) throws IOException {}

          public void setProcessErrorStream(final InputStream is) throws IOException {
            loggers.add(
                new StreamLogger(
                    is,
                    LoggerFactory.getLogger(
                        FastCGIHandler.class.getName() + ".externalprocess.stderr")));
          }
        });

    getLog().info("Starting external process : " + cmd);
    pe.execute(
        CommandLine.parse(cmd),
        new DefaultExecuteResultHandler() {
          @Override
          public void onProcessFailed(final ExecuteException e) {
            super.onProcessFailed(e);
            getLog().error("while running process", e);
          }

          @Override
          public void onProcessComplete(final int exitValue) {
            getLog()
                .info(String.format("external process exited with code %s : %s", exitValue, cmd));
          }
        });
  }
 private static boolean checkLattEPresence() {
   final String DIRNAME = System.getProperty("java.io.tmpdir");
   String result = "";
   try {
     ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
     DefaultExecutor executor = new DefaultExecutor();
     executor.setStreamHandler(new PumpStreamHandler(outputStream));
     executor.setWorkingDirectory(new File(DIRNAME));
     executor.execute(CommandLine.parse(EntireSuite.LATTE_PATH));
     result = outputStream.toString();
   } catch (IOException e) {
     return false;
   }
   return result.startsWith("This is LattE integrale");
 }
示例#6
0
  @Override
  public String preListAllCandidateDevices() {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Executor executor = new CollectStdOutExecutor(baos);

    try {
      String listComPorts =
          new File(System.getProperty("user.dir"), "hardware/tools/listComPorts.exe")
              .getCanonicalPath();

      CommandLine toDevicePath = CommandLine.parse(listComPorts);
      executor.execute(toDevicePath);
      return new String(baos.toByteArray());
    } catch (Throwable e) {
      return super.preListAllCandidateDevices();
    }
  }
  /**
   * Runs file with -V argument and matches the output against OUTPUT_PATTERN.
   *
   * @param from executable to be run with -V command line argument
   * @return Parameters parsed out from process output
   * @throws PlatformDependentTools.ThisIsNotNginxExecutableException if file could not be run, or
   *     output would not match against expected pattern
   */
  public static NginxCompileParameters extract(VirtualFile from)
      throws PlatformDependentTools.ThisIsNotNginxExecutableException {

    NginxCompileParameters result = new NginxCompileParameters();

    Executor executor = new DefaultExecutor();
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    try {
      executor.setStreamHandler(new PumpStreamHandler(os, os));
      executor.execute(CommandLine.parse(from.getPath() + " -V"));
    } catch (IOException e) {
      throw new PlatformDependentTools.ThisIsNotNginxExecutableException(e);
    }

    String output = os.toString();
    Matcher versionMatcher = Pattern.compile("nginx version: nginx/([\\d\\.]+)").matcher(output);
    Matcher configureArgumentsMatcher =
        Pattern.compile("configure arguments: (.*)").matcher(output);

    if (versionMatcher.find() && configureArgumentsMatcher.find()) {

      String version = versionMatcher.group(1);
      String params = configureArgumentsMatcher.group(1);

      result.setVersion(version);

      Iterable<String> namevalues = StringUtil.split(params, " ");
      for (String namevalue : namevalues) {
        int eqPosition = namevalue.indexOf('=');
        if (eqPosition == -1) {
          handleFlag(result, namevalue);
        } else {
          handleNameValue(
              result, namevalue.substring(0, eqPosition), namevalue.substring(eqPosition + 1));
        }
      }

    } else {
      throw new PlatformDependentTools.ThisIsNotNginxExecutableException(
          NginxBundle.message("run.configuration.outputwontmatch"));
    }

    return result;
  }
  /** @throws Exception if any of the commands fail. */
  private void runSystemCommands(List<String> commands) throws Exception {
    for (String command : commands) {
      log.info("[Running command]$ " + command);
      try {
        DefaultExecutor executor = new DefaultExecutor();
        executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
        CommandLine cmdLine = CommandLine.parse(command);
        int exitValue = executor.execute(cmdLine);

        if (exitValue != 0) {
          throw new Exception("Command returned non-zero exit value: " + exitValue);
        }
        log.info("    Completed with exit value: " + exitValue);
      } catch (java.io.IOException e) {
        throw new Exception("Failed to run command. " + e.getMessage(), e);
      } catch (InterruptedException e) {
        throw new Exception("Interrupted while running command. " + e.getMessage(), e);
      }
    }
  }
示例#9
0
  public String getDockerHostIpAddress(Map<String, String> environment) {
    String ipAddress = LOCALHOST; // Default of localhost
    String dockerMachineName = getDockerMachineName(environment);

    if (!dockerMachineName.isEmpty()) {
      LOG.debug("Docker machine name = " + dockerMachineName);
      CommandLine commandline = CommandLine.parse(DOCKER_MACHINE_IP);
      commandline.addArgument(dockerMachineName);
      LOG.debug("Running exec: " + commandline.toString());
      try {
        ipAddress = StringUtils.strip(runCommand(commandline));
      } catch (IOException e) {
        LOG.error("Unable to run exec command to find ip address.", e);
      }
    } else {
      ipAddress = getDocker0AdapterIPAddress();
    }
    LOG.debug("Returned IP address: " + ipAddress);
    return ipAddress;
  }
  @Override
  public int sync() {

    int exitStatus = -1;

    try {
      File targetDir = new File(getFinalSourceDirectory());

      CommandLine command = CommandLine.parse(EXECUTABLE);

      if (!repoExists(targetDir)) {
        command.addArgument("co");
        command.addArgument(repositoryURL);
      } else {
        command.addArgument("up");
      }

      // now add destination
      // command.addArgument(targetDir.getAbsolutePath());
      if (user != null && !user.isEmpty()) {
        command.addArgument("--username");
        command.addArgument(user);
        if (!password.isEmpty()) {
          command.addArgument("--password");
          command.addArgument(password);
        }
      }

      command.addArgument("--non-interactive");

      for (String svnFlag : svnFlagsList) {
        command.addArgument(svnFlag);
      }

      exitStatus = commandLineExecutor.executeCommand(log, command, targetDir);

    } catch (Exception e) {
      log.error("Unable to perform sync: " + e.getMessage());
    }
    return exitStatus;
  }
示例#11
0
  public void runScript(String command) {
    sCommandString = command;
    CommandLine oCmdLine = CommandLine.parse(sCommandString);

    oCmdLine.addArgument("sanga.txt");

    DefaultExecutor oDefaultExecutor = new DefaultExecutor();
    // oDefaultExecutor.setWorkingDirectory(new File(command.getWorkingDir()).getAbsoluteFile());
    // oDefaultExecutor.setExitValue(1);
    try {
      oDefaultExecutor.setWorkingDirectory(new File("/Users/212433329/bharshell"));
      iExitValue = oDefaultExecutor.execute(oCmdLine);
    } catch (ExecuteException e) {
      // TODO Auto-generated catch block
      System.err.println("Execution failed.");
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      System.err.println("permission denied.");
      e.printStackTrace();
    }
  }
示例#12
0
  private void execute(String command, Object... args) {

    String fullCommand = String.format(command, args) + " --config-dir=" + ccmDir;
    try {
      logger.debug("Executing: " + fullCommand);
      CommandLine cli = CommandLine.parse(fullCommand);
      Executor executor = new DefaultExecutor();

      LogOutputStream outStream =
          new LogOutputStream() {
            @Override
            protected void processLine(String line, int logLevel) {
              logger.debug("ccmout> " + line);
            }
          };
      LogOutputStream errStream =
          new LogOutputStream() {
            @Override
            protected void processLine(String line, int logLevel) {
              logger.error("ccmerr> " + line);
            }
          };

      ExecuteStreamHandler streamHandler = new PumpStreamHandler(outStream, errStream);
      executor.setStreamHandler(streamHandler);

      int retValue = executor.execute(cli, ENVIRONMENT_MAP);
      if (retValue != 0) {
        logger.error(
            "Non-zero exit code ({}) returned from executing ccm command: {}",
            retValue,
            fullCommand);
        throw new RuntimeException();
      }
    } catch (IOException e) {
      throw new RuntimeException(String.format("The command %s failed to execute", fullCommand), e);
    }
  }
示例#13
0
  public void mergeImages() throws IOException {

    File snapshotFolder = new File(USER_HOME + SNAPSHOT_IMAGE_PATH);
    File[] snapshotImages = snapshotFolder.listFiles();

    for (File file : snapshotImages) {
      System.out.println("file: " + file.getName());
    }

    if (snapshotImages.length == 1) {
      FileUtils.copyFile(
          snapshotImages[0], new File(USER_HOME + MERGED_IMAGE_PATH + "/merged-image.png"));
    } else {

      String line =
          "python "
              + USER_HOME
              + "/Code/python-script/merge_images.py "
              + USER_HOME
              + SNAPSHOT_IMAGE_PATH
              + "/"
              + snapshotImages[0].getName()
              + " "
              + USER_HOME
              + SNAPSHOT_IMAGE_PATH
              + "/"
              + snapshotImages[1].getName()
              + " "
              + USER_HOME
              + MERGED_IMAGE_PATH
              + "/merged-image.png";
      // String line = "AcroRd32.exe /p /h " + file.getAbsolutePath();
      CommandLine cmdLine = CommandLine.parse(line);
      DefaultExecutor executor = new DefaultExecutor();
      executor.setExitValue(1);
      int exitValue = executor.execute(cmdLine);
    }
  }
  public static CommandExecutorResult execute(String commandString, int expectedExitValue)
      throws Exception {
    ByteArrayOutputStream error = new ByteArrayOutputStream();
    ByteArrayOutputStream stout = new ByteArrayOutputStream();
    CommandLine cmd = CommandLine.parse(commandString);
    try {
      DefaultExecutor executor = new DefaultExecutor();
      executor.setExitValue(expectedExitValue);
      executor.setStreamHandler(new PumpStreamHandler(stout, error));
      // if exit value != expectedExitValue => Exception
      int exitValue = executor.execute(cmd);
      return new CommandExecutorResult(exitValue, stout.toString(), error.toString());

    } catch (Exception e) {
      int exitValue = -1;
      if (e instanceof ExecuteException) {
        exitValue = ((ExecuteException) e).getExitValue();
      }
      throw new CommandExecutorException(
          "error in command " + cmd.toString(),
          new CommandExecutorResult(exitValue, stout.toString(), error.toString()));
    }
  }