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

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

Introduction

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

Prototype

public void execute(final CommandLine command, final ExecuteResultHandler handler)
        throws ExecuteException, IOException 

Source Link

Usage

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

public ConexpCljBridge() {

    this.b = new byte[1];

    /**//from  w  ww. jav a2 s .c  o 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:de.akquinet.innovation.play.maven.Play2PackageMojo.java

private void packageApplication() throws MojoExecutionException {
    String line = getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);
    cmdLine.addArgument("package");
    DefaultExecutor executor = new DefaultExecutor();

    if (timeout > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        executor.setWatchdog(watchdog);/* ww w.  j  av  a2 s.c  o  m*/
    }

    executor.setWorkingDirectory(project.getBasedir());
    executor.setExitValue(0);
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        throw new MojoExecutionException("Error during packaging", e);
    }
}

From source file:de.akquinet.innovation.play.maven.Play2PackageMojo.java

private void packageDistribution() throws MojoExecutionException {
    String line = getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);
    cmdLine.addArgument("dist");
    DefaultExecutor executor = new DefaultExecutor();

    if (timeout > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        executor.setWatchdog(watchdog);//from ww w .  j a va2  s. c o  m
    }

    executor.setWorkingDirectory(project.getBasedir());
    executor.setExitValue(0);
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        throw new MojoExecutionException("Error during distribution creation", e);
    }
}

From source file:com.alibaba.jstorm.yarn.utils.JStormUtils.java

/**
 * If it is backend, please set resultHandler, such as DefaultExecuteResultHandler If it is frontend, ByteArrayOutputStream.toString get the result
 * <p/>//from   w  w  w.ja v a2s  .co m
 * This function don't care whether the command is successfully or not
 *
 * @param command
 * @param environment
 * @param workDir
 * @param resultHandler
 * @return
 * @throws IOException
 */
@Deprecated
public static ByteArrayOutputStream launchProcess(String command, final Map environment, final String workDir,
        ExecuteResultHandler resultHandler) throws IOException {

    String[] cmdlist = command.split(" ");

    CommandLine cmd = new CommandLine(cmdlist[0]);
    for (String cmdItem : cmdlist) {
        if (StringUtils.isBlank(cmdItem) == false) {
            cmd.addArgument(cmdItem);
        }
    }

    DefaultExecutor executor = new DefaultExecutor();

    executor.setExitValue(0);
    if (StringUtils.isBlank(workDir) == false) {
        executor.setWorkingDirectory(new File(workDir));
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    PumpStreamHandler streamHandler = new PumpStreamHandler(out, out);
    if (streamHandler != null) {
        executor.setStreamHandler(streamHandler);
    }

    try {
        if (resultHandler == null) {
            executor.execute(cmd, environment);
        } else {
            executor.execute(cmd, environment, resultHandler);
        }
    } catch (ExecuteException e) {

        // @@@@
        // failed to run command
    }

    return out;

}

From source file:com.blackducksoftware.tools.scmconnector.core.CommandLineExecutor.java

@Override
public int executeCommand(Logger log, CommandLine command, File targetDir, String promptResponse)
        throws Exception {
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);/*w  ww .ja  v a2 s.com*/

    PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHangler(log, Level.INFO));
    executor.setStreamHandler(psh);

    providePromptResponse(psh, promptResponse);

    executor.setWorkingDirectory(targetDir);

    // This log msg would reveal password
    // log.info("Command: " + command.toString() + " executed in: "
    // + targetDir.toString());

    int exitStatus = 1;
    try {
        exitStatus = executor.execute(command, EnvironmentUtils.getProcEnvironment());
    } catch (Exception e) {
        log.error("Failure executing Command: " + e.getMessage());
    }
    return exitStatus;
}

From source file:io.rhiot.utils.process.ExecProcessManager.java

