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:de.jsurf.http.HttpServerHandler.java

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {

    HttpRequest request = (HttpRequest) e.getMessage();
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    response.setContent(ChannelBuffers.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));
    response.setHeader(CONTENT_TYPE, "video/mpts");
    /*response.setChunked(true);
    response.setHeader(Names.TRANSFER_ENCODING, Values.CHUNKED);*/

    Channel c = e.getChannel();//from ww  w .j a va2s.co  m

    // create a media reader
    String inputStream = HttpServerConfiguration.getConfiguration().getChannelInput(request.getUri());

    if (inputStream == null) {
        response = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND);
        ChannelFuture future = c.write(response);
        future.addListener(ChannelFutureListener.CLOSE);
        return;
    }

    String path = new java.io.File(".").getCanonicalPath();
    log.debug("Current execution path: " + path);

    String[] parameters = new String[] { "-loglevel", "error", "-i", inputStream, "-vcodec", "copy", "-acodec",
            "copy", "-vbsf", "h264_mp4toannexb", "-f", "mpegts", "pipe:1" };

    CommandLine cmdLine = CommandLine.parse("ffmpeg.exe");
    cmdLine.addArguments(parameters);
    DefaultExecutor executor = new DefaultExecutor();
    final ExecuteWatchdog watchDog = new ExecuteWatchdog(86400000); // One day timeout          
    executor.setWatchdog(watchDog);

    PipedInputStream pin = new PipedInputStream();
    PipedOutputStream pout = new PipedOutputStream(pin);

    PumpStreamHandler streamHandler = new PumpStreamHandler(pout, System.err);
    executor.setStreamHandler(streamHandler);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    executor.execute(cmdLine, resultHandler);

    c.write(response);
    InputStream in = new BufferedInputStream(pin);
    ChannelFuture future = c.write(new ChunkedStream(in));

    future.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            try {
                log.debug("operationComplete: closeChannel");
                future.getChannel().close();
            } catch (Exception e) {

            }
            log.debug("operationComplete: Destroy ffmpeg process");
            watchDog.destroyProcess();
        }
    });
}

From source file:io.vertx.config.vault.utils.VaultProcess.java

private void startServer() {
    String line = executable.getAbsolutePath() + " server -config=src/test/resources/config.json";
    System.out.println(">> " + line);
    CommandLine parse = CommandLine.parse(line);
    DefaultExecutor executor = new DefaultExecutor();
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    AtomicBoolean ready = new AtomicBoolean();
    PumpStreamHandler pump = new PumpStreamHandler(new VaultOutputStream().addExtractor(l -> {
        if (l.contains("Vault server started!")) {
            ready.set(true);//from  w w  w  . j a va 2 s.c  om
        }
    }), System.err);

    watchDog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchDog);
    executor.setStreamHandler(pump);
    try {
        executor.execute(parse, resultHandler);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    await().untilAtomic(ready, is(true));
    System.out.println("Vault Server ready - but not yet initialized");
}

From source file:com.blackducksoftware.tools.scmconnector.integrations.teamfoundation.TeamFoundationConnector.java

private int createWorkpace() {
    CommandLine command = CommandLine.parse(executable);

    String[] arguments = new String[] { "workspace", "-new", "-collection:" + server + "/" + collection,
            "-login:" + user + "," + password, workspace };

    command.addArguments(arguments, false);

    int exitStatus = 1;

    try {//  ww  w  .  java2  s  .  co m
        exitStatus = commandLineExecutor.executeCommand(log, command, new File(getFinalSourceDirectory()));

    } catch (Exception e) {

        log.error("Failure executing TF Command", e);
    }

    return exitStatus;
}

From source file:com.cws.esolutions.agent.processors.impl.ServiceCheckProcessorImpl.java

