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

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

Introduction

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

Prototype

public PumpStreamHandler(final OutputStream out, final OutputStream err, final InputStream input) 

Source Link

Document

Construct a new PumpStreamHandler.

Usage

From source file:com.github.peterjanes.node.AbstractNpmInstallMojo.java

/**
 *
 * @param outputDirectory The working directory for the npm command.
 * @param npmDependencies A comma-separated list of npm packages to install.
 * @param extraArguments Extra arguments to provide to the npm command.
 * @param artifactScope Scope of the artifacts to include.
 * @throws MojoExecutionException if anything unexpected happens.
 *//*from   w w  w. j a  v  a 2 s  .c  om*/
void execute(File outputDirectory, String npmDependencies, String extraArguments, ResolutionScope artifactScope)
        throws MojoExecutionException {
    if (!outputDirectory.exists()) {
        outputDirectory.mkdirs();
    }

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

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

    if (null != npmDependencies) {
        String[] packages = npmDependencies.split(",");
        for (String pkg : packages) {
            commandArguments.add(pkg);
        }
    }

    List<Artifact> nodeArtifacts = getNodeArtifacts(artifactScope);
    for (Artifact artifact : nodeArtifacts) {
        commandArguments.add(artifact.getFile().getAbsolutePath());
    }

    if (null != extraArguments) {
        String[] extraArgs = extraArguments.split(" ");
        for (String extraArg : extraArgs) {
            commandArguments.add(extraArg);
        }
    }

    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 = getLog().isDebugEnabled() ? System.err : new ByteArrayOutputStream();
    OutputStream stderr = getLog().isDebugEnabled() ? System.err : new ByteArrayOutputStream();

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

        int resultCode = exec.execute(commandLine);

        if (0 != resultCode) {
            System.out.println("STDOUT: " + stdout);
            System.err.println("STDERR: " + stderr);
            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);
    }
}

From source file:it.sonarlint.cli.tools.CommandExecutor.java

private ExecuteStreamHandler createStreamHandler() throws IOException {
    out = new ByteArrayOutputStream();
    err = new ByteArrayOutputStream();
    PipedOutputStream outPiped = new PipedOutputStream();
    InputStream inPiped = new PipedInputStream(outPiped);
    in = outPiped;/*from w  w w . j  ava2  s. c om*/

    TeeOutputStream teeOut = new TeeOutputStream(out, System.out);
    TeeOutputStream teeErr = new TeeOutputStream(err, System.err);

    return new PumpStreamHandler(teeOut, teeErr, inPiped);
}

From source file:name.martingeisse.webide.features.verilog.compiler.VerilogBuilder.java

private void compile(long workspaceId, final JsonAnalyzer descriptorAnalyzer, ResourcePath inputFilePath,
        ResourcePath outputFilePath) {/*from  w  w  w  .  j  a v a  2 s. c om*/
    try {

        // prepare
        ResourceHandle inputFile = new ResourceHandle(workspaceId, inputFilePath);
        ResourceHandle outputFile = new ResourceHandle(workspaceId, outputFilePath);

        // read the input file
        byte[] inputData = inputFile.readBinaryFile(false);
        if (inputData == null) {
            return;
        }

        // delete previous output file
        outputFile.delete();

        // build the command line
        CommandLine commandLine = new CommandLine(Configuration.getIverilogPath());
        commandLine.addArgument("-o");
        commandLine.addArgument(Configuration.getStdoutPath());
        commandLine.addArgument(Configuration.getStdinPath());

        // build I/O streams
        ByteArrayInputStream inputStream = new ByteArrayInputStream(inputData);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        OutputStream errorStream = System.err;
        ExecuteStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream, inputStream);

        // run Icarus
        Executor executor = new DefaultExecutor();
        executor.setStreamHandler(streamHandler);
        executor.execute(commandLine);

        // create the output file
        outputFile.writeFile(outputStream.toByteArray(), true, true);

    } catch (IOException e) {
        // TODO error message
        logger.error(e);
        return;
    }

}

From source file:com.anrisoftware.mongoose.buildins.execbuildin.ExecBuildin.java

private void startProcess() throws IOException, InterruptedException {
    executor.setProcessDestroyer(destroyer);
    executor.setWatchdog(watchdog);/*from  ww w. j av a  2  s.com*/
    executor.setStreamHandler(new PumpStreamHandler(getOutput(), getError(), getInput()));
    executor.execute(parser.parseCommand(command), env, handler);
    waitForCommand();
    parser.cleanUp();
}

From source file:de.tu_dresden.psy.fca.ConexpCljBridge.java

