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

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

Introduction

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

Prototype

public void setExitValue(final int value) 

Source Link

Usage

From source file:org.ng200.openolympus.cerberus.executors.SandboxedExecutor.java

@Override
public ExecutionResult execute(final Path program) throws IOException {
    SandboxedExecutor.logger.debug("Copying program into jail");
    final Path chrootedProgram = this.storage.getPath().resolve("chroot")
            .resolve(program.getFileName().toString());
    chrootedProgram.getParent().toFile().mkdirs();
    FileAccess.copy(program, chrootedProgram, StandardCopyOption.COPY_ATTRIBUTES);

    final CommandLine commandLine = new CommandLine("sudo");
    commandLine.addArgument("olympus_watchdog");

    this.setUpOlrunnerLimits(commandLine);

    commandLine.addArgument(MessageFormat.format("--jail={0}",
            this.storage.getPath().resolve("chroot").toAbsolutePath().toString()));

    commandLine.addArgument("--");
    commandLine//  w  w  w  . ja  v  a  2s .  co  m
            .addArgument("/" + this.storage.getPath().resolve("chroot").relativize(chrootedProgram).toString());

    final DefaultExecutor executor = new DefaultExecutor();

    executor.setExitValue(0);

    executor.setWatchdog(new ExecuteWatchdog(60000)); // 60 seconds for the
    // sandbox to
    // complete

    executor.setWorkingDirectory(this.storage.getPath().toFile());

    executor.setStreamHandler(new PumpStreamHandler(this.outputStream, this.errorStream, this.inputStream));

    SandboxedExecutor.logger.debug("Executing in sandbox: {}", commandLine.toString());
    try {
        executor.execute(commandLine);
    } catch (final ExecuteException e) {
        SandboxedExecutor.logger.info("Execution failed: {}", e);
        throw e;
    } catch (final IOException e) {
        if (!e.getMessage().toLowerCase().equals("stream closed")) {
            throw e;
        }
    }

    return this.readOlrunnerVerdict(this.storage.getPath().resolve("verdict.txt"));
}

From source file:org.opencron.agent.AgentProcessor.java

@Override
public Response execute(final Request request) throws TException {
    if (!this.password.equalsIgnoreCase(request.getPassword())) {
        return errorPasswordResponse(request);
    }//from w  w  w.  j  a  va  2  s  . c o  m

    String command = request.getParams().get("command") + EXITCODE_SCRIPT;

    String pid = request.getParams().get("pid");
    //??
    Long timeout = CommonUtils.toLong(request.getParams().get("timeout"), 0L);

    boolean timeoutFlag = timeout > 0;

    logger.info("[opencron]:execute:{},pid:{}", command, pid);

    File shellFile = CommandUtils.createShellFile(command, pid);

    Integer exitValue;

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    final Response response = Response.response(request);

    final ExecuteWatchdog watchdog = new ExecuteWatchdog(Integer.MAX_VALUE);

    final Timer timer = new Timer();

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    try {
        CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath());
        final DefaultExecutor executor = new DefaultExecutor();

        ExecuteStreamHandler stream = new PumpStreamHandler(outputStream, outputStream);
        executor.setStreamHandler(stream);
        response.setStartTime(new Date().getTime());
        //?0,shell
        executor.setExitValue(0);

        if (timeoutFlag) {
            //...
            executor.setWatchdog(watchdog);
            //
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //,kill...
                    if (watchdog.isWatching()) {
                        /**
                         * watchdogdestroyProcesskill...
                         * watchdog.destroyProcess();
                         */
                        timer.cancel();
                        watchdog.stop();
                        //call  kill...
                        request.setAction(Action.KILL);
                        try {
                            kill(request);
                            response.setExitCode(Opencron.StatusCode.TIME_OUT.getValue());
                        } catch (TException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }, timeout * 60 * 1000);

            //
            resultHandler = new DefaultExecuteResultHandler() {
                @Override
                public void onProcessComplete(int exitValue) {
                    super.onProcessComplete(exitValue);
                    timer.cancel();
                }

                @Override
                public void onProcessFailed(ExecuteException e) {
                    super.onProcessFailed(e);
                    timer.cancel();
                }
            };
        }

        executor.execute(commandLine, resultHandler);

        resultHandler.waitFor();

    } catch (Exception e) {
        if (e instanceof ExecuteException) {
            exitValue = ((ExecuteException) e).getExitValue();
        } else {
            exitValue = Opencron.StatusCode.ERROR_EXEC.getValue();
        }
        if (Opencron.StatusCode.KILL.getValue().equals(exitValue)) {
            if (timeoutFlag) {
                timer.cancel();
                watchdog.stop();
            }
            logger.info("[opencron]:job has be killed!at pid :{}", request.getParams().get("pid"));
        } else {
            logger.info("[opencron]:job execute error:{}", e.getCause().getMessage());
        }
    } finally {

        exitValue = resultHandler.getExitValue();

        if (CommonUtils.notEmpty(outputStream.toByteArray())) {
            try {
                outputStream.flush();
                String text = outputStream.toString();
                if (notEmpty(text)) {
                    try {
                        text = text.replaceAll(String.format(REPLACE_REX, shellFile.getAbsolutePath()), "");
                        response.setMessage(text.substring(0, text.lastIndexOf(EXITCODE_KEY)));
                        exitValue = Integer.parseInt(text
                                .substring(text.lastIndexOf(EXITCODE_KEY) + EXITCODE_KEY.length() + 1).trim());
                    } catch (IndexOutOfBoundsException e) {
                        response.setMessage(text);
                    }
                }
                outputStream.close();
            } catch (Exception e) {
                logger.error("[opencron]:error:{}", e);
            }
        }

        if (Opencron.StatusCode.TIME_OUT.getValue() == response.getExitCode()) {
            response.setSuccess(false).end();
        } else {
            response.setExitCode(exitValue)
                    .setSuccess(response.getExitCode() == Opencron.StatusCode.SUCCESS_EXIT.getValue()).end();
        }

        if (shellFile != null) {
            shellFile.delete();//
        }
    }
    logger.info("[opencron]:execute result:{}", response.toString());
    watchdog.stop();

    return response;
}