public ServiceCheckResponse runSystemCheck(final ServiceCheckRequest request) throws ServiceCheckException {
    final String methodName = IServiceCheckProcessor.CNAME
            + "#runSystemCheck(final ServiceCheckRequest request) throws ServiceCheckException";

    if (DEBUG) {//from w  w w.ja v a  2  s. c o  m
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("ServiceCheckRequest: {}", request);
    }

    int exitCode = -1;
    Socket socket = null;
    File sourceFile = null;
    CommandLine command = null;
    BufferedWriter writer = null;
    ExecuteStreamHandler streamHandler = null;
    ByteArrayOutputStream outputStream = null;
    ServiceCheckResponse response = new ServiceCheckResponse();

    final DefaultExecutor executor = new DefaultExecutor();
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(CONNECT_TIMEOUT * 1000);
    final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    try {
        switch (request.getRequestType()) {
        case NETSTAT:
            sourceFile = scriptConfig.getScripts().get("netstat");

            if (DEBUG) {
                DEBUGGER.debug("sourceFile: {}", sourceFile);
            }

            if (!(sourceFile.canExecute())) {
                throw new ServiceCheckException(
                        "Script file either does not exist or cannot be executed. Cannot continue.");
            }

            command = CommandLine.parse(sourceFile.getAbsolutePath());

            if (request.getPortNumber() != 0) {
                command.addArgument(String.valueOf(request.getPortNumber()), true);
            }

            if (DEBUG) {
                DEBUGGER.debug("CommandLine: {}", command);
            }

            outputStream = new ByteArrayOutputStream();
            streamHandler = new PumpStreamHandler(outputStream);

            executor.setWatchdog(watchdog);
            executor.setStreamHandler(streamHandler);

            if (DEBUG) {
                DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler);
                DEBUGGER.debug("ExecuteWatchdog: {}", watchdog);
                DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler);
                DEBUGGER.debug("DefaultExecutor: {}", executor);
            }

            executor.execute(command, resultHandler);

            resultHandler.waitFor();
            exitCode = resultHandler.getExitValue();

            if (DEBUG) {
                DEBUGGER.debug("exitCode: {}", exitCode);
            }

            writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + sourceFile.getName() + ".log"));
            writer.write(outputStream.toString());
            writer.flush();

            response.setResponseData(outputStream.toString());

            if (executor.isFailure(exitCode)) {
                response.setRequestStatus(AgentStatus.FAILURE);
            } else {
                response.setRequestStatus(AgentStatus.SUCCESS);
            }

            break;
        case REMOTEDATE:
            response.setRequestStatus(AgentStatus.SUCCESS);
            response.setResponseData(System.currentTimeMillis());

            break;
        case TELNET:
            response = new ServiceCheckResponse();

            int targetPort = request.getPortNumber();
            String targetServer = request.getTargetHost();

            if (DEBUG) {
                DEBUGGER.debug("Target port: {}", targetPort);
                DEBUGGER.debug("Target server: {}", targetServer);
            }

            if (targetPort == 0) {
                throw new ServiceCheckException("Target port number was not assigned. Cannot action request.");
            }

            final String CRLF = "\r\n";
            final String TERMINATE_TELNET = "^]";

            synchronized (new Object()) {
                InetSocketAddress socketAddress = new InetSocketAddress(targetServer, targetPort);

                socket = new Socket();
                socket.setSoTimeout(IServiceCheckProcessor.CONNECT_TIMEOUT);
                socket.setSoLinger(false, 0);
                socket.setKeepAlive(false);

                try {
                    socket.connect(socketAddress, IServiceCheckProcessor.CONNECT_TIMEOUT);

                    if (!(socket.isConnected())) {
                        throw new ConnectException("Failed to connect to host " + targetServer + " on port "
                                + request.getPortNumber());
                    }

                    PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true);
                    pWriter.println(TERMINATE_TELNET + CRLF);
                    pWriter.flush();
                    pWriter.close();

                    response.setRequestStatus(AgentStatus.SUCCESS);
                    response.setResponseData("Telnet connection to " + targetServer + " on port "
                            + request.getPortNumber() + " successful.");
                } catch (ConnectException cx) {
                    response.setRequestStatus(AgentStatus.FAILURE);
                    response.setResponseData("Telnet connection to " + targetServer + " on port "
                            + request.getPortNumber() + " failed with message: " + cx.getMessage());
                }
            }

            break;
        case PROCESSLIST:
            sourceFile = scriptConfig.getScripts().get("processList");

            if (DEBUG) {
                DEBUGGER.debug("sourceFile: {}", sourceFile);
            }

            if (!(sourceFile.canExecute())) {
                throw new ServiceCheckException(
                        "Script file either does not exist or cannot be executed. Cannot continue.");
            }

            command = CommandLine.parse(sourceFile.getAbsolutePath());

            if (request.getPortNumber() != 0) {
                command.addArgument(String.valueOf(request.getPortNumber()), true);
            }

            if (DEBUG) {
                DEBUGGER.debug("CommandLine: {}", command);
            }

            outputStream = new ByteArrayOutputStream();
            streamHandler = new PumpStreamHandler(outputStream);

            executor.setWatchdog(watchdog);
            executor.setStreamHandler(streamHandler);

            if (DEBUG) {
                DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler);
                DEBUGGER.debug("ExecuteWatchdog: {}", watchdog);
                DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler);
                DEBUGGER.debug("DefaultExecutor: {}", executor);
            }

            executor.execute(command, resultHandler);

            resultHandler.waitFor();
            exitCode = resultHandler.getExitValue();

            if (DEBUG) {
                DEBUGGER.debug("exitCode: {}", exitCode);
            }

            writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + sourceFile.getName() + ".log"));
            writer.write(outputStream.toString());
            writer.flush();

            response.setResponseData(outputStream.toString());

            if (executor.isFailure(exitCode)) {
                response.setRequestStatus(AgentStatus.FAILURE);
            } else {
                response.setRequestStatus(AgentStatus.SUCCESS);
            }

            break;
        default:
            // unknown operation
            throw new ServiceCheckException("No valid operation was specified");
        }
    } catch (UnknownHostException uhx) {
        ERROR_RECORDER.error(uhx.getMessage(), uhx);

        throw new ServiceCheckException(uhx.getMessage(), uhx);
    } catch (SocketException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        throw new ServiceCheckException(sx.getMessage(), sx);
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new ServiceCheckException(iox.getMessage(), iox);
    } catch (InterruptedException ix) {
        ERROR_RECORDER.error(ix.getMessage(), ix);

        throw new ServiceCheckException(ix.getMessage(), ix);
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }

            if ((socket != null) && (!(socket.isClosed()))) {
                socket.close();
            }
        } catch (IOException iox) {
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }

    return response;
}