@Override
public List<String> executeAndJoinOutput(String... command) {

    CommandLine cmdLine = CommandLine.parse(String.join(" ", command));
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);/*  w  w  w . j a  va2s.  co m*/
    ExecResultHandler resultHandler = null;

    if (getTimeout() > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(getTimeout());
        executor.setWatchdog(watchdog);
        resultHandler = new ExecResultHandler(watchdog);
    }
    try {
        CollectingLogOutputStream outAndErr = new CollectingLogOutputStream();
        executor.setStreamHandler(new PumpStreamHandler(outAndErr));
        if (resultHandler != null) {
            executor.execute(cmdLine, resultHandler);
        } else {
            executor.execute(cmdLine);
        }
        resultHandler.waitFor();
        return outAndErr.getLines();

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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 w  w w.jav  a2s.c om

    // 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:com.virtualparadigm.packman.processor.JPackageManager.java

public static boolean autorun(File autorunDir, Map<String, String> environmentVariableMap) {
    logger.info("PackageManager::autorun()");
    boolean status = true;

    if (autorunDir != null && autorunDir.isDirectory()) {
        File[] autorunFiles = autorunDir.listFiles();
        Arrays.sort(autorunFiles);
        String fileExtension = null;
        DefaultExecutor cmdExecutor = new DefaultExecutor();

        //            String sqlScriptFilePath = null;
        //            Reader sqlScriptReader = null;
        //            Properties sqlScriptProperties = null;
        for (File autorunFile : autorunFiles) {
            if (!autorunFile.isDirectory()) {
                try {
                    fileExtension = FilenameUtils.getExtension(autorunFile.getAbsolutePath());
                    if (fileExtension != null) {
                        if (fileExtension.equalsIgnoreCase("bat")) {
                            logger.info("  executing autorun batch script: " + autorunFile.getAbsolutePath());
                            logger.info("  executing autorun environment: "
                                    + EnvironmentUtils.toStrings(environmentVariableMap));
                            cmdExecutor.execute(CommandLine.parse(autorunFile.getAbsolutePath()),
                                    environmentVariableMap);
                        } else if (fileExtension.equalsIgnoreCase("sh")) {
                            Set<PosixFilePermission> permissionSet = new HashSet<PosixFilePermission>();
                            permissionSet.add(PosixFilePermission.OWNER_READ);
                            permissionSet.add(PosixFilePermission.OWNER_WRITE);
                            permissionSet.add(PosixFilePermission.OWNER_EXECUTE);
                            permissionSet.add(PosixFilePermission.OTHERS_READ);
                            permissionSet.add(PosixFilePermission.OTHERS_WRITE);
                            permissionSet.add(PosixFilePermission.OTHERS_EXECUTE);
                            permissionSet.add(PosixFilePermission.GROUP_READ);
                            permissionSet.add(PosixFilePermission.GROUP_WRITE);
                            permissionSet.add(PosixFilePermission.GROUP_EXECUTE);
                            Files.setPosixFilePermissions(Paths.get(autorunFile.toURI()), permissionSet);

                            logger.info("  executing autorun shell script: " + autorunFile.getAbsolutePath());
                            logger.info("  executing autorun environment: "
                                    + EnvironmentUtils.toStrings(environmentVariableMap));
                            cmdExecutor.execute(CommandLine.parse(autorunFile.getAbsolutePath()),
                                    environmentVariableMap);
                        } else if (fileExtension.equalsIgnoreCase("sql")
                                || fileExtension.equalsIgnoreCase("ddl")) {
                            logger.info("  executing autorun file: " + autorunFile.getAbsolutePath());

                            // look for properties file named same as script file for connection properties
                            //                                sqlScriptFilePath = autorunFile.getAbsolutePath();
                            //                                sqlScriptProperties = PropertyLoader.loadProperties(sqlScriptFilePath.substring(0, sqlScriptFilePath.length()-3) + "properties");
                            //                                sqlScriptReader = new FileReader(autorunFile.getAbsolutePath());
                        } else if (fileExtension.equalsIgnoreCase("jar")) {
                            logger.info("  executing autorun file: " + autorunFile.getAbsolutePath());
                        }//from   w  w w  .j av a 2  s .  co  m
                    }
                } catch (Exception e) {
                    logger.error("", e);
                    e.printStackTrace();
                }
            }
        }
    }
    return status;
}

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);// ww  w .  ja  va  2s.co m
        }
    }), 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.alibaba.jstorm.utils.JStormUtils.java

/**
 * If it is backend, please set resultHandler, such as DefaultExecuteResultHandler If it is frontend, ByteArrayOutputStream.toString get the result
 * <p/>//from  www . j a  v  a 2s .co  m
 * This function don't care whether the command is successfully or not
 * 
 * @param command
 * @param environment
 * @param workDir
 * @param resultHandler
 * @return
 * @throws IOException
 */
public static ByteArrayOutputStream launchProcess(String command, final Map environment, final String workDir,
        ExecuteResultHandler resultHandler) throws IOException {

    String[] cmdlist = command.split(" ");

    CommandLine cmd = new CommandLine(cmdlist[0]);
    for (String cmdItem : cmdlist) {
        if (StringUtils.isBlank(cmdItem) == false) {
            cmd.addArgument(cmdItem);
        }
    }

    DefaultExecutor executor = new DefaultExecutor();

    executor.setExitValue(0);
    if (StringUtils.isBlank(workDir) == false) {
        executor.setWorkingDirectory(new File(workDir));
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    PumpStreamHandler streamHandler = new PumpStreamHandler(out, out);
    if (streamHandler != null) {
        executor.setStreamHandler(streamHandler);
    }

    try {
        if (resultHandler == null) {
            executor.execute(cmd, environment);
        } else {
            executor.execute(cmd, environment, resultHandler);
        }
    } catch (ExecuteException e) {

        // @@@@
        // failed to run command
    }

    return out;

}