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:com.tibco.tgdb.test.lib.TGServer.java

/**
 * <pre>//from  www  . j  a  v  a2s .co m
 * Kill the TG server.
 * - taskkill on Windows.
 * - kill -9 on Unix.
 * </pre>
 * 
 * @throws Exception
 *             Kill operation fails
 */
public void kill() throws Exception {

    if (this.pid == 0)
        throw new TGGeneralException(
                "TG server does not have a PID - Probably due to a previous start-up failure");

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(output);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(psh);
    CommandLine cmdLine;
    if (OS.isFamilyWindows())
        cmdLine = CommandLine.parse("taskkill /f /pid " + this.getPid() + " /t");
    else
        cmdLine = CommandLine.parse("kill -9 " + this.getPid() + "");
    try {
        executor.execute(cmdLine);
    } catch (ExecuteException ee) {
        // System.out.println("TGServer with pid " + this.getPid() + " not killed :");
        // System.out.println("\t- " + output.toString().trim().replace("\n","\n\t- "));
        throw new ExecuteException(output.toString().trim(), 1); // re-throw with better message
    }
    System.out.println("TGServer - Server with pid " + this.getPid() + " successfully killed :");
    if (!output.toString().equals(""))
        System.out.println("\t\t- " + output.toString().trim().replace("\n", "\n\t\t- "));
    this.running = false;
    this.pid = 0;
}

From source file:com.tibco.tgdb.test.lib.TGServer.java

/**
 * <pre>//www. java  2 s.com
 * Kill all the TG server processes.
 * Note that this method blindly tries to kill all the servers of the machine 
 * and do not update the running status of those servers.
 * - taskkill on Windows.
 * - kill -9 on Unix.
 * </pre>
 * 
 * @throws Exception Kill operation fails
 */
