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

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

Introduction

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

Prototype

public static CommandLine parse(final String line) 

Source Link

Document

Create a command line from a string.

Usage

From source file:org.nanoko.playframework.mojo.Play2StartMojo.java

public void execute() throws MojoExecutionException {

    String line = getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);
    cmdLine.addArguments(getPlay2SystemPropertiesArguments(), false);
    cmdLine.addArgument("start");
    System.out.println(cmdLine.toString());
    DefaultExecutor executor = new DefaultExecutor();

    // As where not linked to a project, we can't set the working directory.
    // So it will use the directory where mvn was launched.

    executor.setExitValue(0);/*from   www .ja  v  a 2s.co  m*/
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        // Ignore.
    }
}

From source file:org.nanoko.playframework.mojo.Play2StopMojo.java

public void execute() throws MojoExecutionException {

    String line = getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);
    cmdLine.addArguments(getPlay2SystemPropertiesArguments(), false);
    cmdLine.addArgument("stop");
    System.out.println(cmdLine.toString());
    DefaultExecutor executor = new DefaultExecutor();

    // As where not linked to a project, we can't set the working directory.
    // So it will use the directory where mvn was launched.

    executor.setExitValue(0);/*  w  ww.  j a  va2 s.c  om*/
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        // Ignore.
    }
}

From source file:org.nanoko.playframework.mojo.Play2TestMojo.java

public void execute() throws MojoExecutionException {

    if (isSkipExecution()) {
        getLog().info("Test phase skipped");
        return;// ww w.j  a va 2  s.  com
    }

    if (noTestFound()) {
        getLog().info("Test phase skipped - no tests found");
        return;
    }

    String line = getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);
    cmdLine.addArguments(getPlay2SystemPropertiesArguments(), false);
    cmdLine.addArgument("test");
    DefaultExecutor executor = new DefaultExecutor();

    if (timeout > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        executor.setWatchdog(watchdog);
    }

    executor.setWorkingDirectory(project.getBasedir());

    executor.setExitValue(0);
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        if (testFailureIgnore) {
            getLog().error("Test execution failures ignored");
        } else {
            throw new MojoExecutionException("Error during compilation", e);
        }
    }
}

From source file:org.nps.autopsypycaffe.NPSPyCaffeFactory.java

public NPSPyCaffeFactory() {
    IngestServices services = IngestServices.getInstance();
    props = new Properties();
    //The user directory is where the plugin got installed
    File userDir = PlatformUtil.getUserDirectory();
    basePath = userDir.toString();/* www . j  a  va 2s. c o  m*/
    // Search for all directories in the detectors directory.  This is the list
    // of all the detector types.
    if (new File(basePath + "/NPSPyCaffe/detectors").exists() == false) {
        // When we run in the netbeans debugger basePath is up two directories
        basePath = basePath + "/../../release/NPSPyCaffe/detectors/";
    } else
        basePath = basePath + "/NPSPyCaffe/detectors/";
    String[] dlist = new File(basePath).list();
    for (String name : dlist) {
        if (new File(basePath + name).isDirectory()) {
            detectorTypes.add(name);
        }
    }
    if (detectorTypes.size() == 0) {
        IngestMessage msg = IngestMessage.createErrorMessage(NPSPyCaffeFactory.getModuleName(),
                "Congigure Error!", "No Detector types found!");
        services.postMessage(msg);
    } else
        for (String det : detectorTypes) {
            String[] plist = new File(basePath + det).list();
            for (String name : plist) {
                if (name.endsWith(".properties")) {
                    // Read anything that ends with .properties
                    File propfile = new File(basePath + det + "/" + name);
                    if (propfile.exists() == true) {
                        try {
                            FileInputStream in = new FileInputStream(propfile);
                            props.load(in);
                            in.close();
                            if (name.equals("detector.properties")) {
                                // main property file describing the detector type
                                boolean gpu = checkForGPU(det);
                                hasGPU.put(det, gpu);
                            } else {
                                // specific detector property file so use name of file as detector name
                                int idx = name.indexOf(".properties");
                                String detName = name.substring(0, idx);
                                detectorNames.add(det + "." + detName);
                            }
                        } catch (FileNotFoundException ex) {
                            logger.log(Level.SEVERE, "Could not Find detector.properties file");
                        } catch (IOException ex) {
                            logger.log(Level.SEVERE, ex.getMessage());
                        }
                    }
                }
            }

            for (String name : plist) {
                if (name.endsWith(".properties")) {

                }
            }
        }
    // Find Python Exec
    try {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        CommandLine args = CommandLine.parse("where.exe");
        args.addArgument("python");
        DefaultExecutor exec = new DefaultExecutor();
        PumpStreamHandler stdpump = new PumpStreamHandler(outStream);
        exec.setStreamHandler(stdpump);
        exec.execute(args);
        String whereOut = outStream.toString();
        String[] lines = StringUtils.split(whereOut, "\r\n");
        pythonExec = lines[0];

    } catch (IOException ex) {
    }

}

From source file:org.nuxeo.webpage.archiver.WebpageToBlob.java

