Example usage for org.apache.commons.exec CommandLine CommandLine

List of usage examples for org.apache.commons.exec CommandLine CommandLine

Introduction

In this page you can find the example usage for org.apache.commons.exec CommandLine CommandLine.

Prototype

public CommandLine(final CommandLine other) 

Source Link

Document

Copy constructor.

Usage

From source file:org.jahia.modules.dm.viewer.impl.PDF2SWFConverterService.java

protected CommandLine getConvertCommandLine(File inputFile, File outputFile) {
    CommandLine cmd = new CommandLine(executablePath);
    cmd.addArguments(parameters);// w  ww  .  jav a2 s .co m

    Map<String, File> params = new HashMap<String, File>(2);
    params.put("input", inputFile);
    params.put("output", outputFile);

    cmd.setSubstitutionMap(params);

    return cmd;
}

From source file:org.jahia.modules.docviewer.PDF2SWFConverterService.java

protected CommandLine getConvertCommandLine(File inputFile, File outputFile) {
    CommandLine cmd = new CommandLine(getExecutablePath());
    cmd.addArgument("${inFile}");
    cmd.addArgument("-o");
    cmd.addArgument("${outFile}");
    cmd.addArguments(getParameters(), false);

    Map<String, File> params = new HashMap<String, File>(2);
    params.put("inFile", inputFile);
    params.put("outFile", outputFile);

    cmd.setSubstitutionMap(params);//from ww w  .  j a  v  a 2  s.c o  m

    return cmd;
}

From source file:org.jahia.services.templates.SourceControlFactory.java

/**
 * Sets the executables for various SCM providers.
 * //from  w  w  w  .ja  v  a  2 s. co  m
 * @param sourceControlExecutables
 *            a map with paths to SCM executables by SCM type
 */
public void setSourceControlExecutables(Map<String, String> sourceControlExecutables) {
    this.sourceControlExecutables = new HashMap<String, String>();
    for (Map.Entry<String, String> entry : sourceControlExecutables.entrySet()) {
        try {
            DefaultExecutor executor = new DefaultExecutor();
            executor.setStreamHandler(
                    new PumpStreamHandler(new StringOutputStream(), new StringOutputStream()));
            executor.execute(new CommandLine(entry.getValue()), System.getenv());
        } catch (ExecuteException e) {
            // ignore this one as the command always returns error code 1
        } catch (IOException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Unable to execute the " + entry.getKey() + " SCM executable: " + entry.getValue()
                        + ". The SCM provider will be disabled. Cause: " + e.getMessage(), e);
            } else {
                logger.info("Cannot find a valid " + entry.getKey() + " SCM executable at: " + entry.getValue()
                        + ". The SCM provider will be skipped.");
            }
            continue;
        }
        this.sourceControlExecutables.put(entry.getKey(), entry.getValue());
    }
}

From source file:org.jahia.utils.ProcessHelper.java

/**
 * Executes the external process using the provided command, arguments (optional), parameter substitution map to expand variables in the
 * command or arguments in form of <code>${variable}<code> (optional) and a working directory (optional).
 * Buffers for process output and error stream can be provided.
 * //from w w  w  . ja v  a2s . c o m
 * @param command
 *            the command to be executed
 * @param arguments
 *            optional arguments for the command
 * @param parameterSubstitutionMap
 *            optional values for variables to be expanded
 * @param workingDir
 *            optional working directory for the process to be started from
 * @param resultOut
 *            the buffer to write the process execution output into (optional)
 * @param resultErr
 *            the buffer to write the process execution error into (optional)
 * @return the execution status
 * @return redirectOutputs if set to <code>true</code> the output of the execution will be also redirected to standard system out and
 *         the error to error out
 * @throws JahiaRuntimeException
 *             in case the process execution failed
 */
public static int execute(String command, String arguments[], Map<String, Object> parameterSubstitutionMap,
        File workingDir, StringBuilder resultOut, StringBuilder resultErr, boolean redirectOutputs)
        throws JahiaRuntimeException {

    long timer = System.currentTimeMillis();

    CommandLine cmd = new CommandLine(command);

    if (arguments != null && arguments.length > 0) {
        cmd.addArguments(arguments, false);
    }

    if (parameterSubstitutionMap != null && !parameterSubstitutionMap.isEmpty()) {
        cmd.setSubstitutionMap(parameterSubstitutionMap);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Executing command: {}", cmd.toString());
    } else if (redirectOutputs) {
        logger.info("Executing command: ");
        logger.info(cmd.toString());
    }

    int exitValue = 0;

    StringOutputStream out = new StringOutputStream(redirectOutputs ? System.out : null);
    StringOutputStream err = new StringOutputStream(redirectOutputs ? System.err : null);
    try {
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(out, err));
        if (workingDir != null) {
            if (workingDir.exists() || workingDir.mkdirs()) {
                executor.setWorkingDirectory(workingDir);
            }
        }
        exitValue = executor.execute(cmd, System.getenv());
    } catch (ExecuteException ee) {
        return ee.getExitValue();
    } catch (Exception e) {
        throw new JahiaRuntimeException(e);
    } finally {
        if (resultErr != null) {
            resultErr.append(err.toString());
        }
        if (resultOut != null) {
            resultOut.append(out.toString());
        }
        if (exitValue > 0) {
            logger.error("External process finished with error. Cause: {}", err.toString());
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Execution took {} ms and finished with status {} and output {}",
                    new Object[] { (System.currentTimeMillis() - timer), exitValue, out.toString() });
        }
    }

    return exitValue;
}