From source file:com.blackducksoftware.tools.scmconnector.integrations.mercurial.MercurialConnector.java

@Override
public int sync() {

    int exitStatus = -1;

    CommandLine command = CommandLine.parse(EXECUTABLE);

    String sourceDirIncludingModule = addPathComponentToPath(getFinalSourceDirectory(),
            getModuleNameFromURL(repositoryURL));
    File dir = new File(sourceDirIncludingModule);

    if (localWorkingCopyExists(dir, ".hg", getModuleNameFromURL(repositoryURL))) {

        command.addArgument("pull");
        command.addArgument("-u");

    } else {//from  w  w  w . ja v a 2  s.c o m
        // Need to adjust the working dir for Mercury checkout: must not
        // include the module dir part
        sourceDirIncludingModule = getFinalSourceDirectory();
        dir = new File(sourceDirIncludingModule);

        command.addArgument("clone");
        command.addArgument(repositoryURL);

    }

    try {
        exitStatus = commandLineExecutor.executeCommand(log, command, dir);
    } catch (Exception e) {
        log.error("Problem performing command", e);
    }

    return exitStatus;
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.svmlib.SVMLibExperimentRunner.java

public static void runCommand(String command) throws IOException {
    CommandLine cmdLine = CommandLine.parse(command);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);//from  w ww  .  j  av  a2 s  .co  m

    // set one hour limit for training
    ExecuteWatchdog watchdog = new ExecuteWatchdog(1000 * 60 * 60);
    executor.setWatchdog(watchdog);

    System.out.println("Running\n" + command);

    int exitValue = executor.execute(cmdLine);
}

From source file:com.github.trecloux.yeoman.YeomanMojo.java

void executeCommand(String command) throws MojoExecutionException {
    try {//from   w w  w. ja va2  s  .  c om
        if (isWindows()) {
            command = "cmd /c " + command;
        }
        CommandLine cmdLine = CommandLine.parse(command);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setWorkingDirectory(yeomanProjectDirectory);
        executor.execute(cmdLine);
    } catch (IOException e) {
        throw new MojoExecutionException("Error during : " + command, e);
    }
}

From source file:com.cws.esolutions.agent.processors.impl.ApplicationManagerProcessorImpl.java

/**
 * @see com.cws.esolutions.agent.processors.interfaces.IApplicationManagerProcessor#installApplication(com.cws.esolutions.agent.processors.dto.ApplicationManagerRequest)
 *///from w  w  w  .  j  av  a2s.  c  o m