protected Blob buildCommandLineAndRun(String inCommandLine, CmdParameters inParams, String inFileName,
        boolean inUseAllParams) throws IOException, CommandNotAvailable, NuxeoException {

    // Create a temp. File handled by Nuxeo
    Blob resultPdf = Blobs.createBlobWithExtension(".pdf");

    // Build the full, resolved command line
    String resolvedParameterString = CommandLineParameters.buildParameterString(inCommandLine,
            inParams.getParameter(CommandLineParameters.COOKIE_JAR),
            inParams.getParameter(CommandLineParameters.URL), resultPdf.getFile().getAbsolutePath());

    // Mainly during test, we may have uncjecked parameters (safe because everything is hard-coded server side)
    if (inUseAllParams) {
        if (!Framework.isTestModeSet()) {
            throw new NuxeoException("A call to buildCommandLineAndRun(..., true) is for test only.");
        }/*from ww w . j a  v a  2  s .c o m*/
        Map<String, ParameterValue> allParams = inParams.getParameters();
        String key, value;
        for (Entry<String, ParameterValue> entry : allParams.entrySet()) {
            key = entry.getKey();
            value = entry.getValue().getValue();
            if (!CommandLineParameters.isHandledParameter(key)) {
                resolvedParameterString = StringUtils.replace(resolvedParameterString, "#{" + key + "}", value);
            }
        }
    }

    // Get the exact command line and build the line
    CommandLineDescriptor desc = CommandLineExecutorComponent.getCommandDescriptor(inCommandLine);
    String line = desc.getCommand() + " " + resolvedParameterString;

    // Run the thing
    Exception exception = null;

    CommandLine cmdLine = CommandLine.parse(line);
    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    // We don't want a check on exit values, because a PDF can still be created with errors
    // (can't get a font, ...)
    executor.setExitValues(null);
    executor.setWatchdog(watchdog);
    int exitValue = 0;
    try {
        exitValue = executor.execute(cmdLine);
    } catch (IOException e) {
        exception = e;
    }

    // Even if we had no error catched, we must check if the pdf is valid.
    // Exit value may be 1, or non zero while the pdf was created. But maybe
    // a font could not be correctly rendered, etc. Let's check if we have
    // something in the pdf and it looks valid
    if (!pdfLooksValid(resultPdf.getFile())) {
        resultPdf = null;
        String msg = "Failed to execute the command line [" + cmdLine.toString()
                + " ]. No valid PDF generated. exitValue: " + exitValue;

        if (exitValue == 143) { // On Linux: Timeout, wkhtmltopdf was SIGTERM
            msg += " (time out reached. The timeout was " + timeout + "ms)";
        }
        if (exception == null) {
            throw new NuxeoException(msg);
        } else {
            throw new NuxeoException(msg, exception);
        }
    }

    resultPdf.setMimeType("application/pdf");
    String url = inParams.getParameter(CommandLineParameters.URL);
    // Url parameter can be blank (hard coded url in the command line XML for example)
    if (StringUtils.isBlank(inFileName) && StringUtils.isNotBlank(url)) {
        try {
            URL urlObj = new URL(url);
            inFileName = StringUtils.replace(urlObj.getHost(), ".", "-") + ".pdf";
        } finally {
            // Nothing. Default name has been set by nuxeo
        }
    }
    if (StringUtils.isNotBlank(inFileName)) {
        resultPdf.setFilename(inFileName);
    }

    return resultPdf;
}

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);
    }// w ww. j  a v a2 s.  com

    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.openflamingo.engine.util.FileReader.java

/**
 * ? ??  ??  ? ? .//from   w w w  .ja  va  2 s .co m
 *
 * @param start     ??
 * @param end       ??
 * @param filename ?? ?
 * @return ?? 
 * @throws IOException          ?? ??   
 * @throws InterruptedException       
 */
public static String read(long start, long end, String filename) throws IOException, InterruptedException {
    String command = org.slf4j.helpers.MessageFormatter
            .arrayFormat("sed '{},{}!d' {}", new Object[] { start, end, filename }).getMessage();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(out);

    CommandLine cmdLine = CommandLine.parse(command);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(pumpStreamHandler);
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    executor.execute(cmdLine, resultHandler);

    resultHandler.waitFor();

    return new String(out.toByteArray());
}

From source file:org.openflamingo.engine.util.FileReader.java

/**
 * ? ?? ??  ? .//  w w w .ja va  2s. co  m
 *
 * @param filename ??  ? ?
 * @return  ?? ?? 
 * @throws IOException          ?? ??   
 * @throws InterruptedException       
 */
public static int lines(String filename) throws IOException, InterruptedException {
    String command = org.slf4j.helpers.MessageFormatter.arrayFormat("sed -n '$=' {}", new Object[] { filename })
            .getMessage();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(out);

    CommandLine cmdLine = CommandLine.parse(command);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(pumpStreamHandler);
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    executor.execute(cmdLine, resultHandler);

    resultHandler.waitFor();

    return Integer.parseInt(new String(out.toByteArray()).trim());
}

From source file:org.openhab.binding.exec.internal.ExecBinding.java

/**
 * <p>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>/*from www  . j av  a 2  s  . co  m*/
 * <p>A possible {@link IOException} gets logged but no further processing is
 * done.</p> 
 * 
 * @param commandLine the command line to execute
 * @return response data from executed command line 
 */
private String executeCommandAndWaitResponse(String commandLine) {
    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());
        logger.debug("exit code '{}', result '{}'", exitCode, retval);

    } catch (InterruptedException e) {
        logger.error("Timeout occured when executing commandLine '" + commandLine + "'", e);
    }

    return retval;
}

From source file:org.openhab.io.net.exec.ExecUtil.java

/**
 * <p>//from   w  w  w . j  a v  a  2s . c o  m
 * 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>
 * <p>
 * A possible {@link IOException} gets logged but no further processing is
 * done.
 * </p>
 * 
 * @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;
}