public ConexpCljBridge() {

    this.b = new byte[1];

    /**/*  w  w  w  .jav a2s  . co  m*/
     * build the command line (see conexp-clj/bin/conexp-clj)
     */

    String java_bin = Launcher.getJavaCommand();

    CommandLine conexp_cmd = new CommandLine(java_bin);
    conexp_cmd.addArgument("-server");
    conexp_cmd.addArgument("-cp");
    conexp_cmd.addArgument("./conexp-clj/lib/conexp-clj-0.0.7-alpha-SNAPSHOT-standalone.jar");
    conexp_cmd.addArgument("clojure.main");
    conexp_cmd.addArgument("-e");
    conexp_cmd.addArgument("");
    conexp_cmd.addArgument("./conexp-clj/lib/conexp-clj.clj");

    /**
     * open the pipes
     */

    this.to_conexp = new PipedOutputStream();
    try {
        this.stream_to_conexp = new PipedInputStream(this.to_conexp, 2048);
    } catch (IOException e2) {
        e2.printStackTrace();
    }

    this.stream_error_conexp = new PipedOutputStream();
    this.stream_from_conexp = new PipedOutputStream();

    try {
        this.from_conexp = new PipedInputStream(this.stream_from_conexp, 2048);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    try {
        this.error_conexp = new PipedInputStream(this.stream_error_conexp, 2048);
    } catch (IOException e1) {

        e1.printStackTrace();
    }

    /**
     * setup apache commons exec
     */

    this.result = new DefaultExecuteResultHandler();

    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    executor.setStreamHandler(
            new PumpStreamHandler(this.stream_from_conexp, this.stream_error_conexp, this.stream_to_conexp));

    /**
     * run in non-blocking mode
     */

    try {
        executor.execute(conexp_cmd, this.result);
    } catch (ExecuteException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    this.output_buffer = "";

}

From source file:ch.vorburger.exec.ManagedProcess.java

protected synchronized void startPreparation() throws ManagedProcessException {
    if (isAlive()) {
        throw new ManagedProcessException(procLongName()
                + " is still running, use another ManagedProcess instance to launch another one");
    }/*from  w w w. j a  v  a2s.  c o  m*/
    if (logger.isInfoEnabled())
        logger.info("Starting {}", procLongName());

    stdouts = new MultiOutputStream();
    stderrs = new MultiOutputStream();
    PumpStreamHandler outputHandler = new PumpStreamHandler(stdouts, stderrs, input);
    executor.setStreamHandler(outputHandler);

    String pid = procShortName();
    stdouts.addOutputStream(new SLF4jLogOutputStream(logger, pid, STDOUT, outputStreamLogDispatcher));
    stderrs.addOutputStream(new SLF4jLogOutputStream(logger, pid, STDERR, outputStreamLogDispatcher));

    if (consoleBufferMaxLines > 0) {
        console = new RollingLogOutputStream(consoleBufferMaxLines);
        stdouts.addOutputStream(console);
        stderrs.addOutputStream(console);
    }

    if (destroyOnShutdown) {
        executor.setProcessDestroyer(shutdownHookProcessDestroyer);
    }

    if (commandLine.isFile()) {
        try {
            Util.forceExecutable(getExecutableFile());
        } catch (Exception e) {
            throw new ManagedProcessException("Unable to make command executable", e);
        }
    } else {
        logger.debug(commandLine.getExecutable()
                + " is not a java.io.File, so it won't be made executable (which MAY be a problem on *NIX, but not for sure)");
    }
}

From source file:net.robyf.dbpatcher.util.MySqlUtil.java

private static void executeWithInput(final CommandLine commandLine, final InputStream input) {
    try {//from   w w  w .  j  av  a  2  s  .com
        PumpStreamHandler handler = new PumpStreamHandler(null, null, input);

        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(handler);
        executor.setWatchdog(new ExecuteWatchdog(300000L));
        int returnCode = executor.execute(commandLine);
        if (returnCode != 0) {
            throw new UtilException("Error executing: " + commandLine //NOSONAR
                    + ", return code = " + returnCode); //NOSONAR
        }
    } catch (IOException ioe) {
        throw new UtilException("Error executing: " + commandLine, ioe); //NOSONAR
    }
}

From source file:com.k42b3.sacmis.Sacmis.java

private void executeCommand() {
    out.setText("");

    try {//ww  w  . j a  va 2 s.  c  o  m
        // save file
        saveFile();

        CommandLine commandLine = CommandLine.parse(this.path + " " + this.args.getText());

        // set timeout
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);

        // create executor
        DefaultExecutor executor = new DefaultExecutor();

        executor.setExitValue(this.exitCode);

        this.baos = new ByteArrayOutputStream();

        this.baosErr = new ByteArrayOutputStream();

        if (this.writerStdIn) {
            this.bais = new ByteArrayInputStream(in.getText().getBytes());

            executor.setStreamHandler(new PumpStreamHandler(this.baos, this.baosErr, this.bais));
        } else {
            executor.setStreamHandler(new PumpStreamHandler(this.baos, this.baosErr));
        }

        executor.setWatchdog(watchdog);

        executor.execute(commandLine, new ExecuteResultHandler() {

            public void onProcessComplete(int e) {
                out.setText(baos.toString());
            }

            public void onProcessFailed(ExecuteException e) {
                out.setText(baosErr.toString());
            }

        });
    } catch (Exception e) {
        out.setText(e.getMessage());
    }
}

From source file:edu.stolaf.cs.wmrserver.testjob.TestJobTask.java

protected TestJobResult.TransformResult runTransform(long id, File executable, File workingDir,
        InputStream input) throws IOException {
    // Create the result object
    TestJobResult.TransformResult result = new TestJobResult.TransformResult();

    CountingOutputStream output = null;// w  ww .j  a  v  a  2  s  .c om
    CountingOutputStream error = null;
    try {
        // Create and open temporary file for standard output
        File outputFile = File.createTempFile("job-" + Long.toString(_id), "-output", _tempDir);
        output = new CountingOutputStream(new FileOutputStream(outputFile));

        // Create and open temporary file for standard error
        File errorFile = File.createTempFile("job-" + Long.toString(_id), "-error", _tempDir);
        error = new CountingOutputStream(new FileOutputStream(errorFile));

        // If executable is relative, try to resolve in working directory
        // (This emulates the behavior of Streaming)
        if (!executable.isAbsolute()) {
            File resolvedExecutable = new File(workingDir, executable.toString());
            if (resolvedExecutable.isFile()) {
                resolvedExecutable.setExecutable(true);
                executable = resolvedExecutable.getAbsoluteFile();
            }
        }

        // Run the transform

        CommandLine command;
        if (_switchUserCommand == null)
            command = new CommandLine(executable);
        else {
            command = CommandLine.parse(_switchUserCommand);
            HashMap<String, String> substitutionMap = new HashMap<String, String>();
            substitutionMap.put("cmd", executable.toString());
            command.setSubstitutionMap(substitutionMap);
        }

        DefaultExecutor executor = new DefaultExecutor();
        ExecuteWatchdog dog = new ExecuteWatchdog(EXECUTABLE_TIMEOUT);
        PumpStreamHandler pump = new PumpStreamHandler(output, error, input);
        executor.setWorkingDirectory(workingDir);
        executor.setWatchdog(dog);
        executor.setStreamHandler(pump);
        executor.setExitValues(null);

        int exitCode = executor.execute(command);

        result.setExitCode(exitCode);

        // Check whether it produced any output
        if (output.getByteCount() == 0) {
            output.close();
            outputFile.delete();
        } else
            result.setOutputFile(outputFile);

        // Check whether it produced any error output
        if (error.getByteCount() == 0) {
            error.close();
            errorFile.delete();
        } else
            result.setErrorFile(errorFile);
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(error);
    }

    return result;
}

From source file:com.lenox.common.exec.ManagedProcess.java

protected synchronized void startPreparation() throws ManagedProcessException {
    if (isAlive()) {
        throw new ManagedProcessException(procLongName()
                + " is still running, use another ManagedProcess instance to launch another one");
    }//from w  w  w.j  a v  a 2s . c  om
    if (logger.isInfoEnabled())
        logger.info("Starting {}", procLongName());

    stdouts = new MultiOutputStream();
    stderrs = new MultiOutputStream();
    PumpStreamHandler outputHandler = new PumpStreamHandler(stdouts, stderrs, input);
    executor.setStreamHandler(outputHandler);

    String pid = procShortName();
    stdouts.addOutputStream(new SLF4jLogOutputStream(logger, pid, SLF4jLogOutputStream.Type.stdout));
    stderrs.addOutputStream(new SLF4jLogOutputStream(logger, pid, SLF4jLogOutputStream.Type.stderr));

    if (consoleBufferMaxLines > 0) {
        console = new RollingLogOutputStream(consoleBufferMaxLines);
        stdouts.addOutputStream(console);
        stderrs.addOutputStream(console);
    }

    if (destroyOnShutdown) {
        executor.setProcessDestroyer(shutdownHookProcessDestroyer);
    }

    if (commandLine.isFile()) {
        try {
            Util.forceExecutable(getExecutableFile());
        } catch (Exception e) {
            throw new ManagedProcessException("Unable to make command executable", e);
        }
    }
}