From source file:org.jberet.support.io.OsCommandBatchlet.java

/**
 * {@inheritDoc}//from   w  ww  .j a v  a 2 s  . c  o m
 * <p>
 * This method runs the OS command.
 * If the command completes successfully, its process exit code is returned.
 * If there is exception while running the OS command, which may be
 * caused by timeout, the command being stopped, or other errors, the process
 * exit code is set as the step exit status, and the exception is thrown.
 *
 * @return the OS command process exit code
 *
 * @throws Exception upon errors
 */
@Override
public String process() throws Exception {
    final DefaultExecutor executor = new DefaultExecutor();
    final CommandLine commandLineObj;
    if (commandLine != null) {
        commandLineObj = CommandLine.parse(commandLine);
    } else {
        if (commandArray == null) {
            throw SupportMessages.MESSAGES.invalidReaderWriterProperty(null, null, "commandArray");
        } else if (commandArray.isEmpty()) {
            throw SupportMessages.MESSAGES.invalidReaderWriterProperty(null, commandArray.toString(),
                    "commandArray");
        }
        commandLineObj = new CommandLine(commandArray.get(0));
        final int len = commandArray.size();
        if (len > 1) {
            for (int i = 1; i < len; i++) {
                commandLineObj.addArgument(commandArray.get(i));
            }
        }
    }

    if (workingDir != null) {
        executor.setWorkingDirectory(workingDir);
    }
    if (streamHandler != null) {
        executor.setStreamHandler((ExecuteStreamHandler) streamHandler.newInstance());
    }

    SupportLogger.LOGGER.runCommand(commandLineObj.getExecutable(),
            Arrays.toString(commandLineObj.getArguments()), executor.getWorkingDirectory().getAbsolutePath());

    if (commandOkExitValues != null) {
        executor.setExitValues(commandOkExitValues);
    }

    watchdog = new ExecuteWatchdog(
            timeoutSeconds > 0 ? timeoutSeconds * 1000 : ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchdog);

    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    executor.execute(commandLineObj, environment, resultHandler);
    resultHandler.waitFor();

    final ExecuteException exception = resultHandler.getException();
    if (exception != null) {
        stepContext.setExitStatus(String.valueOf(resultHandler.getExitValue()));
        if (!isStopped) {
            throw exception;
        } else {
            SupportLogger.LOGGER.warn("", exception);
        }
    }
    return String.valueOf(resultHandler.getExitValue());
}

From source file:org.jboss.windup.decorator.java.decompiler.BackupOfJadretroDecompilerAdapter.java

private void executeJad(File classLocation, File sourceOutputLocation) {

    try {//from  w  w  w.j  ava  2  s  .c  om
        // Build command array
        CommandLine cmdLine = new CommandLine(APP_NAME);
        cmdLine.addArgument("-d");
        cmdLine.addArgument("${outputLocation}");
        cmdLine.addArgument("-f");
        cmdLine.addArgument("-o");
        cmdLine.addArgument("-s");
        cmdLine.addArgument("java");
        cmdLine.addArgument("${classLocation}");

        Map<String, Object> argMap = new HashMap<String, Object>();
        argMap.put("outputLocation", sourceOutputLocation);
        argMap.put("classLocation", classLocation);
        cmdLine.setSubstitutionMap(argMap);

        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
        executor.setWatchdog(watchdog);
        int exitValue = executor.execute(cmdLine);

        LOG.debug("Decompiler exited with exit code: " + exitValue);

        if (!sourceOutputLocation.exists()) {
            LOG.error("Expected decompiled source: " + sourceOutputLocation.getAbsolutePath()
                    + "; did not find file.  This likey means that the decompiler did not successfully decompile the class.");
        } else {
            LOG.debug("Decompiled to: " + sourceOutputLocation.getAbsolutePath());
        }

    } catch (IOException e) {
        throw new FatalWindupException(
                "Error running " + APP_NAME + " decompiler.  Validate that " + APP_NAME + " is on your PATH.",
                e);
    } catch (Exception e) {
        throw new FatalWindupException(
                "Error running " + APP_NAME + " decompiler.  Validate that " + APP_NAME + " is on your PATH.",
                e);
    }
}

