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

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

Introduction

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

Prototype

public CommandLine addArguments(final String addArguments) 

Source Link

Document

Add multiple arguments.

Usage

From source file:net.orpiske.sdm.lib.Executable.java

/**
 * Executes a command//  w w  w.j  a  v  a 2  s .  co  m
 * @param command the command to execute
 * @param arguments the arguments to pass to the command
 * @return the return code from the command
 * @throws ExecuteException
 * @throws IOException
 */
public static int exec(final String command, final String arguments) throws ExecuteException, IOException {
    CommandLine cmd = new CommandLine(command);

    cmd.addArguments(arguments);

    DefaultExecutor executor = new DefaultExecutor();

    return executor.execute(cmd);
}

From source file:com.nts.alphamale.shell.AdbShellCommand.java

/**
 * 1. adbcommand.properties? ? adb command list  ?  ResourceBudle? ?  ??? .
 * 2.  adb  ?  ??? . //from  ww  w  . j av  a2s. c  om
 * @param serial ?? 
 * @param adbCmd adb 
 * @param args adb  ?? ()
 * @return adb command line
 */
public static CommandLine cmd(String serial, String adbCmd, String[] args) {
    CommandLine cmd = cmd(serial, adbCmd);
    cmd.addArguments(args);
    return cmd;
}

From source file:de.pawlidi.openaletheia.utils.exec.ProcessExecutor.java

/**
 * Execute given system command with arguments.
 * //from   www .j  a v  a  2 s  .  co m
 * @param command
 *            to execute
 * @param args
 *            as command arguments
 * @return command output as String, null otherwise
 */
public static String executeCommand(final String command, String... args) {
    if (StringUtils.isNotEmpty(command)) {

        // create string output for executor
        ProcessStringOutput processOutput = new ProcessStringOutput(PROCESS_OUTPUT_LEVEL);
        // create external process
        Executor executor = createExecutor(processOutput);

        // create command line without any arguments
        final CommandLine commandLine = new CommandLine(command);

        if (ArrayUtils.isNotEmpty(args)) {
            // add command arguments
            commandLine.addArguments(args);
        }
        int exitValue = -1;

        try {
            // execute command
            exitValue = executor.execute(commandLine);
        } catch (IOException e) {
            // ignore exception
        }

        if (!executor.isFailure(exitValue)) {
            return processOutput.getOutput();
        }
    }
    return null;
}

From source file:com.nts.alphamale.shell.AdbShellCommand.java

/**
 * 1. adbcommand.properties? ? adb command list  ?  ResourceBudle? ?  ??? .
 * 2.  adb  ?  ??? . /*from   www . ja  va 2s .  c  o  m*/
 * @param serial ?? 
 * @param adbCmd adb 
 * @return adb command line
 */
public static CommandLine cmd(String serial, String adbCmd) {
    CommandLine cmd = new CommandLine(Utils.adb());
    if (!serial.isEmpty()) {
        cmd.addArgument("-s");
        cmd.addArgument(serial);
    }
    if (ADB_COMMAND_BUNDLE.getString(adbCmd).isEmpty()) {
        cmd.addArguments(adbCmd.split(" "));
    } else {
        cmd.addArguments(ADB_COMMAND_BUNDLE.getString(adbCmd).split(" "));
    }
    return cmd;
}

From source file:io.manasobi.utils.CmdUtils.java

/**
 *   (commandLine) ?   ?? ?  ? ?// w  ww.j  av  a  2s  .co m
 * 
 * @param commandLine    
 * @param argument     ?
 * @param timeout     
 * 
 * @return int ? 
 */
public static int execute(CommandLine commandLine, String argument, long timeout) {

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

    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(streamHandler);

    // ? 
    if (StringUtils.isNotEmpty(argument)) {
        commandLine.addArguments(argument);
    }

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

    // ??  ? 
    executor.setExitValue(SUCCESS_RETURN_CODE);

    try {

        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

        executor.execute(commandLine, resultHandler);
        resultHandler.waitFor();

        return resultHandler.getExitValue();

    } catch (Exception e) {

        throw new CmdUtilsException(e.getMessage());
    }
}

From source file:ca.unbsj.cbakerlab.sqltemplate.schematicanswers.ExecutionEngine.java

public String run(String input) {
    File req = tmpFile("request-", ".tptp");

    writeStringToFile(req, input);/*from  w  w w.jav a  2  s  .c o  m*/

    CommandLine cl = new CommandLine(m_binPath);
    cl.addArguments(m_commBuilder.buildCommandLine(m_resourcePaths, req.getPath()));
    //System.out.println("--"+ cl.toString());
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    execute(cl, out, m_exeTimeout);
    req.delete();

    File schematic_answer = new File(
            System.getProperty("java.io.tmpdir").concat("/SQLTemplateDir") + "/schematic_answers.xml");
    writeStringToFile(schematic_answer, out.toString());

    return m_resultHandler.parse(out.toString());
}

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

