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

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

Introduction

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

Prototype

int execute(CommandLine command) throws ExecuteException, IOException;

Source Link

Document

Methods for starting synchronous execution.

Usage

From source file:it.drwolf.ridire.index.cwb.CWBConcordancer.java

private Integer getCQPQueryResultsSize(File queryFile) throws ExecuteException, IOException {
    Executor executor = new DefaultExecutor();
    File tempSh = File.createTempFile("ridireSH", ".sh");
    File tempSize = File.createTempFile("ridireSZ", ".size");
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("export LC_ALL=C\n");
    stringBuffer.append(this.cqpExecutable + " -f " + queryFile.getAbsolutePath() + " -D " + this.cqpCorpusName
            + " -r " + this.cqpRegistry + " > " + tempSize.getAbsolutePath() + "\n");
    FileUtils.writeStringToFile(tempSh, stringBuffer.toString());
    tempSh.setExecutable(true);//from  ww  w.j  a  va  2s .c om
    CommandLine commandLine = new CommandLine(tempSh.getAbsolutePath());
    executor.execute(commandLine);
    Integer size = 0;
    List<String> lines = FileUtils.readLines(tempSize);
    if (lines.size() > 0) {
        size = Integer.parseInt(lines.get(0).trim());
    }
    FileUtils.deleteQuietly(tempSh);
    FileUtils.deleteQuietly(tempSize);
    return size;
}

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

/**
 * Initialize the TG server synchronously. This Init operation blocks until
 * it is completed.//  w  w w .  ja  v  a2  s . c  o m
 * 
 * @param initFile
 *            TG server init config file
 * @param forceCreation
 *            Force creation. Delete all the data in the db directory first.
 * @param timeout
 *            Number of milliseconds allowed to initialize the server
 * @return the output stream of init operation 
 * @throws TGInitException
 *             Init operation fails or timeout occurs 
 */
public String init(String initFile, boolean forceCreation, long timeout) throws TGInitException {

    File initF = new File(initFile);
    if (!initF.exists())
        throw new TGInitException("TGServer - Init file '" + initFile + "' does not exist");
    try {
        this.setInit(initF);
    } catch (TGGeneralException e) {
        throw new TGInitException(e.getMessage());
    }

    //ByteArrayOutputStream output = new ByteArrayOutputStream();

    PumpStreamHandler psh = new PumpStreamHandler(new ByteArrayOutputStream());
    Executor tgExec = new DefaultExecutor();
    tgExec.setStreamHandler(psh);
    tgExec.setWorkingDirectory(new File(this.home + "/bin"));
    CommandLine tgCL = new CommandLine((new File(this.home + "/bin/" + process)).getAbsolutePath());
    if (forceCreation)
        tgCL.addArguments(new String[] { "-i", "-f", "-Y", "-c", initFile, "-l", this.initLogFileBase });
    else
        tgCL.addArguments(new String[] { "-i", "-Y", "-c", initFile, "-l", this.initLogFileBase });

    ExecuteWatchdog tgWatch = new ExecuteWatchdog(timeout);
    tgExec.setWatchdog(tgWatch);
    System.out.println("TGServer - Initializing " + StringUtils.toString(tgCL.toStrings(), " "));
    String output = "";
    try {
        tgExec.execute(tgCL);
        output = new String(Files.readAllBytes(Paths.get(this.getInitLogFile().toURI())));
    } catch (IOException ee) {
        if (tgWatch.killedProcess())
            throw new TGInitException("TGServer - Init did not complete within " + timeout + " ms");
        else {
            try {
                Thread.sleep(1000); // make sure output has time to fill up

            } catch (InterruptedException ie) {
                ;
            }
            throw new TGInitException("TGServer - Init failed: " + ee.getMessage(), output);
        }
    }
    try {
        this.setBanner(output);
    } catch (TGGeneralException tge) {
        throw new TGInitException(tge.getMessage());
    }

    if (output.contains("TGSuccess")) {
        System.out.println("TGServer - Initialized successfully");
        return output;
    } else
        throw new TGInitException("TGServer - Init failed", output);
}

From source file:it.drwolf.ridire.index.cwb.CWBPatternSearcher.java