From source file:org.opennms.netmgt.integrations.R.RScriptExecutor.java

/**
 * Executes by given script by:/*w  w w .j av a 2  s  . c  o  m*/
 *   - Searching both the classpath and the filesystem for the path
 *   - Copying the script at the given path to a temporary file and
 *     performing variable substitution with the arguments using Freemarker.
 *   - Invoking the script with commons-exec
 *   - Converting the input table to CSV and passing this to the process via stdin
 *   - Parsing stdout, expecting CSV output, and converting this to an immutable table
 */
public RScriptOutput exec(String script, RScriptInput input) throws RScriptException {
    Preconditions.checkNotNull(script, "script argument");
    Preconditions.checkNotNull(input, "input argument");

    // Grab the script/template
    Template template;
    try {
        template = m_freemarkerConfiguration.getTemplate(script);
    } catch (IOException e) {
        throw new RScriptException("Failed to read the script.", e);
    }

    // Create a temporary file
    File scriptOnDisk;
    try {
        scriptOnDisk = File.createTempFile("Rcsript", "R");
        scriptOnDisk.deleteOnExit();
    } catch (IOException e) {
        throw new RScriptException("Failed to create a temporary file.", e);
    }

    // Perform variable substitution and write the results to the temporary file
    try (FileOutputStream fos = new FileOutputStream(scriptOnDisk); Writer out = new OutputStreamWriter(fos);) {
        template.process(input.getArguments(), out);
    } catch (IOException | TemplateException e) {
        scriptOnDisk.delete();
        throw new RScriptException("Failed to process the template.", e);
    }

    // Convert the input matrix to a CSV string which will be passed to the script via stdin.
    // The table may be large, so we try and avoid writing it to disk
    StringBuilder inputTableAsCsv;
    try {
        inputTableAsCsv = toCsv(input.getTable());
    } catch (IOException e) {
        scriptOnDisk.delete();
        throw new RScriptException("Failed to convert the input table to CSV.", e);
    }

    // Invoke Rscript against the script (located in a temporary file)
    CommandLine cmdLine = new CommandLine(RSCRIPT_BINARY);
    cmdLine.addArgument(scriptOnDisk.getAbsolutePath());

    // Use commons-exec to execute the process
    DefaultExecutor executor = new DefaultExecutor();

    // Use the CharSequenceInputStream in order to avoid explicitly converting
    // the StringBuilder a string and then an array of bytes.
    InputStream stdin = new CharSequenceInputStream(inputTableAsCsv, Charset.forName("UTF-8"));
    ByteArrayOutputStream stderr = new ByteArrayOutputStream();
    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(stdout, stderr, stdin));

    // Fail if we get a non-zero exit code
    executor.setExitValue(0);

    // Fail if the process takes too long
    ExecuteWatchdog watchdog = new ExecuteWatchdog(SCRIPT_TIMEOUT_MS);
    executor.setWatchdog(watchdog);

    // Execute
    try {
        executor.execute(cmdLine);
    } catch (IOException e) {
        scriptOnDisk.delete();
        throw new RScriptException("An error occured while executing Rscript, or the requested script.",
                inputTableAsCsv.toString(), stderr.toString(), stdout.toString(), e);
    }

    // Parse and return the results
    try {
        ImmutableTable<Long, String, Double> table = fromCsv(stdout.toString());
        return new RScriptOutput(table);
    } catch (Throwable t) {
        throw new RScriptException("Failed to parse the script's output.", inputTableAsCsv.toString(),
                stderr.toString(), stdout.toString(), t);
    } finally {
        scriptOnDisk.delete();
    }
}