public static void killAll() throws Exception {

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(output);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(psh);
    executor.setWorkingDirectory(new File(System.getProperty("java.io.tmpdir")));
    CommandLine cmdLine;
    if (OS.isFamilyWindows())
        cmdLine = CommandLine.parse("taskkill /f /im " + process + ".exe");
    else { // Unix
        File internalScriptFile = new File(ClassLoader
                .getSystemResource(
                        TGServer.class.getPackage().getName().replace('.', '/') + "/TGKillProcessByName.sh")
                .getFile());
        File finalScriptFile = new File(executor.getWorkingDirectory() + "/" + internalScriptFile.getName());
        Files.copy(internalScriptFile.toPath(), finalScriptFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        cmdLine = CommandLine.parse("sh " + finalScriptFile.getAbsolutePath() + " " + process + "");
    }
    try {
        Thread.sleep(1000);
        executor.execute(cmdLine);
    } catch (ExecuteException ee) {
        if (output.toString().contains(
                "ERROR: The process \"" + process + (OS.isFamilyWindows() ? ".exe\"" : "") + " not found"))
            return;
        throw new ExecuteException(output.toString().trim(), 1); // re-throw with better message
    }
    // Check one more thing :
    // On Windows when some processes do not get killed taskkill still
    // returns exit code
    if (OS.isFamilyWindows()) {
        if (output.toString().contains("ERROR"))
            throw new ExecuteException(output.toString().trim(), 1);
    } else {
        if (output.toString().contains("ERROR: The process \"" + process + "\" not found"))
            return;
    }

    System.out.println("TGServer - Server(s) successfully killed :");
    if (!output.toString().equals(""))
        System.out.println("\t\t- " + output.toString().trim().replace("\n", "\n\t\t- "));
}

From source file:it.drwolf.ridire.session.async.Mapper.java

@SuppressWarnings("unchecked")
private StringWithEncoding transformPDF2HTML(File resourceFile, EntityManager entityManager)
        throws IOException, InterruptedException {
    String workingDirName = System.getProperty("java.io.tmpdir");
    String userDir = System.getProperty("user.dir");
    byte[] buf = new byte[Mapper.BUFLENGTH];
    int count = 0;
    GZIPInputStream gzis = new GZIPInputStream(new FileInputStream(resourceFile));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    while ((count = gzis.read(buf)) != -1) {
        baos.write(buf, 0, count);/*from  w  w w .j  av a  2s  . c o m*/
    }
    gzis.close();
    baos.close();
    byte[] byteArray = baos.toByteArray();
    String uuid = UUID.randomUUID().toString();
    String pdfFileName = uuid + ".pdf";
    String htmlFileName = uuid + ".html";
    File tmpDir = new File(workingDirName);
    String htmlFileNameCompletePath = workingDirName + JobMapperMonitor.FILE_SEPARATOR + htmlFileName;
    File fileToConvert = new File(tmpDir, pdfFileName);
    FileUtils.writeByteArrayToFile(fileToConvert, byteArray);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    CommandParameter cp = entityManager.find(CommandParameter.class, CommandParameter.PDFTOHTML_EXECUTABLE_KEY);
    CommandLine commandLine = CommandLine.parse(cp.getCommandValue());
    commandLine.addArgument("-c");
    commandLine.addArgument("-i");
    commandLine.addArgument(fileToConvert.getAbsolutePath());
    commandLine.addArgument(htmlFileNameCompletePath);
    executor.setExitValue(0);
    executor.execute(commandLine);
    try {
        FileUtils.moveFileToDirectory(
                new File(userDir + JobMapperMonitor.FILE_SEPARATOR + uuid + "-outline.html"), tmpDir, false);
    } catch (IOException e) {
    }
    cp = entityManager.find(CommandParameter.class, CommandParameter.PDFCLEANER_EXECUTABLE_KEY);
    commandLine = CommandLine
            .parse("java -Xmx128m -jar -Djava.io.tmpdir=" + this.tempDir + " " + cp.getCommandValue());
    commandLine.addArgument(htmlFileNameCompletePath);
    commandLine.addArgument("39");
    commandLine.addArgument("6");
    commandLine.addArgument("5");
    executor = new DefaultExecutor();
    executor.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(Mapper.PDFCLEANER_TIMEOUT);
    executor.setWatchdog(watchdog);
    ByteArrayOutputStream baosStdOut = new ByteArrayOutputStream(1024);
    ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(baosStdOut, null, null);
    executor.setStreamHandler(executeStreamHandler);
    int exitValue = executor.execute(commandLine);
    String htmlString = null;
    if (exitValue == 0) {
        htmlString = baosStdOut.toString();
    }
    FileUtils.deleteQuietly(new File(htmlFileNameCompletePath));
    PrefixFileFilter pff = new PrefixFileFilter(uuid);
    for (File f : FileUtils.listFiles(tmpDir, pff, null)) {
        FileUtils.deleteQuietly(f);
    }
    if (htmlString != null) {
        htmlString = htmlString.replaceAll("&nbsp;", " ");
        htmlString = htmlString.replaceAll("<br.*?>", " ");
        CharsetDetector charsetDetector = new CharsetDetector();
        charsetDetector.setText(htmlString.getBytes());
        String encoding = charsetDetector.detect().getName();
        return new StringWithEncoding(htmlString, encoding);
    }
    return null;
}

From source file:GUI.GraphicalInterface.java

private void executeJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_executeJButtonActionPerformed
    /* Clear terminal area if needed */
    if (clearJCheckBox.isSelected() == true) {
        terminalJTextArea.setText(m_defaultTerminal);
    }/*w  ww . j a va  2s . co m*/

    if (OS.isFamilyUnix() && m_command.equals("traceroute")) {
        /* set Absolute path to traceroute in Linux */
        m_command = "/usr/sbin/traceroute";
    }

    m_internalPrefix = OS.isFamilyWindows();
    String prefix = (m_internalPrefix) ? "cmd.exe /c " : "";

    String option = optionJComboBox.getSelectedItem().toString();
    option = option.startsWith("(") ? "" : " " + option;

    String optionarg = optionJTextField.getText();
    optionarg = optionarg.trim().isEmpty() ? "" : " " + optionarg.trim();

    String cmdarg = argumentJTextField.getText();
    cmdarg = cmdarg.trim().isEmpty() ? "" : " " + cmdarg.trim();

    m_completeCommand = m_command + option + optionarg + cmdarg;
    cmdLine = CommandLine.parse(prefix + m_completeCommand);

    /* Update status bar */
    statusJLabel.setText("Running command... " + m_completeCommand);
    statusJProgressBar.setIndeterminate(true);

    terminalJTextArea.append(m_completeCommand + "\n");
    setScrollBar(jScrollPane1, 100);

    m_isManualExecution = false;
    t = new Thread(new newProcess(), "Process-Thread");
    t.start();

    /* Add command to history */
    if (!historyJCheckBox.isSelected()) {
        m_history += m_completeCommand + "\n";
    }

    /* Clear states */
    if (clearargJCheckBox.isSelected()) {
        argumentJTextField.setText("");
        optionJTextField.setText("");
    }
    passwordJTextField.setText("");
    passwordJTextField.setEnabled(false);
    rootJCheckBox.setSelected(false);
}