private Integer getCQPQueryResultsSize(File queryFile, String cqpSizeQuery)
        throws ExecuteException, IOException {
    EnvironmentUtils.addVariableToEnvironment(EnvironmentUtils.getProcEnvironment(), "LC_ALL=C");
    Executor executor = new DefaultExecutor();
    File tempSize = File.createTempFile("ridireSZ", ".size");
    File tempSh = File.createTempFile("ridireSH", ".sh");
    CommandLine commandLine = new CommandLine(this.cqpExecutable);
    commandLine.addArgument("-f").addArgument(queryFile.getAbsolutePath()).addArgument("-D")
            .addArgument(this.cqpCorpusName).addArgument("-r").addArgument(this.cqpRegistry);
    String commLineString = commandLine.toString() + " > " + tempSize.getAbsolutePath();
    FileUtils.writeStringToFile(tempSh, commLineString);
    tempSh.setExecutable(true);/*from   w  w  w  .  j av  a2 s . com*/
    executor = new DefaultExecutor();
    executor.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(CWBPatternSearcher.TIMEOUT);
    executor.setWatchdog(watchdog);
    commandLine = new CommandLine(tempSh.getAbsolutePath());
    executor.execute(commandLine);
    Integer size = 0;
    List<String> lines = FileUtils.readLines(tempSize);
    if (lines.size() > 0) {
        size = Integer.parseInt(lines.get(0).trim());
    }
    FileUtils.deleteQuietly(tempSh);
    FileUtils.deleteQuietly(tempSize);
    return size;
}

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

/**
 * Invoke TG admin synchronously. /*  w w w.  j  a v  a2  s  . c om*/
 * Admin operation blocks until it is completed.
 * 
 * @param tgHome TG admin home
 * @param url Url to connect to TG server
 * @param user System User name
 * @param pwd System User password
 * @param logFile TG admin log file location - Generated by admin
 * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire
 * @param cmd TG admin command file or command string
 * @param memSize Specify the maximum memory usage (MB). -1 for default (8 MB)
 * @param timeout Number of milliseconds allowed to complete admin operation
 * 
 * @return Output console of admin operation 
 * @throws TGAdminException Admin execution fails or timeout occurs 
 */
public static String invoke(String tgHome, String url, String user, String pwd, String logFile, String logLevel,
        String cmd, int memSize, long timeout) throws TGAdminException {
    if (tgHome == null)
        throw new TGAdminException("TGAdmin - TGDB home is not defined");
    File ftgHome = new File(tgHome);
    if (!ftgHome.exists())
        throw new TGAdminException("TGAdmin - TGDB home '" + tgHome + "' does not exist");

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(output);
    Executor tgExec = new DefaultExecutor();
    tgExec.setStreamHandler(psh);
    tgExec.setWorkingDirectory(new File(tgHome + "/bin"));

    CommandLine tgCL = new CommandLine((new File(tgHome + "/bin/" + process)).getAbsolutePath());

    // Define arguments
    List<String> args = new ArrayList<String>();
    if (url != null) {
        args.add("--url");
        args.add(url);
    }
    if (user != null) {
        args.add("--uid");
        args.add(user);
    }
    if (pwd != null) {
        args.add("--pwd");
        args.add(pwd);
    }
    if (logFile != null) {
        args.add("--log");
        args.add(logFile);
    }
    if (logLevel != null) {
        args.add("--log-level");
        args.add(logLevel);
    }
    if (memSize >= 0) {
        args.add("--max-memory");
        args.add(Integer.toString(memSize));
    }

    File cmdFile = null;
    if (cmd == null)
        throw new TGAdminException("TGAdmin - Command is required.");
    if (cmd.matches(
            "(?s)^(kill|show|describe|create|stop|info|checkpoint|dump|set|connect|disconnect|export|import|exit).*$")) {
        try {
            cmdFile = new File(tgHome + "/invokeAdminScript.txt");
            Files.write(Paths.get(cmdFile.toURI()), cmd.getBytes(StandardCharsets.UTF_8));
        } catch (IOException ioe) {
            throw new TGAdminException("TGAdmin - " + ioe.getMessage());
        }
    } else {
        cmdFile = new File(cmd);
    }

    if (!cmdFile.exists()) {
        throw new TGAdminException("TGAdmin - Command file '" + cmdFile + "' does not exist");
    }
    args.add("--file");
    args.add(cmdFile.getAbsolutePath());

    tgCL.addArguments((String[]) args.toArray(new String[args.size()]));

    ExecuteWatchdog tgWatch = new ExecuteWatchdog(timeout);
    tgExec.setWatchdog(tgWatch);
    System.out.println("TGAdmin - Invoking " + StringUtils.toString(tgCL.toStrings(), " "));

    long endProcTime = 0;
    long totalProcTime = 0;
    try {
        TGAdmin.startProcTime = System.currentTimeMillis();
        tgExec.execute(tgCL);
        endProcTime = System.currentTimeMillis();
    } catch (IOException ee) {
        if (tgWatch.killedProcess())
            throw new TGAdminException("TGAdmin - Operation did not complete within " + timeout + " ms",
                    output.toString());
        else {
            try {
                Thread.sleep(1000); // make sure output has time to fill up
            } catch (InterruptedException ie) {
                ;
            }
            throw new TGAdminException("TGAdmin - Execution failed: " + ee.getMessage(), output.toString());
        }
    }
    if (url != null && !output.toString().contains("Successfully connected to server"))
        throw new TGAdminException("TGAdmin - Admin could not connect to server " + url + " with user " + user,
                output.toString());
    if (endProcTime != 0)
        totalProcTime = endProcTime - TGAdmin.startProcTime;
    if (TGAdmin.showOperationBanner)
        System.out.println(
                "TGAdmin - Operation completed" + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : ""));
    return output.toString();
}