From source file:org.opennms.netmgt.measurements.impl.RrdtoolXportFetchStrategy.java

/**
 * {@inheritDoc}//  w  w  w .  j a va 2s.  com
 */
@Override
protected FetchResults fetchMeasurements(long start, long end, long step, int maxrows,
        Map<Source, String> rrdsBySource, Map<String, Object> constants) throws RrdException {

    String rrdBinary = System.getProperty("rrd.binary");
    if (rrdBinary == null) {
        throw new RrdException("No RRD binary is set.");
    }

    final long startInSeconds = (long) Math.floor(start / 1000);
    final long endInSeconds = (long) Math.floor(end / 1000);

    long stepInSeconds = (long) Math.floor(step / 1000);
    // The step must be strictly positive
    if (stepInSeconds <= 0) {
        stepInSeconds = 1;
    }

    final CommandLine cmdLine = new CommandLine(rrdBinary);
    cmdLine.addArgument("xport");
    cmdLine.addArgument("--step");
    cmdLine.addArgument("" + stepInSeconds);
    cmdLine.addArgument("--start");
    cmdLine.addArgument("" + startInSeconds);
    cmdLine.addArgument("--end");
    cmdLine.addArgument("" + endInSeconds);
    if (maxrows > 0) {
        cmdLine.addArgument("--maxrows");
        cmdLine.addArgument("" + maxrows);
    }

    // Use labels without spaces when executing the xport command
    // These are mapped back to the requested labels in the response
    final Map<String, String> labelMap = Maps.newHashMap();

    int k = 0;
    for (final Map.Entry<Source, String> entry : rrdsBySource.entrySet()) {
        final Source source = entry.getKey();
        final String rrdFile = entry.getValue();
        final String tempLabel = Integer.toString(++k);
        labelMap.put(tempLabel, source.getLabel());

        cmdLine.addArgument(String.format("DEF:%s=%s:%s:%s", tempLabel, Utils.escapeColons(rrdFile),
                Utils.escapeColons(source.getEffectiveDataSource()), source.getAggregation()));
        cmdLine.addArgument(String.format("XPORT:%s:%s", tempLabel, tempLabel));
    }

    // Use commons-exec to execute rrdtool
    final DefaultExecutor executor = new DefaultExecutor();

    // Capture stdout/stderr
    final ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    final ByteArrayOutputStream stderr = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(stdout, stderr, null));

    // Fail if we get a non-zero exit code
    executor.setExitValue(0);

    // Fail if the process takes too long
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(XPORT_TIMEOUT_MS);
    executor.setWatchdog(watchdog);

    // Export
    RrdXport rrdXport;
    try {
        LOG.debug("Executing: {}", cmdLine);
        executor.execute(cmdLine);

        final XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        final SAXSource source = new SAXSource(xmlReader, new InputSource(new StringReader(stdout.toString())));
        final JAXBContext jc = JAXBContext.newInstance(RrdXport.class);
        final Unmarshaller u = jc.createUnmarshaller();
        rrdXport = (RrdXport) u.unmarshal(source);
    } catch (IOException e) {
        throw new RrdException("An error occured while executing '" + StringUtils.join(cmdLine.toStrings(), " ")
                + "' with stderr: " + stderr.toString(), e);
    } catch (SAXException | JAXBException e) {
        throw new RrdException("The output generated by 'rrdtool xport' could not be parsed.", e);
    }

    final int numRows = rrdXport.getRows().size();
    final int numColumns = rrdXport.getMeta().getLegends().size();
    final long xportStartInMs = rrdXport.getMeta().getStart() * 1000;
    final long xportStepInMs = rrdXport.getMeta().getStep() * 1000;

    final long timestamps[] = new long[numRows];
    final double values[][] = new double[numColumns][numRows];

    // Convert rows to columns
    int i = 0;
    for (final XRow row : rrdXport.getRows()) {
        // Derive the timestamp from the start and step since newer versions
        // of rrdtool no longer include it as part of the rows
        timestamps[i] = xportStartInMs + xportStepInMs * i;
        for (int j = 0; j < numColumns; j++) {
            if (row.getValues() == null) {
                // NMS-7710: Avoid NPEs, in certain cases the list of values may be null
                throw new RrdException(
                        "The output generated by 'rrdtool xport' was not recognized. Try upgrading your rrdtool binaries.");
            }
            values[j][i] = row.getValues().get(j);
        }
        i++;
    }

    // Map the columns by label
    // The legend entries are in the same order as the column values
    final Map<String, double[]> columns = Maps.newHashMapWithExpectedSize(numColumns);
    i = 0;
    for (String label : rrdXport.getMeta().getLegends()) {
        columns.put(labelMap.get(label), values[i++]);
    }

    return new FetchResults(timestamps, columns, xportStepInMs, constants);
}