From source file:org.jboss.windup.decorator.java.decompiler.JadretroDecompilerAdapter.java

private void executeJad(File classLocation, File sourceOutputLocation) {

    try {/*from  w  w  w .ja v a 2  s  .c o  m*/
        // Build command array
        CommandLine cmdLine = new CommandLine(APP_NAME);
        cmdLine.addArgument("-d");
        cmdLine.addArgument("${outputLocation}");
        cmdLine.addArgument("-f");
        cmdLine.addArgument("-o");
        cmdLine.addArgument("-s");
        cmdLine.addArgument("java");
        cmdLine.addArgument("${classLocation}");

        Map<String, Object> argMap = new HashMap<String, Object>();
        argMap.put("outputLocation", sourceOutputLocation);
        argMap.put("classLocation", classLocation);
        cmdLine.setSubstitutionMap(argMap);

        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
        executor.setWatchdog(watchdog);
        int exitValue = executor.execute(cmdLine);

        LOG.debug("Decompiler exited with exit code: " + exitValue);

        if (!sourceOutputLocation.exists()) {
            LOG.error("Expected decompiled source: " + sourceOutputLocation.getAbsolutePath()
                    + "; did not find file.  This likey means that the decompiler did not successfully decompile the class.");
        } else {
            LOG.debug("Decompiled to: " + sourceOutputLocation.getAbsolutePath());
        }

    } catch (IOException e) {
        throw new FatalWindupException(
                "Error running " + APP_NAME + " decompiler.  Validate that " + APP_NAME + " is on your PATH.",
                e);
    }
}

From source file:org.jlab.clara.std.services.DataManager.java

private void stageInputFile(FilePaths files, EngineData output) {
    Path stagePath = FileUtils.getParent(files.stagedInputFile);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {//from  w  ww . j av a  2 s . c o  m
        FileUtils.createDirectories(stagePath);

        CommandLine cmdLine = new CommandLine("cp");
        cmdLine.addArgument(files.inputFile.toString());
        cmdLine.addArgument(files.stagedInputFile.toString());

        DefaultExecutor executor = new DefaultExecutor();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        executor.setStreamHandler(streamHandler);

        executor.execute(cmdLine);
        System.out.printf("%s service: input file '%s' copied to '%s'%n", NAME, files.inputFile, stagePath);
        returnFilePaths(output, files);

    } catch (ExecuteException e) {
        ServiceUtils.setError(output, "could not complete request: " + outputStream.toString().trim());
    } catch (IOException e) {
        ServiceUtils.setError(output, "could not complete request: " + e.getMessage());
    }
}

From source file:org.jlab.clara.std.services.DataManager.java

private void removeStagedInputFile(FilePaths files, EngineData output) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {// w w  w.j  a  v a  2  s  .co m
        CommandLine cmdLine = new CommandLine("rm");
        cmdLine.addArgument(files.stagedInputFile.toString());

        DefaultExecutor executor = new DefaultExecutor();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        executor.setStreamHandler(streamHandler);

        executor.execute(cmdLine);
        System.out.printf("%s service: staged input file %s removed%n", NAME, files.stagedInputFile);
        returnFilePaths(output, files);

    } catch (ExecuteException e) {
        ServiceUtils.setError(output, "could not complete request: " + outputStream.toString().trim());
    } catch (IOException e) {
        ServiceUtils.setError(output, "could not complete request: " + e.getMessage());
    }
}

From source file:org.jlab.clara.std.services.DataManager.java

private void saveOutputFile(FilePaths files, EngineData output) {
    Path outputPath = FileUtils.getParent(files.outputFile);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {//w  w  w .  j a v a2  s  .c  om
        FileUtils.createDirectories(outputPath);

        CommandLine cmdLine = new CommandLine("mv");

        //            cmdLine.addArgument(files.stagedOutputFile.toString());
        //            cmdLine.addArgument(files.outputFile.toString());

        //             modified 09.12.18. Stage back multiple output files. vg
        Files.list(directoryPaths.stagePath).forEach(name -> {
            name.startsWith(files.stagedOutputFile.toString());
            cmdLine.addArgument(name.toString());
        });
        cmdLine.addArgument(outputPath.toString());
        //                                                                  vg

        DefaultExecutor executor = new DefaultExecutor();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        executor.setStreamHandler(streamHandler);

        executor.execute(cmdLine);
        System.out.printf("%s service: output file '%s' saved to '%s'%n", NAME, files.stagedOutputFile,
                outputPath);
        returnFilePaths(output, files);

    } catch (ExecuteException e) {
        ServiceUtils.setError(output, "could not complete request: " + outputStream.toString().trim());
    } catch (IOException e) {
        ServiceUtils.setError(output, "could not complete request: " + e.getMessage());
    }
}