From source file:it.drwolf.ridire.index.cwb.CWBConcordancer.java

private void executeQueryForContext(CWBResult item, File contextFile, boolean left)
        throws ExecuteException, IOException {
    Executor executor = new DefaultExecutor();
    File tempSh = File.createTempFile("ridireCTX", ".sh");
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("LC_ALL=C && ");
    if (left) {/* w ww.j a  v  a  2  s.c om*/
        stringBuffer.append(this.cwbdecodeExecutable + " -r " + this.cqpRegistry + " -C -s "
                + Math.max(0, item.getStartPosition() - 101) + " -e " + (item.getStartPosition() - 1) + " "
                + this.cqpCorpusName + " -P word" + " > " + contextFile.getAbsolutePath() + "\n");
    } else {
        stringBuffer.append(this.cwbdecodeExecutable + " -r " + this.cqpRegistry + " -C -s "
                + (item.getEndPosition() + 1) + " -e " + (item.getEndPosition() + 101) + " "
                + this.cqpCorpusName + " -P word" + " > " + contextFile.getAbsolutePath() + "\n");
    }
    FileUtils.writeStringToFile(tempSh, stringBuffer.toString());
    tempSh.setExecutable(true);
    CommandLine commandLine = new CommandLine(tempSh.getAbsolutePath());
    executor.execute(commandLine);
    FileUtils.deleteQuietly(tempSh);
}

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

/**
 * Invoke TG admin synchronously. //from   w w w .  jav  a 2s.  co m
 * Admin operation blocks until it is completed.
 * 
 * @param url Url to connect to TG server
 * @param user User name
 * @param pwd User password
 * @param logFile TG admin log file location - Generated by admin
 * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire
 * @param cmdFile TG admin command file - Need to exist before invoking admin
 * @param memSize Specify the maximum memory usage (MB). -1 for default (8 MB)
 * @param timeout Number of milliseconds allowed to complete admin operation
 * 
 * @return Output console of admin operation 
 * @throws TGAdminException Admin execution fails or timeout occurs 
 */
public String invoke(String url, String user, String pwd, String logFile, String logLevel, String cmdFile,
        int memSize, long timeout) throws TGAdminException {

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(output);
    Executor tgExec = new DefaultExecutor();
    tgExec.setStreamHandler(psh);
    tgExec.setWorkingDirectory(new File(this.home + "/bin"));

    CommandLine tgCL = new CommandLine((new File(this.home + "/bin/" + process)).getAbsolutePath());

    // Define arguments
    List<String> args = new ArrayList<String>();
    if (url != null) {
        args.add("--url");
        args.add(url);
    }
    if (user != null) {
        args.add("--uid");
        args.add(user);
    }
    if (pwd != null) {
        args.add("--pwd");
        args.add(pwd);
    }
    if (logFile != null) {
        args.add("--log");
        args.add(logFile);
    }
    if (logLevel != null) {
        args.add("--log-level");
        args.add(logLevel);
    }
    if (memSize >= 0) {
        args.add("--max-memory");
        args.add(Integer.toString(memSize));
    }
    if (cmdFile == null)
        throw new TGAdminException("TGAdmin - Command file is required.");
    args.add("--file");
    args.add(cmdFile);

    tgCL.addArguments((String[]) args.toArray(new String[args.size()]));

    ExecuteWatchdog tgWatch = new ExecuteWatchdog(timeout);
    tgExec.setWatchdog(tgWatch);
    System.out.println("TGAdmin - Invoking " + StringUtils.toString(tgCL.toStrings(), " "));
    long startProcTime = 0;
    long endProcTime = 0;
    long totalProcTime = 0;
    try {
        startProcTime = System.currentTimeMillis();
        tgExec.execute(tgCL);
        endProcTime = System.currentTimeMillis();
    } catch (IOException ee) {
        if (tgWatch.killedProcess())
            throw new TGAdminException("TGAdmin - Operation did not complete within " + timeout + " ms",
                    output.toString());
        else {
            try {
                Thread.sleep(1000); // make sure output has time to fill up
            } catch (InterruptedException ie) {
                ;
            }
            throw new TGAdminException("TGAdmin - Execution failed: " + ee.getMessage(), output.toString());
        }
    }
    if (!output.toString().contains("Successfully connected to server"))
        throw new TGAdminException("TGAdmin - Admin could not connect to server", output.toString());
    if (endProcTime != 0)
        totalProcTime = endProcTime - startProcTime;
    System.out.println(
            "TGAdmin - Operation completed" + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : ""));
    return output.toString();
}

