Example usage for org.apache.commons.exec.util StringUtils toString

List of usage examples for org.apache.commons.exec.util StringUtils toString

Introduction

In this page you can find the example usage for org.apache.commons.exec.util StringUtils toString.

Prototype

public static String toString(final String[] strings, final String separator) 

Source Link

Document

Concatenates an array of string using a separator.

Usage

From source file:com.github.genium_framework.appium.support.command.CommandManager.java

/**
 * Execute a command on the operating system using Java's built-in Process
 * class/*from   w  w  w .  ja v  a  2 s  . co m*/
 *
 * @param command A string array representation of the command to execute.
 * @param getOutput Whether or not to get the output/error streams of the
 * process you forked. This is helpful for debugging reasons.
 * @return A string representation of output/error streams of the process.
 */
public static String executeCommandUsingJavaRuntime(String[] command, boolean getOutput) {
    String output = "";

    try {
        Process p = Runtime.getRuntime().exec(command);

        // read the output from the command if requested by the user
        if (getOutput) {
            List<String> outErrStr = IOUtils.readLines(p.getInputStream());
            output = StringUtils.toString(outErrStr.toArray(new String[outErrStr.size()]), "\n");
        }
    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, "An exception was thrown while executing the command (" + command + ")", ex);
    }

    return output;
}

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

/**
 * Invoke TG admin synchronously. /* w ww .j a va 2s.  c o 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:com.tibco.tgdb.test.lib.TGAdmin.java

/**
 * Invoke TG admin synchronously. /*from   w w  w  .  j a v  a2  s  .co m*/
 * 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:com.tibco.tgdb.test.lib.TGServer.java

/**
 * Initialize the TG server synchronously. This Init operation blocks until
 * it is completed./*www .j a  v  a 2  s.  co  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:com.tibco.tgdb.test.lib.TGServer.java

/**
 * Start the TG server synchronously./*  ww  w . j av  a2  s. co  m*/
 * 
 * @param timeout
 *            Number of milliseconds allowed to start the server
 * @throws TGStartException Start operation fails
 */
public void start(long timeout) throws TGStartException {

    if (this.configFile == null)
        throw new TGStartException("TGServer - Config file not set");

    if (this.logFile == null)
        this.setLogFile("tgdb_" + this.dbName);

    //this.outStream = new ByteArrayOutputStream(); // reset
    //this.errStream = new ByteArrayOutputStream(); // reset
    PumpStreamHandler psh = new PumpStreamHandler(new ByteArrayOutputStream());
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    Executor tgExec = new DefaultExecutor();
    tgExec.setWorkingDirectory(new File(this.home + "/bin"));
    tgExec.setStreamHandler(psh);
    CommandLine tgCL = new CommandLine((new File(this.home + "/bin/" + process)).getAbsolutePath());
    tgCL.addArguments(new String[] { "-s", "-c", this.configFile.getAbsolutePath(), "-l", this.logFileBase });

    System.out.println("TGServer - Starting " + StringUtils.toString(tgCL.toStrings(), " "));
    try {
        tgExec.execute(tgCL, resultHandler);
    } catch (IOException ioe) {
        try {
            Thread.sleep(1000); // Make sure output/error fill up
        } catch (InterruptedException ie) {
            ;
        }
        throw new TGStartException(ioe.getMessage());
    }

    if (timeout > 0) {
        Calendar future = Calendar.getInstance();
        future.add(Calendar.MILLISECOND, (int) timeout);
        boolean started = false;
        boolean error = false;
        List<String> acceptedClients = new ArrayList<String>();
        String acceptedClient;
        while (!future.before(Calendar.getInstance())) {
            try {
                Thread.sleep(1000);
                BufferedReader reader = new BufferedReader(new StringReader(this.getOutput()));
                String line = reader.readLine();
                while (line != null) {
                    if (line.contains("Process pid:"))
                        this.setPid(Integer.parseInt(line.substring(line.lastIndexOf("Process pid:") + 12,
                                line.indexOf(",", line.lastIndexOf("Process pid:") + 12))));
                    if (line.contains("[Error]")) {
                        error = true;
                    }
                    if (line.contains("Accepting clients on")) {
                        started = true;
                        acceptedClient = line.substring(line.indexOf("- Accepting clients on") + 2);
                        if (!acceptedClients.contains(acceptedClient))
                            acceptedClients.add(acceptedClient);
                    }
                    line = reader.readLine();
                }
                reader.close();
                if (started)
                    break;
            } catch (Exception e) {
                throw new TGStartException("TGServer - " + e.getMessage());
            }
        }
        if (!started)
            throw new TGStartException(
                    "TGServer - Did not start on time (after " + timeout + " msec) - See log " + this.logFile);
        else {
            this.running = true;
            System.out.println("TGServer - Started successfully with pid " + this.pid + " :");
            System.out.println("\t\t- Log file: " + this.logFile);
            if (error)
                System.out.println("\t\t- With some error(s) - See log");
            for (String client : acceptedClients)
                System.out.println("\t\t- " + client);
            try {
                this.setBanner(this.getOutput());
            } catch (TGGeneralException tge) {
                throw new TGStartException(tge.getMessage());
            }
        }
    }
}