Esempio n. 1
0
  /**
   * Create a complete command line, including path and arguments.
   *
   * @return Configured command line, ready for execution
   */
  private CommandLine createCommandLine() {
    final String javaPath = getJavaPath();

    final String gsHome = Environment.getHomeDirectory();
    final String[] commandParams = {
      "-Dcom.gs.home=" + gsHome,
      "-Dorg.hyperic.sigar.path=" + gsHome + "/lib/platform/sigar",
      "-Dcom.gs.usm.RecipeShutdownTimeout=" + timeout,
      IntegratedProcessingUnitContainer.class.getName(),
      "-cluster",
      "id=1",
      "total_members=1"
    };
    final CommandLine cmdLine = new CommandLine(javaPath);

    for (final String param : commandParams) {
      cmdLine.addArgument(param);
    }
    if (this.serviceFileName != null) {
      cmdLine.addArgument("-properties");
      cmdLine.addArgument(
          "embed://"
              + CloudifyConstants.CONTEXT_PROPERTY_SERVICE_FILE_NAME
              + "="
              + this.serviceFileName);
    }

    // -Dcom.gs.usm.RecipeShutdownTimeout=10

    return cmdLine;
  }
  /**
   * Executes the ffmpeg process with the previous given arguments.
   *
   * @return The standard output of the child process.
   * @throws IOException If the process call fails.
   */
  public String execute() throws IOException {
    CommandLine cmdLine = new CommandLine(ffmpegExecutablePath);

    int fileNumber = 0;
    Map<String, File> map = new HashMap<String, File>();
    for (int i = 0; i < args.size(); i++) {
      final String arg = args.get(i);
      final Boolean isFile = argIsFile.get(i);
      if (isFile) {
        String key = "file" + fileNumber;
        map.put(key, new File(arg));
        cmdLine.addArgument("${" + key + "}", false);
        fileNumber++;
      } else {
        cmdLine.addArgument(arg);
      }
    }
    cmdLine.setSubstitutionMap(map);
    LOG.fine("Execute: " + cmdLine);
    DefaultExecutor executor = new DefaultExecutor();
    // 5minutes wait
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000 * 5);
    executor.setWatchdog(watchdog);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(out));
    int[] exitValues = {0, 1};
    executor.setExitValues(exitValues);
    executor.execute(cmdLine);
    return out.toString();
  }
  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;
    }
  }
Esempio n. 4
0
 private CommandLine getWindowsKillCommand(int pid) {
   CommandLine command = new CommandLine("taskkill");
   command.addArgument("/F");
   command.addArgument("/PID");
   command.addArgument("" + pid);
   command.addArgument("/T");
   return command;
 }
Esempio n. 5
0
  private CommandLine makeCommandLine(String program, List<String> args)
      throws NotAuthorizedException, IOException {
    String path = validateProgram(program);
    CommandLine cmd = new CommandLine(path);
    if (args != null) for (String arg : args) cmd.addArgument(arg, false);

    return cmd;
  }