From source file:org.opennms.web.rest.measurements.fetch.RrdtoolXportFetchStrategy.java

/**
 * {@inheritDoc}//www.j ava  2s  . c o  m
 */
@Override
protected FetchResults fetchMeasurements(long start, long end, long step, int maxrows,
        Map<Source, String> rrdsBySource, Map<String, Object> constants) throws RrdException {

    String rrdBinary = System.getProperty("rrd.binary");
    if (rrdBinary == null) {
        throw new RrdException("No RRD binary is set.");
    }

    final long startInSeconds = (long) Math.floor(start / 1000);
    final long endInSeconds = (long) Math.floor(end / 1000);

    long stepInSeconds = (long) Math.floor(step / 1000);
    // The step must be strictly positive
    if (stepInSeconds <= 0) {
        stepInSeconds = 1;
    }

    final CommandLine cmdLine = new CommandLine(rrdBinary);
    cmdLine.addArgument("xport");
    cmdLine.addArgument("--step");
    cmdLine.addArgument("" + stepInSeconds);
    cmdLine.addArgument("--start");
    cmdLine.addArgument("" + startInSeconds);
    cmdLine.addArgument("--end");
    cmdLine.addArgument("" + endInSeconds);
    if (maxrows > 0) {
        cmdLine.addArgument("--maxrows");
        cmdLine.addArgument("" + maxrows);
    }

    // Use labels without spaces when executing the xport command
    // These are mapped back to the requested labels in the response
    final Map<String, String> labelMap = Maps.newHashMap();

    int k = 0;
    for (final Map.Entry<Source, String> entry : rrdsBySource.entrySet()) {
        final Source source = entry.getKey();
        final String rrdFile = entry.getValue();
        final String tempLabel = Integer.toString(++k);
        labelMap.put(tempLabel, source.getLabel());

        cmdLine.addArgument(String.format("DEF:%s=%s:%s:%s", tempLabel, rrdFile, source.getAttribute(),
                source.getAggregation()));
        cmdLine.addArgument(String.format("XPORT:%s:%s", tempLabel, tempLabel));
    }

    // Use commons-exec to execute rrdtool
    final DefaultExecutor executor = new DefaultExecutor();

    // Capture stdout/stderr
    final ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    final ByteArrayOutputStream stderr = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(stdout, stderr, null));

    // Fail if we get a non-zero exit code
    executor.setExitValue(0);

    // Fail if the process takes too long
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(XPORT_TIMEOUT_MS);
    executor.setWatchdog(watchdog);

    // Export
    RrdXport rrdXport;
    try {
        executor.execute(cmdLine);

        final XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        final SAXSource source = new SAXSource(xmlReader, new InputSource(new StringReader(stdout.toString())));
        final JAXBContext jc = JAXBContext.newInstance(RrdXport.class);
        final Unmarshaller u = jc.createUnmarshaller();
        rrdXport = (RrdXport) u.unmarshal(source);
    } catch (IOException e) {
        throw new RrdException("An error occured while executing '" + StringUtils.join(cmdLine.toStrings(), " ")
                + "' with stderr: " + stderr.toString(), e);
    } catch (SAXException | JAXBException e) {
        throw new RrdException("The output generated by 'rrdtool xport' could not be parsed.", e);
    }

    final int numRows = rrdXport.getRows().size();
    final int numColumns = rrdXport.getMeta().getLegends().size();

    final long timestamps[] = new long[numRows];
    final double values[][] = new double[numColumns][numRows];

    // Convert rows to columns
    int i = 0;
    for (final XRow row : rrdXport.getRows()) {
        timestamps[i] = row.getTimestamp() * 1000;
        for (int j = 0; j < numColumns; j++) {
            if (row.getValues() == null) {
                // NMS-7710: Avoid NPEs, in certain cases the list of values may be null
                throw new RrdException(
                        "The output generated by 'rrdtool xport' was not recognized. Try upgrading your rrdtool binaries.");
            }
            values[j][i] = row.getValues().get(j);
        }
        i++;
    }

    // Map the columns by label
    // The legend entries are in the same order as the column values
    final Map<String, double[]> columns = Maps.newHashMapWithExpectedSize(numColumns);
    i = 0;
    for (String label : rrdXport.getMeta().getLegends()) {
        columns.put(labelMap.get(label), values[i++]);
    }

    return new FetchResults(timestamps, columns, rrdXport.getMeta().getStep() * 1000, constants);
}

