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

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

Introduction

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

Prototype

public DefaultExecutor() 

Source Link

Document

Default constructor creating a default PumpStreamHandler and sets the working directory of the subprocess to the current working directory.

Usage

From source file:org.codehaus.mojo.latex.LaTeXMojo.java

private void execute(CommandLine commandLine, File dir) throws IOException, MojoFailureException {
    final DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(dir);//from ww w . ja  va 2s .  co  m
    if (executor.execute(commandLine) != 0) {
        throw new MojoFailureException("Error code returned for: " + commandLine.toString());
    }
}

From source file:org.codehaus.mojo.VeraxxMojo.java

protected void preExecute(Executor exec, CommandLine commandLine, Map enviro) throws MojoExecutionException {
    OutputStream outStream = /*System.out;*/new ByteArrayOutputStream();
    OutputStream errStream = new ByteArrayOutputStream();

    CommandLine commandLineCheck = new CommandLine(getExecutable());
    Executor execCheck = new DefaultExecutor();
    String[] args = parseCommandlineArgs("--version");
    commandLineCheck.addArguments(args, false);
    execCheck.setWorkingDirectory(exec.getWorkingDirectory());

    getLog().info("Executing command line: " + commandLineCheck);

    int res = 0;/*from w  w w .  jav  a  2 s . c  o  m*/
    try {
        res = executeCommandLine(execCheck, commandLineCheck, enviro, outStream/*getOutputStreamOut()*/,
                errStream/*getOutputStreamErr()*/, getInputStream());
    } catch (ExecuteException e) {
        getLog().info(
                "Exec Exception while detecting Vera++ version. Assume old Vera++ v1.1.x (and less) output parsing style");
        getLog().info("Vera++ err output is : " + errStream.toString());
        veraxx_version = 0;
        /*throw new MojoExecutionException( "preExecute Command execution failed.", e );*/
        return;
    } catch (IOException e) {
        getLog().info("Vera++ detected version is : " + outStream.toString());
        getLog().info("Vera++ err output is : " + errStream.toString());
        // due to jdk8 bug :: https://bugs.openjdk.java.net/browse/JDK-8054565
        // we use this dirty try/catch ...
        // because this quick command line call can close the output stream before jvm does
        getLog().info("jvm " + System.getProperty("java.version") + " (8u11 - 9) workaround, ignoring a "
                + e.toString() + " during vera++ test command line.");
        //throw new MojoExecutionException( "preExecute Command execution failed.", e );
    }

    if (isResultCodeAFailure(res)) {
        getLog().info("Vera++ returned a failure result code : " + res);
        //throw new MojoExecutionException( "preExecute Result of " + commandLineCheck + " execution is: '" + res + "'." );
    }
    DefaultArtifactVersion newFormatMinVersion = new DefaultArtifactVersion("1.2.0");
    DefaultArtifactVersion currentVeraVersion = new DefaultArtifactVersion(outStream.toString());

    getLog().debug("Vera++ detected version is : " + outStream.toString());
    getLog().debug("Vera++ version as ArtefactVersion is : " + currentVeraVersion.toString());

    if (currentVeraVersion.compareTo(newFormatMinVersion) < 0) {
        getLog().info("Use old Vera++ v1.1.x (and less) output parsing style");
        veraxx_version = 0;
    } else {
        getLog().info("Use Vera++ v1.2.0 (and more) output parsing style");
        veraxx_version = 1;
    }
}

From source file:org.codice.alliance.distribution.sdk.video.stream.mpegts.MpegTsUdpClient.java

private static DefaultExecuteResultHandler executeFFmpeg(final CommandLine command, final int timeoutSeconds,
        final PumpStreamHandler streamHandler) throws IOException {
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutSeconds * 1000);
    final Executor executor = new DefaultExecutor();
    executor.setWatchdog(watchdog);/*w w  w.ja  v  a  2  s.  co m*/

    if (streamHandler != null) {
        executor.setStreamHandler(streamHandler);
    }

    final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    executor.execute(command, resultHandler);

    return resultHandler;
}

From source file:org.codice.git.GitIntegrationTest.java

private int executeGitCommand(String[] args) throws IOException {
    int exitValue = 0;
    List<String> outputLines = null;
    CommandLine cmdLine = new CommandLine("git");
    for (String arg : args) {
        cmdLine.addArgument(arg);/*from  w  ww  .j  a v a2 s.co  m*/
    }
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    executor.setWorkingDirectory(trash);
    CollectingLogOutputStream output = new CollectingLogOutputStream();
    PumpStreamHandler pump = new PumpStreamHandler(output, output);
    executor.setStreamHandler(pump);
    try {
        exitValue = executor.execute(cmdLine);
        outputLines = output.getLines();
    } catch (IOException e) {
        boolean hookRan = false;
        String errorMessage = "";
        // Check if we got the aborted message from the hook - implies it ran successfully
        outputLines = output.getLines();
        if ((outputLines != null) && (outputLines.size() > 0)) {
            errorMessage = outputLines.get(0);
            for (String line : outputLines) {
                if (line.contains("HOOK ABORTED")) {
                    hookRan = true;
                    break;
                }
            }
        }
        if (hookRan) {
            LOGGER.debug("Hook ran successfully - returning an error to abort the git command");
        } else {
            LOGGER.warn("Unexpected error during hook processing - first line of output: {}", errorMessage, e);
            throw e;
        }
        exitValue = 1;
    }

    for (String line : outputLines) {
        System.err.println(line);
    }
    return exitValue;
}

From source file:org.codice.git.hook.Artifact.java