Esempio n. 6
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;
  }
  /** @throws MojoExecutionException if anything unexpected happens. */
  public void execute() throws MojoExecutionException {
    if (!workingDirectory.exists()) {
      workingDirectory.mkdirs();
    }

    CommandLine commandLine = new CommandLine(executable);
    Executor exec = new DefaultExecutor();
    exec.setWorkingDirectory(workingDirectory);

    Map env = new HashMap();
    try {
      Map systemEnvVars = EnvironmentUtils.getProcEnvironment();
      env.putAll(systemEnvVars);
    } catch (IOException e) {
      getLog().error("Could not assign default system enviroment variables.", e);
    }
    env.put("NODE_PATH", new File(workingDirectory, "node_modules").getAbsolutePath());
    env.put("XUNIT_FILE", outputFile.getAbsolutePath());

    List commandArguments = new ArrayList();
    commandArguments.add("test");

    String[] args = new String[commandArguments.size()];
    for (int i = 0; i < commandArguments.size(); i++) {
      args[i] = (String) commandArguments.get(i);
    }

    commandLine.addArguments(args, false);

    OutputStream stdout = System.out;
    OutputStream stderr = System.err;

    try {
      outputFile.getParentFile().mkdirs();
      getLog()
          .debug(
              "Executing command line "
                  + commandLine
                  + " in directory "
                  + workingDirectory.getAbsolutePath());
      exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in));

      int resultCode = exec.execute(commandLine, env);

      if (0 != resultCode) {
        throw new MojoExecutionException(
            "Result of " + commandLine + " execution is: '" + resultCode + "'.");
      }
    } catch (ExecuteException e) {
      throw new MojoExecutionException(EXECUTION_FAILED, e);

    } catch (IOException e) {
      throw new MojoExecutionException(EXECUTION_FAILED, e);
    }
  }
Esempio n. 8
0
 /**
  * Generates a CommandLine to execute a program.
  *
  * @param mode
  * @param executable
  * @return
  */
 public static CommandLine getCommandLine(ExecutionMode mode, String executable) {
   CommandLine command = null;
   if (ExecutionMode.INTERACTIVE.equals(mode) && SystemUtils.IS_OS_WINDOWS) {
     command = new CommandLine("cmd");
     command.addArgument("/c");
     command.addArgument("start");
     command.addArgument(executable);
   } else {
     command = new CommandLine(executable);
   }
   return command;
 }
Esempio n. 9
0
 public static void run(
     InvocationOutputHandler outputHandler,
     Map<String, String> envVarsForApp,
     CommandLine command,
     File projectRoot,
     long timeout)
     throws ProjectCannotStartException {
   long startTime = logStartInfo(command, projectRoot);
   ExecuteWatchdog watchDog = new ExecuteWatchdog(timeout);
   Executor executor = createExecutor(outputHandler, command, projectRoot, watchDog);
   try {
     int exitValue = executor.execute(command, envVarsForApp);
     if (executor.isFailure(exitValue)) {
       String message =
           watchDog.killedProcess()
               ? "Timed out waiting for " + command
               : "Exit code " + exitValue + " returned from " + command;
       throw new ProjectCannotStartException(message);
     }
   } catch (Exception e) {
     String message =
         "Error running: "
             + dirPath(projectRoot)
             + "> "
             + StringUtils.join(command.toStrings(), " ");
     outputHandler.consumeLine(message);
     outputHandler.consumeLine(e.toString());
     throw new ProjectCannotStartException(message, e);
   }
   logEndTime(command, startTime);
 }
Esempio n. 10
0
  public static String sync_getVerificationOutput(
      String lolaBinPath,
      String modelToVerify,
      String propertyToVerify,
      boolean useCoverabilitySearch,
      final int timeoutInSeconds)
      throws Exception {

    int cores = Runtime.getRuntime().availableProcessors();
    String filePath =
        System.getProperty("java.io.tmpdir") + "/" + java.util.UUID.randomUUID() + ".lola";
    IOUtils.writeFile(modelToVerify.getBytes(), filePath, false);
    // IOUtils.writeFile(propertyToVerify.getBytes(), filePath+".ctl", false);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CommandLine cmdLine = new CommandLine(lolaBinPath);

    cmdLine.addArgument("--nolog");

    // cmdLine.addArgument("--formula="+filePath+".ctl", false);
    cmdLine.addArgument("--formula=" + propertyToVerify, false);
    cmdLine.addArgument("--threads=" + cores);
    if (useCoverabilitySearch) cmdLine.addArgument("--search=cover");
    cmdLine.addArgument("-p");
    // cmdLine.addArgument("--path=\""+filePath+".out\"", false);
    // cmdLine.addArgument("--state=\""+filePath+".out\"", false);
    cmdLine.addArgument(filePath, false);

    DefaultExecutor exec = new DefaultExecutor();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(1000 * timeoutInSeconds);

    exec.setWatchdog(watchdog);
    exec.setStreamHandler(streamHandler);
    exec.setExitValues(new int[] {0, 1, 2, 139, 35584});
    int exitVal = exec.execute(cmdLine);

    String output = outputStream.toString();

    if (watchdog.killedProcess())
      throw new Exception(
          "ERROR: Timeout occurred. LOLA has reached the execution time limit of "
              + timeoutInSeconds
              + " seconds, so it has been aborted.\nPartial Output:\n"
              + output);

    if (exitVal != 0 || output.equals("") || output.contains("aborting [#"))
      throw new Exception(
          "ERROR: LOLA internal error\nExit code:"
              + exitVal
              + "\nExec: "
              + cmdLine.toString()
              + "\nOutput:\n"
              + output);
    new File(filePath).delete();
    return output;
  }
  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;
  }