From source file:org.sikuli.natives.CommandExecutorHelper.java

public static CommandExecutorResult execute(String commandString, int expectedExitValue) throws Exception {
    ByteArrayOutputStream error = new ByteArrayOutputStream();
    ByteArrayOutputStream stout = new ByteArrayOutputStream();
    CommandLine cmd = CommandLine.parse(commandString);
    try {//from  w w w. j  av a2 s.c o m
        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()));
    }
}

From source file:org.sikuli.natives.LinuxUtil.java

@Override
public void checkLibAvailability() {
    List<CommandLine> commands = Arrays.asList(CommandLine.parse("wmctrl -m"),
            CommandLine.parse("xdotool version"), CommandLine.parse("killall --version"));
    String msg = "";
    for (CommandLine cmd : commands) {
        try {//from  w  ww  .  j a v  a2s .c om
            DefaultExecutor executor = new DefaultExecutor();
            executor.setExitValue(0);
            //suppress system output
            executor.setStreamHandler(new PumpStreamHandler(null));
            executor.execute(cmd);
        } catch (IOException e) {
            String executable = cmd.toStrings()[0];
            if (executable.equals("wmctrl")) {
                wmctrlAvail = false;
            }
            if (executable.equals("xdotool")) {
                xdoToolAvail = false;
            }
            msg += "command '" + executable + "' is not executable\n";
        }
    }
    if (!msg.isEmpty()) {
        msg += "Please check the availability - some features might not work without!";
        Debug.error(msg);
    }
}

From source file:org.sonar.plugins.ideainspections.IdeaExecutor.java

/**
 * Execute Idea Inspections and return the generated XML report.
 * @return File a directory with the inspection results or null if the project was not found
 *//*from w  ww. jav a2  s . c o m*/
public File execute() {
    if (!project.exists()) {
        LOG.info("Cannot find: " + project + ". Skipping...");
        return null;
    }

    TimeProfiler profiler = new TimeProfiler().start("Execute Idea Inspections " + IdeaVersion.getVersion());

    CommandLine cmdLine = new CommandLine(jdkHome + "/bin/java");

    cmdLine.addArgument("-XX:-UseGCOverheadLimit");
    cmdLine.addArgument("-Xmx" + memory);
    cmdLine.addArgument("-XX:MaxPermSize=" + permSize);
    cmdLine.addArgument("-Xbootclasspath/a:" + bootJar.getPath());

    cmdLine.addArgument("-Djdk." + jdkName + "=" + jdkHome);
    cmdLine.addArgument("-cp");
    cmdLine.addArgument(buildClassPath());
    cmdLine.addArgument(IDEA_MAIN_CLASS_NAME);
    cmdLine.addArgument("inspect");
    cmdLine.addArgument(project.getPath());
    cmdLine.addArgument(profile.getPath());
    cmdLine.addArgument(reportDirectory.getPath());
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);

    //ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    //executor.setWatchdog(watchdog);
    try {
        LOG.info("About to execute: \n" + cmdLine.toString());
        executor.execute(cmdLine);
    } catch (Exception e) {
        throw new SonarException("Can not execute Idea Inspections", e);
    } finally {
        profiler.stop();
    }
    return reportDirectory;
}