/**
 * Downloads the artifact using maven./*from  www  . j a v  a 2s. c om*/
 *
 * @param settings the maven settings file or "" if using the default one
 * @param out      the output stream where to print messages to the user
 * @throws IOException if an error occurs
 */
protected void downloadUsingMaven(String settings, PrintStream out) throws IOException {
    final CommandLine cmd = new CommandLine(SystemUtils.IS_OS_WINDOWS ? "mvn.cmd" : "mvn");

    cmd.addArgument("-f").addArgument(new File(handler.getBasedir(), "pom.xml").getAbsolutePath());
    if (StringUtils.isNotEmpty(settings)) {
        cmd.addArgument("-s").addArgument(settings);
    }
    cmd.addArgument("org.apache.maven.plugins:maven-dependency-plugin:3.0.0:copy")
            .addArgument("-Dartifact=" + mvnInfo)
            .addArgument("-DoutputDirectory=" + handler.getBasedir().getAbsolutePath())
            .addArgument("-Dmdep.stripClassifier=true").addArgument("-Dmdep.stripVersion=true");
    if (!install) {
        cmd.addArgument("-quiet");
    }
    final DefaultExecutor exec = new DefaultExecutor();

    exec.setExitValue(0);
    try {
        exec.execute(cmd);
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, "failed to download blacklist words artifact", e);
        if (file.exists()) { // ignore the error and continue with the one that is there
            return;
        }
        out.printf("%sFailed to download artifact '%s'; %s.%n", eprefix, mvnInfo, e.getMessage());
        throw new IOException("failed to download blacklist words artifact", e);
    }
    if (!mvnName.equals(file.getName())) {
        final File f = new File(handler.getBasedir(), mvnName);

        out.printf("%sMoving %s to %s.%n", iprefix, mvnName, file);
        if (!f.renameTo(file)) {
            LOGGER.log(Level.WARNING, "failed to copy {0} file", file.getName());
            if (file.exists()) { // ignore the error and continue with the one that is there
                return;
            }
            out.printf("%sFailed to move %s to %s.%n", eprefix, mvnName, file);
            throw new IOException("failed to copy " + file.getName() + " file");
        }
    }
}

From source file:org.dataconservancy.dcs.access.server.util.VivoUtil.java

public static String cmdExec(String query, String sparqlEndpoint) {
    String cmd = "curl -s -S -X POST --data-binary \"" + query + "\" " + sparqlEndpoint;
    CommandLine cmdLine = CommandLine.parse(cmd);
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(stdout);

    executor.setStreamHandler(psh);//from   w ww . ja va 2 s.  c  om

    int exitValue;
    try {
        exitValue = executor.execute(cmdLine);
    } catch (ExecuteException e) {
        //logger.log(Level.SEVERE, e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        //.log(Level.SEVERE, e.getMessage());
        e.printStackTrace();
    }

    //String str = "";
    BufferedReader br = null;
    try {
        br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(stdout.toByteArray())));
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    String output_line = null;
    String xml = "";
    try {
        int flag = 0;

        while ((output_line = br.readLine()) != null) {
            if (output_line.contains("--:--")) {
                if (output_line.contains("<?xml version"))
                    output_line = output_line.substring(output_line.indexOf("<?xml version"));
                else
                    continue;
            }
            xml += output_line;

        }

    } catch (IOException e) {
        //logger.log(Level.SEVERE, e.getMessage());
        e.printStackTrace();
    }
    return xml;
}

From source file:org.dataconservancy.dcs.id.impl.DataciteIdService.java

ByteArrayOutputStream executeCommand(String command) throws IOException {
    CommandLine cmdLine = CommandLine.parse(command);
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(stdout);

    executor.setStreamHandler(psh);//from w  w w.  j a v a  2  s . co m

    int exitValue = executor.execute(cmdLine);
    return stdout;
}

From source file:org.docwhat.iated.AppState.java

public String editFile(File file) {
    String editor = getEditor();/* w ww.j  a v  a  2 s  .  c o m*/
    CommandLine cmd;

    if (OS.isFamilyMac() && editor.matches(".*\\.app")) {
        cmd = new CommandLine("/usr/bin/open");
        cmd.addArgument("-a").addArgument(editor).addArgument(file.toString());
    } else {
        cmd = new CommandLine(editor);
        cmd.addArgument(file.toString());
    }

    Executor executor = new DefaultExecutor();
    try {
        executor.execute(cmd);
    } catch (ExecuteException ex) {
        //TODO Do something meaningful with the exception.
        throw new RuntimeException(ex);
    } catch (IOException ex) {
        //TODO Do something meaningful with the exception.
        throw new RuntimeException(ex);
    }
    return "bogus-token";
}

From source file:org.eclipse.ecf.python.AbstractPythonLauncher.java

protected Executor createExecutor() {
    return new DefaultExecutor();
}

From source file:org.eclipse.kura.linux.net.modem.SupportedUsbModems.java

/**
 * Execute command an return splitted lines
 *
 * @param command//from  w w  w  .j a v  a2 s. c o  m
 *            the command to execute
 * @return the lines output by the command
 * @throws IOException
 *             if executing the commands fails
 */
private static List<String> execute(final String command) throws ExecuteException, IOException {
    final DefaultExecutor executor = new DefaultExecutor();

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(out, NullOutputStream.NULL_OUTPUT_STREAM));

    int rc = executor.execute(CommandLine.parse(command));

    s_logger.debug("Called {} - rc = {}", command, rc);

    return IOUtils.readLines(new ByteArrayInputStream(out.toByteArray()));
}