Esempio n. 12
0
 private static void logEndTime(CommandLine command, long startTime) {
   log.info(
       "Completed "
           + command.getExecutable()
           + " in "
           + (System.currentTimeMillis() - startTime)
           + "ms");
 }
  @Override
  public void init() throws Exception {

    // pdf2json settings
    for (final Map.Entry<String, String> entry : System.getenv().entrySet()) {
      if ("path".equals(entry.getKey().toLowerCase())) {
        try {
          CommandLine commandLine = new CommandLine("pdf2json");
          commandLine.addArgument("-v");
          ExternalExecution.exec(
              commandLine, Config.init().successfulExitStatusValueIs(1).doNotDisplayErrorTrace());
          isActivated = true;
        } catch (final Exception e) {
          // pdf2json is not installed
          System.err.println("pdf2json is not installed");
        }
      }
    }
  }
  public int retrievePageCount(File source) {

    File target =
        new File(
            System.getProperty("java.io.tmpdir"),
            FilenameUtils.removeExtension(source.getName()) + ".pdf");

    Map<String, Object> args = newHashMap();
    args.put("source", source);
    args.put("targetDir", target.getParentFile());

    CommandLine cmd = new CommandLine("loffice");
    cmd.addArgument("--headless");
    cmd.addArgument("--convert-to");
    cmd.addArgument("pdf");
    cmd.addArgument("--outdir");
    cmd.addArgument("${targetDir}");
    cmd.addArgument("${source}");
    cmd.setSubstitutionMap(args);

    try {
      DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

      ExecuteWatchdog watchdog = new ExecuteWatchdog(10L * 1000L);
      executor.setWatchdog(watchdog);
      logger.trace("About to execute command {}", cmd.toString());
      executor.execute(cmd, resultHandler);

      resultHandler.waitFor();
      final int exitValue = resultHandler.getExitValue();

      if (exitValue != 0) {
        logger.error(
            "Unable to convert Microsoft Word file {} to PDF. Exit code = {}",
            source.getAbsolutePath(),
            exitValue);
        return -1;
      }
      final int pageCount = pdfDocumentInspector.retrievePageCount(target);
      deleteFileIfNeeded(target);
      return pageCount;

    } catch (IOException | InterruptedException e) {
      logger.error("Unable to create a PDF from {}", source.getAbsolutePath(), e);
      deleteFileIfNeeded(target);
      return -1;
    }
  }