From source file:GUI.GraphicalInterface.java

private void executeManualJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_executeManualJButtonActionPerformed
    /* get the command from manual-cmd textField */
    String manual = commandJTextField.getText().trim();
    if (manual.length() == 0) {
        statusJLabel.setText("Empty command entered.");
        return;/*ww  w.j  a  v  a  2 s  . c om*/
    }

    /* Clear terminal area if needed */
    if (clearJCheckBox.isSelected() == true) {
        terminalJTextArea.setText("");
    }

    m_completeCommand = manual;
    m_internalPrefix = !manual.startsWith("cmd.exe") && OS.isFamilyWindows();
    String prefix = (m_internalPrefix) ? "cmd.exe /c " : "";
    cmdLine = CommandLine.parse(prefix + manual);

    /* Update status bar */
    statusJLabel.setText("Running command... " + m_completeCommand);
    statusJProgressBar.setIndeterminate(true);

    terminalJTextArea.append(m_completeCommand + "\n");
    setScrollBar(jScrollPane1, 100);

    m_isManualExecution = true;
    t = new Thread(new newProcess());
    t.start();

    /* Add command to history */
    if (!historyJCheckBox.isSelected()) {
        m_history += m_completeCommand + "\n";
    }

    /* Clear states after executing command */
    /* Set argument box to null after executing command */
    if (clearargJCheckBox.isSelected()) {
        commandJTextField.setText("");
    }
    passwordJTextField.setText("");
    passwordJTextField.setEnabled(false);
    rootJCheckBox.setSelected(false);
}

From source file:net.sourceforge.seqware.pipeline.plugins.ITUtility.java

/**
 * Run an arbitrary command and check it against an expected return value
 *
 * @param line//from ww  w.j  ava  2s  .  com
 * @param expectedReturnValue
 * @param dir working directory, can be null if you don't want to change directories
 * @return
 * @throws IOException
 */
public static String runArbitraryCommand(String line, int expectedReturnValue, File dir) throws IOException {
    Log.info("Running " + line);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CommandLine commandline = CommandLine.parse(line);
    DefaultExecutor exec = new DefaultExecutor();
    if (dir != null) {
        exec.setWorkingDirectory(dir);
    }
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    exec.setStreamHandler(streamHandler);
    exec.setExitValue(expectedReturnValue);
    try {
        int exitValue = exec.execute(commandline);
        Assert.assertTrue(
                "exit value for full jar with no params should be " + expectedReturnValue + " was " + exitValue,
                exitValue == expectedReturnValue);
        String output = outputStream.toString();
        return output;
    } catch (ExecuteException e) {
        Log.error("Execution failed with:");
        Log.error(outputStream.toString());
        throw e;
    }
}

From source file:net.spinetrak.rpitft.command.Command.java

Result execute(final Stream stream_) {
    final CommandLine commandline = CommandLine.parse(_script);
    final DefaultExecutor exec = new DefaultExecutor();
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(500);
    exec.setWatchdog(watchdog);/*from  www  . java  2 s .  c  om*/
    final PumpStreamHandler streamHandler = new PumpStreamHandler(stream_.getStream());
    exec.setStreamHandler(streamHandler);
    int result = -1;
    try {
        result = exec.execute(commandline);
    } catch (final IOException ex_) {
        //LOGGER.error(ex_.getMessage());
    }
    return new Result(stream_, result);
}