From source file:org.cloudifysource.dsl.context.utils.VolumeUtils.java

private static void executeCommandLine(final String commandLine, final long timeout)
        throws LocalStorageOperationException, TimeoutException {

    Executor executor = new DefaultExecutor();
    executor.setExitValue(0);/*from   w w w  . j  a  v  a  2 s. co m*/
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(watchdog);
    ProcessOutputStream outAndErr = new ProcessOutputStream();
    try {
        PumpStreamHandler streamHandler = new PumpStreamHandler(outAndErr);
        executor.setStreamHandler(streamHandler);
        logger.info("Executing commandLine : '" + commandLine + "'");
        executor.execute(CommandLine.parse(commandLine));
        logger.info("Execution completed successfully. Process output was : " + outAndErr.getOutput());
    } catch (final Exception e) {
        if (watchdog.killedProcess()) {
            throw new TimeoutException("Timed out while executing commandLine : '" + commandLine + "'");
        }
        throw new LocalStorageOperationException("Failed executing commandLine : '" + commandLine
                + ". Process output was : " + outAndErr.getOutput(), e);
    }
}

From source file:org.cloudifysource.utilitydomain.context.blockstorage.VolumeUtils.java

private static void executeCommandLine(final String commandLine, final long timeout)
        throws LocalStorageOperationException, TimeoutException {

    Executor executor = new DefaultExecutor();
    executor.setExitValue(0);/*from   w w w. ja  va2 s . co m*/
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(watchdog);
    ProcessOutputStream outAndErr = new ProcessOutputStream();
    try {
        PumpStreamHandler streamHandler = new PumpStreamHandler(outAndErr);
        executor.setStreamHandler(streamHandler);
        logger.info("Executing commandLine : '" + commandLine + "'");
        executor.execute(CommandLine.parse(commandLine));
        logger.info("Execution completed successfully. Process output was : " + outAndErr.getOutput());
    } catch (final Exception e) {
        if (watchdog.killedProcess()) {
            throw new TimeoutException("Timed out while executing commandLine : '" + commandLine + "'");
        }

        throw new LocalStorageOperationException("Failed executing commandLine : '" + commandLine
                + ". Process output was : " + outAndErr.getOutput(), e);
    }
}

From source file:org.cloudifysource.utilitydomain.context.blockstorage.VolumeUtils.java

private static String executeSilentCommandLineReturnOutput(final String commandLine, final long timeout)
        throws LocalStorageOperationException, TimeoutException {

    Executor executor = new DefaultExecutor();
    executor.setExitValue(0);//  www.  java 2 s.c  o m
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(watchdog);
    ProcessOutputStream outAndErr = new ProcessOutputStream();
    try {
        PumpStreamHandler streamHandler = new PumpStreamHandler(outAndErr);
        executor.setStreamHandler(streamHandler);
        executor.execute(CommandLine.parse(commandLine));
    } catch (final Exception e) {
        if (watchdog.killedProcess()) {
            throw new TimeoutException("Timed out while executing commandLine : '" + commandLine + "'");
        }

        throw new LocalStorageOperationException("Failed executing commandLine : '" + commandLine
                + ". Process output was : " + outAndErr.getOutput(), e);
    }

    return outAndErr.getOutput();
}

From source file:org.docwhat.iated.AppState.java

public String editFile(File file) {
    String editor = getEditor();/*from  ww w  .j  a  v a  2s.c  om*/
    CommandLine cmd;

    if (OS.isFamilyMac() && editor.matches(".*\\.app")) {
        cmd = new CommandLine("/usr/bin/open");
        cmd.addArgument("-a").addArgument(editor).addArgument(file.toString());
    } else {
        cmd = new CommandLine(editor);
        cmd.addArgument(file.toString());
    }

    Executor executor = new DefaultExecutor();
    try {
        executor.execute(cmd);
    } catch (ExecuteException ex) {
        //TODO Do something meaningful with the exception.
        throw new RuntimeException(ex);
    } catch (IOException ex) {
        //TODO Do something meaningful with the exception.
        throw new RuntimeException(ex);
    }
    return "bogus-token";
}