Esempio n. 15
0
  /**
   * @param printJobTimeout the printJobTimeout (ms) before the watchdog terminates the print
   *     process
   * @param printInBackground printing done in the background or blocking
   * @param streamHandler
   * @return a print result handler (implementing a future)
   * @throws IOException the test failed
   */
  public static PrintResultHandler executeProgram(
      CommandLine commandLine,
      String workingDirectory,
      long printJobTimeout,
      boolean printInBackground,
      int successExitValue,
      ExecuteStreamHandler streamHandler)
      throws IOException {
    ExecuteWatchdog watchdog = null;
    PrintResultHandler resultHandler;

    // Create the executor and consider the successExitValue as success
    Executor executor = new DefaultExecutor();
    executor.setExitValue(successExitValue);

    if (StringHelper.isNotEmpty(workingDirectory)) {
      executor.setWorkingDirectory(new File(workingDirectory));
    }

    // Redirect streams if needed
    if (streamHandler != null) {
      executor.setStreamHandler(streamHandler);
    }

    // Create a watchdog if requested
    if (printJobTimeout > 0) {
      watchdog = new ExecuteWatchdog(printJobTimeout);
      executor.setWatchdog(watchdog);
    }

    // Pass a "ExecuteResultHandler" when doing background printing
    if (printInBackground) {
      log.debug(String.format("Executing non-blocking process %s", commandLine.toString()));
      resultHandler = new PrintResultHandler(watchdog);
      executor.execute(commandLine, resultHandler);
    } else {
      log.debug(String.format("Executing blocking process %s", commandLine.toString()));
      successExitValue = executor.execute(commandLine);
      resultHandler = new PrintResultHandler(successExitValue);
    }

    return resultHandler;
  }
Esempio n. 16
0
 /**
  * Executes a java command from within
  *
  * @param session
  * @param toolchainManager
  * @param mode
  * @param mainClass
  * @param vmargs
  * @param mainArgs
  * @throws MojoExecutionException
  */
 @SuppressWarnings("rawtypes")
 public static void executeJava(
     MavenSession session,
     ToolchainManager toolchainManager,
     ExecutionMode mode,
     String mainClass,
     String[] vmargs,
     String[] mainArgs)
     throws MojoExecutionException {
   String javaExecutable = getJavaExecutable(session, toolchainManager);
   CommandLine command = getCommandLine(mode, javaExecutable);
   if (vmargs != null) {
     command.addArguments(vmargs, false);
   }
   command.addArgument(mainClass);
   if (mainArgs != null) {
     command.addArguments(mainArgs, false);
   }
   execute(session, command, null, new HashMap());
 }
Esempio n. 17
0
  protected org.apache.commons.exec.CommandLine getCommandLine(
      boolean addShExt, String scriptName, String... args) {
    org.apache.commons.exec.CommandLine result;

    if (isWindows()) {
      result = new org.apache.commons.exec.CommandLine("cmd.exe");
      result.addArgument("/C");
      result.addArgument(scriptName.replace('/', '\\') + ".bat");
    } else {
      result =
          new org.apache.commons.exec.CommandLine(
              "./" + (addShExt ? scriptName + ".sh" : scriptName));
    }

    for (String arg : args) {
      result.addArgument(arg);
    }

    return result;
  }
Esempio n. 18
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;
  }
  public String toString() {
    CommandLine cmdLine = new CommandLine(ffmpegExecutablePath);

    int fileNumber = 0;
    Map<String, File> map = new HashMap<String, File>();
    for (int i = 0; i < args.size(); i++) {
      final String arg = args.get(i);
      final Boolean isFile = argIsFile.get(i);
      if (isFile) {
        String key = "file" + fileNumber;
        map.put(key, new File(arg));
        cmdLine.addArgument("${" + key + "}", false);
        fileNumber++;
      } else {
        cmdLine.addArgument(arg);
      }
    }
    cmdLine.setSubstitutionMap(map);
    return cmdLine.toString();
  }
Esempio n. 20
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();
    }
  }