From source file:net.test.aliyun.z7.Zip7Object.java

public static int extract(final String extToosHome, final String extractFile, final String toDir)
        throws Throwable {
    String cmdLine = String.format("%s\\7z.exe x \"%s\" -aoa -y \"-o%s\"", extToosHome, extractFile, toDir);
    CommandLine commandline = CommandLine.parse(cmdLine);
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    DefaultExecutor executor = new DefaultExecutor();
    int extValue = -1;
    try {//from   www. j a  va 2 s.c  o  m
        executor.execute(commandline, resultHandler);
        resultHandler.waitFor(300 * 1000);
        extValue = resultHandler.getExitValue();
        if (extValue == 0) {
            new File(extractFile).delete();
        }
    } catch (Exception e) {
        //
    } finally {
        if (extValue != 0) {
            FileUtils.deleteDir(new File(toDir));
            return extValue;
        }
    }
    //
    Iterator<File> itFile = FileUtils.iterateFiles(new File(toDir), FileFilterUtils.fileFileFilter(),
            FileFilterUtils.directoryFileFilter());
    while (itFile.hasNext()) {
        File it = itFile.next();
        if (it.isDirectory())
            continue;
        for (String com : compression) {
            if (StringUtils.endsWithIgnoreCase(it.getName(), com)) {
                String itPath = it.getAbsolutePath();
                String subToDir = itPath.substring(0, itPath.length() - com.length());
                extract(extToosHome, itPath, subToDir);
            }
        }
    }
    return 0;
}

From source file:net.tkausl.RunMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    File plugins = pluginfolder == null ? new File(serverPath, "plugins") : new File(serverPath, pluginfolder);
    if (!plugins.exists())
        plugins.mkdirs();//from www .j a  v a  2  s  .  c o  m

    File pluginFile = new File(plugins, fileName + ".dev");
    if (!pluginFile.exists()) {
        try {
            PrintWriter w = new PrintWriter(pluginFile);
            w.print(outputDir);
            w.close();
        } catch (FileNotFoundException ex) {
            throw new MojoExecutionException("Could not write .dev-file");
        }
    }
    Executor ex = new DefaultExecutor();
    CommandLine commandLine = CommandLine.parse("java");
    String execArgs = System.getProperty("exec.args");
    if (execArgs != null && execArgs.trim().length() > 0) {
        commandLine.addArguments(execArgs.split(" "));
    }
    commandLine.addArguments(new String[] { "-jar", serverJar });

    if (pluginfolder != null)
        commandLine.addArguments(new String[] { "--plugins", pluginfolder });

    ex.setWorkingDirectory(serverPath);
    //PumpStreamHandler psh = new PumpStreamHandler(System.out, System.err, System.in);
    //ex.setStreamHandler(psh);
    ex.setStreamHandler(new ExecuteStreamHandler() {
        private PumpStreamHandler psh = new PumpStreamHandler(System.out, System.err);
        InputStreamPumper isp;
        Thread ispt;

        public void setProcessInputStream(OutputStream os) throws IOException {
            isp = new InputStreamPumper(System.in, os);
        }

        public void setProcessErrorStream(InputStream is) throws IOException {
            psh.setProcessErrorStream(is);
        }

        public void setProcessOutputStream(InputStream is) throws IOException {
            psh.setProcessOutputStream(is);
        }

        public void start() throws IOException {
            if (isp != null) {
                ispt = new Thread(isp);
                ispt.setDaemon(true);
                ispt.start();
            }
            psh.start();
        }

        public void stop() throws IOException {
            if (ispt != null)
                ispt.interrupt();
            psh.stop();
        }
    });
    try {
        ex.execute(commandLine);
    } catch (IOException ex1) {
        throw new MojoExecutionException("Error in Execution");
    }
}

From source file:npanday.plugin.partcover.AbstractPartCoverMojo.java

protected int executeCommandLine(String line) throws ExecuteException, IOException {
    CommandLine commandLine = CommandLine.parse(line);
    DefaultExecutor executor = new DefaultExecutor();
    return executor.execute(commandLine);
}