public ApplicationManagerResponse installApplication(final ApplicationManagerRequest request)
        throws ApplicationManagerException {
    final String methodName = IApplicationManagerProcessor.CNAME
            + "#installApplication(final ApplicationManagerRequest request) throws ApplicationManagerException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("ApplicationManagerRequest: {}", request);
    }

    BufferedWriter writer = null;
    ApplicationManagerResponse response = new ApplicationManagerResponse();

    final double version = request.getVersion();
    final DefaultExecutor executor = new DefaultExecutor();
    final String installerOptions = request.getInstallerOptions();
    final File installPath = FileUtils.getFile(request.getInstallPath());
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(CONNECT_TIMEOUT * 1000);
    final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    final File packageInstaller = FileUtils.getFile(request.getPackageInstaller());

    if (DEBUG) {
        DEBUGGER.debug("double: {}", version);
        DEBUGGER.debug("DefaultExecutor: {}", executor);
        DEBUGGER.debug("String: {}", installerOptions);
        DEBUGGER.debug("File: {}", installPath);
        DEBUGGER.debug("ExecuteWatchdog: {}", watchdog);
        DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler);
        DEBUGGER.debug("File:{}", packageInstaller);
    }

    try {
        if (!(packageInstaller.canExecute())) {
            throw new ApplicationManagerException("Unable to execute package installer. Cannot continue.");
        }

        if (!(installPath.canWrite()) && (!(installPath.mkdirs()))) {
            throw new ApplicationManagerException("Unable to create installation target. Cannot continue.");
        }

        CommandLine command = CommandLine.parse(packageInstaller.getAbsolutePath());
        command.addArgument(installerOptions, false);
        command.addArgument(request.getPackageLocation(), false);

        if (DEBUG) {
            DEBUGGER.debug("CommandLine: {}", command);
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ExecuteStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        streamHandler.start();

        executor.setWatchdog(watchdog);
        executor.setStreamHandler(streamHandler);

        if (DEBUG) {
            DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler);
            DEBUGGER.debug("ExecuteWatchdog: {}", watchdog);
            DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler);
            DEBUGGER.debug("DefaultExecutor: {}", executor);
        }

        executor.execute(command, resultHandler);

        resultHandler.waitFor();
        int exitCode = resultHandler.getExitValue();

        writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + request.getPackageName() + ".log"));
        writer.write(outputStream.toString());
        writer.flush();

        if (DEBUG) {
            DEBUGGER.debug("exitCode: {}", exitCode);
        }

        if (executor.isFailure(exitCode)) {
            throw new ApplicationManagerException("Application installation failed: Result Code: " + exitCode);
        }

        response.setResponse(outputStream.toString());
        response.setRequestStatus(AgentStatus.SUCCESS);
    } catch (ExecuteException eex) {
        ERROR_RECORDER.error(eex.getMessage(), eex);

        throw new ApplicationManagerException(eex.getMessage(), eex);
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new ApplicationManagerException(iox.getMessage(), iox);
    } catch (InterruptedException ix) {
        ERROR_RECORDER.error(ix.getMessage(), ix);

        throw new ApplicationManagerException(ix.getMessage(), ix);
    } finally {
        try {
            writer.close();
        } catch (IOException iox) {
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }

    return response;
}

From source file:com.blackducksoftware.tools.scmconnector.integrations.teamfoundation.TeamFoundationConnector.java

private int mapWorkpace() {
    CommandLine command = CommandLine.parse(executable);

    command.addArgument("workfold", false);
    command.addArgument("-map", false);
    command.addArgument("-workspace:" + workspace, false);
    command.addArgument("-login:" + user + "," + password, false);
    command.addArgument("$" + view, false); // Don't mess with quoting
    command.addArgument(getFinalSourceDirectory(), false);

    int exitStatus = 1;

    try {/*w w  w. j av a2 s  .co m*/
        exitStatus = commandLineExecutor.executeCommand(log, command, new File(getFinalSourceDirectory()));

    } catch (Exception e) {

        log.error("Failure executing TF Command", e);
    }
    return exitStatus;

}

From source file:com.blackducksoftware.tools.scmconnector.integrations.subversion.SubversionConnector.java

@Override
public int sync() {

    int exitStatus = -1;

    try {//from www.  ja v a 2 s.c o m
        File targetDir = new File(getFinalSourceDirectory());

        CommandLine command = CommandLine.parse(EXECUTABLE);

        if (!repoExists(targetDir)) {
            command.addArgument("co");
            command.addArgument(repositoryURL);
        } else {
            command.addArgument("up");
        }

        // now add destination
        // command.addArgument(targetDir.getAbsolutePath());
        if (user != null && !user.isEmpty()) {
            command.addArgument("--username");
            command.addArgument(user);
            if (!password.isEmpty()) {
                command.addArgument("--password");
                command.addArgument(password);
            }
        }

        command.addArgument("--non-interactive");

        for (String svnFlag : svnFlagsList) {
            command.addArgument(svnFlag);
        }

        exitStatus = commandLineExecutor.executeCommand(log, command, targetDir);

    } catch (Exception e) {
        log.error("Unable to perform sync: " + e.getMessage());
    }
    return exitStatus;
}