public int execute(String[] args, @Nullable Path workingDir, Map<String, String> addEnv) throws IOException {
    if (!Files.isExecutable(file)) {
        Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(file, perms);
    }//from ww  w.jav a  2s  .  c o m

    ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
    CommandLine cmd = new CommandLine(file.toFile());
    cmd.addArguments(args);
    DefaultExecutor exec = new DefaultExecutor();
    exec.setWatchdog(watchdog);
    exec.setStreamHandler(createStreamHandler());
    exec.setExitValues(null);
    if (workingDir != null) {
        exec.setWorkingDirectory(workingDir.toFile());
    }
    in.close();
    LOG.info("Executing: {}", cmd.toString());
    Map<String, String> env = new HashMap<>(System.getenv());
    env.putAll(addEnv);
    return exec.execute(cmd, env);
}

From source file:its.tools.CommandExecutor.java

public void execute(String[] args, @Nullable Path workingDir) throws IOException {
    if (!Files.isExecutable(file)) {
        Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(file, perms);
    }/*w  ww.ja  v  a 2 s.  co  m*/

    watchdog = new ExecuteWatchdog(TIMEOUT);
    CommandLine cmd = new CommandLine(file.toFile());
    cmd.addArguments(args);
    DefaultExecutor exec = new DefaultExecutor();
    exec.setWatchdog(watchdog);
    exec.setStreamHandler(createStreamHandler());
    exec.setExitValues(null);
    if (workingDir != null) {
        exec.setWorkingDirectory(workingDir.toFile());
    }
    in.close();
    LOG.info("Executing: {}", cmd.toString());
    exec.execute(cmd, new ResultHander());
}

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 va 2 s  .  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.takari.maven.plugins.compile.javac.CompilerJavacLauncher.java

private void compile(File options, File output, final Map<File, Resource<File>> sources) throws IOException {
    new CompilerConfiguration(getSourceEncoding(), getCompilerOptions(), sources.keySet()).write(options);

    // use the same JVM as the one used to run Maven (the "java.home" one)
    String executable = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
    if (File.separatorChar == '\\') {
        executable = executable + ".exe";
    }/*from w  w w  . j  a  va 2s .c o  m*/

    CommandLine cli = new CommandLine(executable);

    // jvm options
    cli.addArguments(new String[] { "-cp", jar.getAbsolutePath() });
    if (meminitial != null) {
        cli.addArgument("-Xms" + meminitial);
    }
    if (maxmem != null) {
        cli.addArgument("-Xmx" + maxmem);
    }

    // main class and program arguments
    cli.addArgument(CompilerJavacForked.class.getName());
    cli.addArgument(options.getAbsolutePath(), false);
    cli.addArgument(output.getAbsolutePath(), false);

    DefaultExecutor executor = new DefaultExecutor();
    // ExecuteWatchdog watchdog = null;
    // if (forkedProcessTimeoutInSeconds > 0) {
    // watchdog = new ExecuteWatchdog(forkedProcessTimeoutInSeconds * 1000L);
    // executor.setWatchdog(watchdog);
    // }
    // best effort to avoid orphaned child process
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    executor.setWorkingDirectory(basedir);

    log.debug("External java process command line:\n   {}", cli);
    try {
        executor.execute(cli); // this throws ExecuteException if process return code != 0
    } catch (ExecuteException e) {
        if (!log.isDebugEnabled()) {
            log.info("External java process command line:\n   {}", cli);
        }
        throw e;
    }

    final Map<File, Output<File>> outputs = new HashMap<File, Output<File>>();

    CompilerOutput.process(output, new CompilerOutputProcessor() {
        @Override
        public void processOutput(File inputFile, File outputFile) {
            outputs.put(outputFile, context.processOutput(outputFile));
        }

        @Override
        public void addMessage(String path, int line, int column, String message, MessageSeverity kind) {
            if (".".equals(path)) {
                context.addPomMessage(message, kind, null);
            } else {
                File file = new File(path);
                Resource<File> resource = sources.get(file);
                if (resource == null) {
                    resource = outputs.get(file);
                }
                if (resource != null) {
                    if (isShowWarnings() || kind != MessageSeverity.WARNING) {
                        resource.addMessage(line, column, message, kind, null);
                    }
                } else {
                    log.warn("Unexpected java resource {}", file);
                }
            }
        }

        @Override
        public void addLogMessage(String message) {
            log.warn(message);
        }
    });
}