Example #1
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;
  }
  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;
    }
  }
Example #3
0
 public void onProcessFailed(ExecuteException ex) {
   super.onProcessFailed(ex);
   if ((watchdog != null) && watchdog.killedProcess()) {
     log.debug("The process timed out");
   } else {
     log.debug("The process failed to do", ex);
   }
 }
 public void onProcessFailed(ExecuteException e) {
   super.onProcessFailed(e);
   if (watchdog != null && watchdog.killedProcess())
     System.err.println("[resultHandler] The Syntren launcher process timed out");
   else
     System.err.println(
         "[resultHandler] The Syntren laucher process failed to do: " + e.getMessage());
 }
Example #5
0
  public static Killer startDaemon(
      InvocationOutputHandler buildLogHandler,
      InvocationOutputHandler consoleLogHandler,
      Map<String, String> envVarsForApp,
      CommandLine command,
      File projectRoot,
      Waiter startupWaiter) {
    long startTime = logStartInfo(command, projectRoot);
    Killer watchDog = new Killer(ExecuteWatchdog.INFINITE_TIMEOUT);
    Executor executor = createExecutor(consoleLogHandler, command, projectRoot, watchDog);

    try {
      DefaultExecuteResultHandler handler = new DefaultExecuteResultHandler();
      executor.execute(command, envVarsForApp, handler);

      startupWaiter.or(c -> handler.hasResult()); // stop waiting if the process exist
      startupWaiter.blockUntilReady();

      if (handler.hasResult()) {
        String message =
            "The project at "
                + dirPath(projectRoot)
                + " started but exited all too soon. Check the console log for information.";
        buildLogHandler.consumeLine(message);
        throw new ProjectCannotStartException(message);
      }
    } catch (TimeoutException te) {
      String message =
          "Built successfully, but timed out waiting for startup at " + dirPath(projectRoot);
      watchDog.destroyProcess();
      buildLogHandler.consumeLine(message);
      throw new ProjectCannotStartException(message);
    } catch (ProjectCannotStartException pcse) {
      throw pcse;
    } catch (Exception e) {
      String message = "Built successfully, but error on start for " + dirPath(projectRoot);
      buildLogHandler.consumeLine(message);
      buildLogHandler.consumeLine(e.toString());
      throw new ProjectCannotStartException(message, e);
    }

    logEndTime(command, startTime);
    return watchDog;
  }
  @SuppressWarnings({"unchecked", "rawtypes"})
  @Override
  protected int _exec() {
    int returnValue = 0;
    CommandLine cmdLine = getCommandLine();

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    ExecuteWatchdog watchdog = new ScriptExecuteWatchdog();

    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    executor.setWorkingDirectory(currentDir);
    executor.setWatchdog(watchdog);
    if (terminal != null) {
      ExecuteStreamHandler monitorStreamHandler =
          new PumpStreamHandler(terminal.getOutputStream(), terminal.getErrorStream());
      executor.setStreamHandler(monitorStreamHandler);
    } else {
      ExecuteStreamHandler silentStreamHandler = new PumpStreamHandler();
      executor.setStreamHandler(silentStreamHandler);
    }

    Map procEnvironment = null;
    if (environment != null) {
      try {
        procEnvironment = EnvironmentUtils.getProcEnvironment();
        procEnvironment.putAll(environment);
      } catch (IOException e) {
        logger.error(e.getMessage());
        procEnvironment = null;
      }
    }

    try {
      executor.execute(cmdLine, procEnvironment, resultHandler);
      notifyStart();
    } catch (Exception e) {
      logger.warn("[EXECUTOR] ERROR: {}", e.getMessage());

      notifyError(-1, e.getMessage());

      return 1;
    }

    try {
      if (resultHandler.hasResult()) {
        notifyRefresh();
      } else {
        logger.info("[EXECUTOR] RUNNING");
        while (!resultHandler.hasResult()) {
          resultHandler.waitFor(PrefUtil.getInt(PrefUtil.SCRIPT_RUN_REFRESH_TIME, 1000));
          notifyRefresh();
        }
      }
    } catch (InterruptedException e) {
      logger.warn("[EXECUTOR] INTERRUPTED");
      watchdog.destroyProcess();
    } finally {
      if (watchdog.killedProcess()) {
        logger.warn("[EXECUTOR] WAITING FOR KILL");
        try {
          resultHandler.waitFor(PrefUtil.getInt(PrefUtil.SCRIPT_WAIT_FOR_KILL_REFRESH_TIME, 5000));
        } catch (InterruptedException e) {
          logger.warn("[EXECUTOR] INTERRUPTED: {}", e.getMessage());
          notifyError(-1, e.getMessage());
        }
      }
      try {
        ExecuteException exception = resultHandler.getException();
        if (exception != null) {
          returnValue = resultHandler.getExitValue();
          logger.warn("[EXECUTOR] ERROR: {}", exception.getMessage());

          if (terminal != null) {
            // String error = terminal.getErrorStream().peekLines();
            // notifyError(returnValue, error);
            // error is empty
            notifyError(returnValue, exception.getMessage());
          } else {
            notifyError(returnValue, exception.getMessage());
          }
          service.shutdownNow();
        } else {
          returnValue = resultHandler.getExitValue();
          logger.info("[EXECUTOR] FINISH: {}", returnValue);
          notifyFinish(resultHandler.getExitValue());
        }
      } catch (IllegalStateException e) {
        returnValue = -1;
        logger.warn("[EXECUTOR] INTERRUPTED: {}", e.getMessage());
        notifyError(returnValue, e.getMessage());
      }
    }
    if (!keepFileOnEnd) {
      internalDeleteOnEnd();
    }

    return returnValue;
  }
Example #7
0
 public void onProcessComplete(int exitValue) {
   super.onProcessComplete(exitValue);
   log.debug("The process successfully executed");
 }
Example #8
0
 public PrintResultHandler(int exitValue) {
   super.onProcessComplete(exitValue);
 }
 public void onProcessComplete(int exitValue) {
   super.onProcessComplete(exitValue);
   System.out.println("[resultHandler] The Syntren launcher was successfully completed ...");
 }
 public SyntrenRunScriptResultHandler(int exitValue) {
   super.onProcessComplete(exitValue);
 }