Esempio n. 21
0
  public int execute(String[] args, @Nullable Path workingDir) throws IOException {
    if (!Files.isExecutable(file)) {
      Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
      perms.add(PosixFilePermission.OWNER_READ);
      perms.add(PosixFilePermission.OWNER_EXECUTE);
      Files.setPosixFilePermissions(file, perms);
    }

    ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
    CommandLine cmd = new CommandLine(file.toFile());
    cmd.addArguments(args);
    DefaultExecutor exec = new DefaultExecutor();
    exec.setWatchdog(watchdog);
    exec.setStreamHandler(createStreamHandler());
    exec.setExitValues(null);
    if (workingDir != null) {
      exec.setWorkingDirectory(workingDir.toFile());
    }
    in.close();
    LOG.info("Executing: {}", cmd.toString());
    return exec.execute(cmd);
  }
Esempio n. 22
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));
          }
        });
  }
  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()));
    }
  }
 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");
 }
Esempio n. 25
0
 private static Executor createExecutor(
     InvocationOutputHandler consoleLogHandler,
     CommandLine command,
     File projectRoot,
     ExecuteWatchdog watchDog) {
   Executor executor = new DefaultExecutor();
   executor.setWorkingDirectory(projectRoot);
   executor.setWatchdog(watchDog);
   executor.setStreamHandler(
       new PumpStreamHandler(new WriterOutputStream(new WriterToOutputBridge(consoleLogHandler))));
   consoleLogHandler.consumeLine(
       dirPath(executor.getWorkingDirectory())
           + "> "
           + String.join(" ", command.toStrings())
           + "\n");
   return executor;
 }
Esempio n. 26
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;
  }
Esempio n. 28
0
  /**
   * Create user on the system. Synchronized to prevent multiple threads from trying to create user
   * at the same time.
   *
   * @param user user id
   * @param group group id
   * @throws GenieException If there is any problem.
   */
  protected synchronized void createUser(final String user, final String group)
      throws GenieException {

    // First check if user already exists
    final CommandLine idCheckCommandLine =
        new CommandLine("id").addArgument("-u").addArgument(user);

    try {
      this.executor.execute(idCheckCommandLine);
      log.debug("User already exists");
    } catch (final IOException ioe) {
      log.debug("User does not exist. Creating it now.");

      // Determine if the group is valid by checking that its not null and not same as user.
      final boolean isGroupValid = StringUtils.isNotBlank(group) && !group.equals(user);

      // Create the group for the user if its not the same as the user.
      if (isGroupValid) {
        log.debug("Group and User are different so creating group now.");
        final CommandLine groupCreateCommandLine =
            new CommandLine("sudo").addArgument("groupadd").addArgument(group);

        // We create the group and ignore the error as it will fail if group already exists.
        // If the failure is due to some other reason, then user creation will fail and we catch
        // that.
        try {
          log.debug(
              "Running command to create group:  [" + groupCreateCommandLine.toString() + "]");
          this.executor.execute(groupCreateCommandLine);
        } catch (IOException ioexception) {
          log.debug("Group creation threw an error as it might already exist");
        }
      }

      final CommandLine userCreateCommandLine =
          new CommandLine("sudo").addArgument("useradd").addArgument(user);
      if (isGroupValid) {
        userCreateCommandLine.addArgument("-G").addArgument(group);
      }
      userCreateCommandLine.addArgument("-M");

      try {
        log.debug("Running command to create user: [" + userCreateCommandLine.toString() + "]");
        this.executor.execute(userCreateCommandLine);
      } catch (IOException ioexception) {
        throw new GenieServerException(
            "Could not create user " + user + " with exception " + ioexception);
      }
    }
  }
  /** @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);
      }
    }
  }
Esempio n. 30
0
  /** For console commands on Windows only */
  protected org.apache.commons.exec.CommandLine getConsoleCommandLine(
      String scriptName, String... args) {
    org.apache.commons.exec.CommandLine result;

    result = new org.apache.commons.exec.CommandLine("cmd.exe");
    result.addArgument("/C");
    result.addArgument("start");
    result.addArgument("/I");
    result.addArgument(scriptName.replace('/', '\\') + ".bat");

    for (String arg : args) {
      result.addArgument(arg);
    }

    return result;
  }