From source file:org.wisdom.maven.node.NPM.java

/**
 * Executes the current NPM.//from  w  w w .  j ava 2  s  .  co  m
 * NPM can have several executable attached to them, so the 'binary' argument specifies which
 * one has to be executed. Check the 'bin' entry of the package.json file to determine which
 * one you need. 'Binary' is the key associated with the executable to invoke. For example, in
 * <code>
 * <pre>
 *      "bin": {
 *           "coffee": "./bin/coffee",
 *           "cake": "./bin/cake"
 *      },
 *     </pre>
 * </code>
 * <p/>
 * we have two alternatives: 'coffee' and 'cake'.
 *
 * @param binary the key of the binary to invoke
 * @param args   the arguments
 * @return the execution exit status
 * @throws MojoExecutionException if the execution failed
 */
public int execute(String binary, String... args) throws MojoExecutionException {
    File destination = getNPMDirectory();
    if (!destination.isDirectory()) {
        throw new IllegalStateException("The npm module " + this.npmName + " is not installed");
    }

    CommandLine cmdLine = new CommandLine(node.getNodeExecutable());
    File npmExec = null;
    try {
        npmExec = findExecutable(binary);
    } catch (IOException | ParseException e) { //NOSONAR
        log.error(e);
    }
    if (npmExec == null) {
        throw new IllegalStateException(
                "Cannot execute NPM " + this.npmName + " - cannot find the JavaScript file " + "matching "
                        + binary + " in the " + PACKAGE_JSON + " file");
    }

    // NPM is launched using the main file.
    cmdLine.addArgument(npmExec.getAbsolutePath(), false);
    for (String arg : args) {
        cmdLine.addArgument(arg, this.handleQuoting);
    }

    DefaultExecutor executor = new DefaultExecutor();

    executor.setExitValue(0);

    errorStreamFromLastExecution = new LoggedOutputStream(log, true, true);
    outputStreamFromLastExecution = new LoggedOutputStream(log, false, registerOutputStream);
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStreamFromLastExecution,
            errorStreamFromLastExecution);

    executor.setStreamHandler(streamHandler);
    executor.setWorkingDirectory(node.getWorkDir());
    log.info("Executing " + cmdLine.toString() + " from " + executor.getWorkingDirectory().getAbsolutePath());

    try {
        return executor.execute(cmdLine, extendEnvironmentWithNodeInPath(node));
    } catch (IOException e) {
        throw new MojoExecutionException("Error during the execution of the NPM " + npmName, e);
    }

}

From source file:org.wisdom.maven.node.NPM.java

/**
 * Executes the current NPM using the given binary file.
 *
 * @param binary the program to run/*  ww w  .  j  ava2s.c o  m*/
 * @param args   the arguments
 * @return the execution exit status
 * @throws MojoExecutionException if the execution failed
 */
public int execute(File binary, String... args) throws MojoExecutionException {
    File destination = getNPMDirectory();
    if (!destination.isDirectory()) {
        throw new IllegalStateException("NPM " + this.npmName + " not installed");
    }

    CommandLine cmdLine = new CommandLine(node.getNodeExecutable());

    if (binary == null) {
        throw new IllegalStateException(
                "Cannot execute NPM " + this.npmName + " - the given binary is 'null'.");
    }

    if (!binary.isFile()) {
        throw new IllegalStateException("Cannot execute NPM " + this.npmName + " - the given binary does not "
                + "exist: " + binary.getAbsoluteFile() + ".");
    }

    // NPM is launched using the main file.
    cmdLine.addArgument(binary.getAbsolutePath(), false);
    for (String arg : args) {
        cmdLine.addArgument(arg, this.handleQuoting);
    }

    DefaultExecutor executor = new DefaultExecutor();

    executor.setExitValue(0);

    errorStreamFromLastExecution = new LoggedOutputStream(log, true, true);
    outputStreamFromLastExecution = new LoggedOutputStream(log, false, registerOutputStream);

    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStreamFromLastExecution,
            errorStreamFromLastExecution);

    executor.setStreamHandler(streamHandler);
    executor.setWorkingDirectory(node.getWorkDir());
    log.info("Executing " + cmdLine.toString() + " from " + executor.getWorkingDirectory().getAbsolutePath());

    try {
        return executor.execute(cmdLine, extendEnvironmentWithNodeInPath(node));
    } catch (IOException e) {
        throw new MojoExecutionException("Error during the execution of the NPM " + npmName, e);
    }

}