com.tibco.tgdb.test.lib.TGAdmin.java Source code

Java tutorial

Introduction

Here is the source code for com.tibco.tgdb.test.lib.TGAdmin.java

Source

package com.tibco.tgdb.test.lib;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Scanner;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.Executor;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.commons.exec.util.StringUtils;

import com.tibco.tgdb.test.utils.ProcessCheck;

/**
 * Copyright 2018 TIBCO Software Inc. All rights reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); You may not use this file except 
 * in compliance with the License.
 * A copy of the License is included in the distribution package with this file.
 * You also may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

/**
 * TG Admin can execute admin operations on a TG server.
 * 
 * @author sbagi@tibco.com
 *
 */
public class TGAdmin {

    final private static String process = "tgdb-admin";
    private static boolean showOperationBanner = true;
    private static boolean showStopServerBanner = true;
    private static long startProcTime = 0;

    private File home;

    /**
     * Create a TG admin
     * 
     * @param tgHome
     *            TG admin home
     * @throws TGGeneralException
     *             File path not found
     */
    public TGAdmin(String tgHome) throws TGGeneralException {
        if (tgHome == null)
            throw new TGGeneralException("TGAdmin - TGDB home is not defined");
        File ftgHome = new File(tgHome);
        if (!ftgHome.exists())
            throw new TGGeneralException("TGAdmin - TGDB home '" + tgHome + "' does not exist");

        this.setHome(ftgHome);
    }

    private void setHome(File tgHome) {
        this.home = tgHome;
    }

    /**
     * Invoke TG admin synchronously. 
     * 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();
    }

    /**
     * Get connections synchronously. 
     * Operation blocks until it is completed.
     * 
     * @param tgServer TG server to get connections from
     * @param tgNetListenerName Name of the net listener for TG Admin to connect to - if null connect to 1st one
     * @param logFile TG admin log file location - Generated by admin
     * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire
     * @param timeout Number of milliseconds allowed to complete the stop server operation - If lower than 0 wait forever
     * @return Array of session IDs
     * @throws TGAdminException Admin execution fails or timeout occurs 
     */
    public static String[] getConnections(TGServer tgServer, String tgNetListenerName, String logFile,
            String logLevel, long timeout) throws TGAdminException {

        String output = showConnections(tgServer, tgNetListenerName, logFile, logLevel, timeout);
        Scanner scanner = new Scanner(output);
        boolean counting = false;
        //int indexClientId;
        int indexSessionId = 0;
        int adminConnectionCount = 0;
        List<String> connectionList = new ArrayList<String>();
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.contains("Client ID")) {
                counting = true;
                //indexClientId = line.indexOf("Client ID");
                indexSessionId = line.indexOf("Session ID");
            } else if (line.contains("----------"))
                counting = false;
            else if (line.contains("connection(s) returned")) {
                counting = false;
                adminConnectionCount = Integer.parseInt(line.substring(0, line.indexOf(' ', 0)));
            } else if (counting) {
                connectionList.add(line.substring(indexSessionId, line.indexOf(' ', indexSessionId)));
            }
        }
        scanner.close();
        if (connectionList.size() != adminConnectionCount)
            throw new TGAdminException("TGAdmin - Not able to determine number of connections");
        return connectionList.toArray(new String[0]);
    }

    /**
     * Display connections synchronously. 
     * Operation blocks until it is completed.
     * 
     * @param tgServer TG server to show connection from
     * @param tgNetListenerName Name of the net listener for TG Admin to connect to - if null connect to 1st one
     * @param logFile TG admin log file location - Generated by admin
     * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire
     * @param timeout Number of milliseconds allowed to complete the stop server operation - If lower than 0 wait forever
     * @return Output console 
     * @throws TGAdminException Admin execution fails or timeout occurs 
     */
    public static String showConnections(TGServer tgServer, String tgNetListenerName, String logFile,
            String logLevel, long timeout) throws TGAdminException {

        if (tgServer == null)
            throw new TGAdminException("TGAdmin - tgServer cannot be null");

        String showCmd = "show connections\ndisconnect\nexit";
        File cmdFile;
        try {
            cmdFile = new File(tgServer.getHome().getAbsolutePath() + "/showConnectionsAdminScript.txt");
            Files.write(Paths.get(cmdFile.toURI()), showCmd.getBytes(StandardCharsets.UTF_8));
        } catch (IOException ioe) {
            throw new TGAdminException("TGAdmin - " + ioe.getMessage());
        }

        TGServer.NetListener netListener = tgServer.getNetListeners()[0]; // default get the 1st one
        if (tgNetListenerName != null) {
            for (TGServer.NetListener net : tgServer.getNetListeners()) {
                if (net.getName().equals(tgNetListenerName)) {
                    netListener = net;
                }
            }
        }

        String host = netListener.getHost();
        int port = netListener.getPort();
        String user = tgServer.getSystemUser();
        String pwd = tgServer.getSystemPwd();
        String url;
        try {
            url = "tcp://" + ((netListener.isIPv6()) ? ("[" + host + ":" + port + "]") : (host + ":" + port));
        } catch (TGGeneralException e) {
            throw new TGAdminException("TGAdmin - " + e.getMessage());
        }

        TGAdmin.showOperationBanner = false;
        String output = TGAdmin.invoke(tgServer.getHome().getAbsolutePath(), url, user, pwd, logFile, logLevel,
                cmdFile.getAbsolutePath(), -1, timeout);
        long endProcTime = System.currentTimeMillis();
        long totalProcTime = endProcTime - TGAdmin.startProcTime;
        System.out.println("TGAdmin - Show connections completed"
                + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : ""));

        return output;
    }

    /**
     * Display server info synchronously. 
     * Info operation blocks until it is completed.
     * 
     * @param tgServer TG server to get information from
     * @param tgNetListenerName Name of the net listener for TG Admin to connect to - if null connect to 1st one
     * @param logFile TG admin log file location - Generated by admin
     * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire
     * @param timeout Number of milliseconds allowed to complete the stop server operation - If lower than 0 wait forever
     *
     * @return Output console of info operation 
     * @throws TGAdminException Admin execution fails or timeout occurs 
     */
    public static String infoServer(TGServer tgServer, String tgNetListenerName, String logFile, String logLevel,
            long timeout) throws TGAdminException {

        if (tgServer == null)
            throw new TGAdminException("TGAdmin - tgServer cannot be null");

        String infoCmd = "info\ndisconnect\nexit";
        File cmdFile;
        try {
            cmdFile = new File(tgServer.getHome().getAbsolutePath() + "/infoAdminScript.txt");
            Files.write(Paths.get(cmdFile.toURI()), infoCmd.getBytes(StandardCharsets.UTF_8));
        } catch (IOException ioe) {
            throw new TGAdminException("TGAdmin - " + ioe.getMessage());
        }

        TGServer.NetListener netListener = tgServer.getNetListeners()[0]; // default get the 1st one
        if (tgNetListenerName != null) {
            for (TGServer.NetListener net : tgServer.getNetListeners()) {
                if (net.getName().equals(tgNetListenerName)) {
                    netListener = net;
                }
            }
        }

        String host = netListener.getHost();
        int port = netListener.getPort();
        String user = tgServer.getSystemUser();
        String pwd = tgServer.getSystemPwd();
        String url;
        try {
            url = "tcp://" + ((netListener.isIPv6()) ? ("[" + host + ":" + port + "]") : (host + ":" + port));
        } catch (TGGeneralException e) {
            throw new TGAdminException("TGAdmin - " + e.getMessage());
        }

        TGAdmin.showOperationBanner = false;
        String output = TGAdmin.invoke(tgServer.getHome().getAbsolutePath(), url, user, pwd, logFile, logLevel,
                cmdFile.getAbsolutePath(), -1, timeout);
        long endProcTime = System.currentTimeMillis();
        long totalProcTime = endProcTime - TGAdmin.startProcTime;
        System.out.println(
                "TGAdmin - Server info completed" + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : ""));

        return output;
    }

    /**
     * Stop TG server synchronously. 
     * Stop operation blocks until it is completed.
     * 
     * @param tgServer TG server to stop
     * @param tgNetListenerName Name of the net listener for TG Admin to connect to - if null connect to 1st one
     * @param logFile TG admin log file location - Generated by admin
     * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire
     * @param timeout Number of milliseconds allowed to complete the stop server operation - If lower than 0 wait forever
     *
     * @return Output console of stop operation 
     * @throws TGAdminException Admin execution fails or timeout occurs 
     */
    public static String stopServer(TGServer tgServer, String tgNetListenerName, String logFile, String logLevel,
            long timeout) throws TGAdminException {

        if (tgServer == null)
            throw new TGAdminException("TGAdmin - tgServer cannot be null");

        TGServer.NetListener netListener = tgServer.getNetListeners()[0]; // default get the 1st one
        if (tgNetListenerName != null) {
            for (TGServer.NetListener net : tgServer.getNetListeners()) {
                if (net.getName().equals(tgNetListenerName)) {
                    netListener = net;
                }
            }
        }

        String host = netListener.getHost();
        int port = netListener.getPort();
        String user = tgServer.getSystemUser();
        String pwd = tgServer.getSystemPwd();
        String url;
        try {
            url = "tcp://" + ((netListener.isIPv6()) ? ("[" + host + ":" + port + "]") : (host + ":" + port));
        } catch (TGGeneralException e) {
            throw new TGAdminException("TGAdmin - " + e.getMessage());
        }
        TGAdmin.showStopServerBanner = false;
        String output = TGAdmin.stopServer(tgServer.getHome().getAbsolutePath(), url, user, pwd, logFile, logLevel,
                3000);

        boolean tgdbRunning = true;
        if (timeout >= 0) {
            Calendar future = Calendar.getInstance();
            future.add(Calendar.MILLISECOND, (int) timeout);
            while (!future.before(Calendar.getInstance())) {
                try {
                    Thread.sleep(1000);
                    tgdbRunning = ProcessCheck.isProcessRunning(tgServer.getPid());
                    if (!tgdbRunning)
                        break;
                } catch (IOException | TGGeneralException | InterruptedException e) {
                    throw new TGAdminException("TGAdmin - " + e.getMessage(), output);
                }
            }
        } else { // wait forever for tgdb to stop
            while (true) {
                try {
                    Thread.sleep(1000);
                    tgdbRunning = ProcessCheck.isProcessRunning(tgServer.getPid());
                    if (!tgdbRunning)
                        break;
                } catch (IOException | TGGeneralException | InterruptedException e) {
                    throw new TGAdminException("TGAdmin - " + e.getMessage(), output);
                }
            }
        }
        if (tgdbRunning)
            throw new TGAdminException("TGAdmin - Server did not stop on time (after " + timeout + " msec)");

        long endProcTime = System.currentTimeMillis();
        long totalProcTime = endProcTime - TGAdmin.startProcTime;
        System.out.println(
                "TGAdmin - Server stop completed" + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : ""));
        tgServer.setRunning(false);
        tgServer.setPid(0);
        return output;
    }

    /**
     * Invoke TG admin synchronously. 
     * 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();
    }

    /**
     * Invoke TG admin synchronously. 
     * Admin operation blocks until it is completed.
     * 
     * @param tgServer TG server to connect to
     * @param tgNetListenerName Name of the net listener for TG Admin to connect to - if null connect to 1st one
     * @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(TGServer tgServer, String tgNetListenerName, String logFile, String logLevel,
            String cmd, int memSize, long timeout) throws TGAdminException {

        if (tgServer == null)
            throw new TGAdminException("TGAdmin - tgServer cannot be null");

        TGServer.NetListener netListener = tgServer.getNetListeners()[0]; // default get the 1st one
        String user = null;
        String pwd = null;
        String url = null;

        if (tgNetListenerName != null) {
            for (TGServer.NetListener net : tgServer.getNetListeners()) {
                if (net.getName().equals(tgNetListenerName)) {
                    netListener = net;
                }
            }

            String host = netListener.getHost();
            int port = netListener.getPort();
            user = tgServer.getSystemUser();
            pwd = tgServer.getSystemPwd();
            try {
                url = "tcp://" + ((netListener.isIPv6()) ? ("[" + host + ":" + port + "]") : (host + ":" + port));
            } catch (TGGeneralException e) {
                throw new TGAdminException("TGAdmin - " + e.getMessage());
            }
        }

        TGAdmin.showOperationBanner = true;
        return TGAdmin.invoke(tgServer.getHome().getAbsolutePath(), url, user, pwd, logFile, logLevel, cmd, memSize,
                timeout);
    }

    /**
     * Stop TG server asynchronously. 
     * Return after Admin operation completes but server will take extra time to really stop.
     * 
     * @param tgHome TG admin home
     * @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 waitToCompletion Number of milliseconds to wait for this call to return
     * 
     * @return Output console of stop operation 
     * @throws TGAdminException Admin execution fails 
     */
    public static String stopServer(String tgHome, String url, String user, String pwd, String logFile,
            String logLevel, long waitToCompletion) throws TGAdminException {

        String stopCmd = "stop server\ndisconnect\nexit";
        File cmdFile;
        try {
            cmdFile = new File(tgHome + "/stopAdminScript.txt");
            Files.write(Paths.get(cmdFile.toURI()), stopCmd.getBytes(StandardCharsets.UTF_8));
        } catch (IOException ioe) {
            throw new TGAdminException("TGAdmin - " + ioe.getMessage());
        }
        TGAdmin.showOperationBanner = false;
        String output = TGAdmin.invoke(tgHome, url, user, pwd, logFile, logLevel, cmdFile.getAbsolutePath(), -1,
                20000);
        try {
            Thread.sleep(waitToCompletion); // give some sec for tgdb server to die
        } catch (InterruptedException e) {
            ;
        }
        long endProcTime = System.currentTimeMillis();
        long totalProcTime = endProcTime - TGAdmin.startProcTime;
        if (TGAdmin.showStopServerBanner)
            System.out.println("TGAdmin - Server stop completed"
                    + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : ""));
        return output;
    }

    /**
     * Create a user. 
     * Operation blocks until it is completed.
     * 
     * @param tgServer TG server to create user from 
     * @param tgNetListenerName Name of the net listener for TG Admin to connect to - if null connect to 1st one
     * @param user username to be created
     * @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 timeout Number of milliseconds allowed to complete the stop server operation - If lower than 0 wait forever
     *
     * @return true if user creation succeeded 
     * @throws TGAdminException Admin execution fails or timeout occurs 
     */
    public static boolean createUser(TGServer tgServer, String tgNetListenerName, String user, String pwd,
            String logFile, String logLevel, long timeout) throws TGAdminException {

        if (tgServer == null)
            throw new TGAdminException("TGAdmin - tgServer cannot be null");

        if (user == null || pwd == null)
            throw new TGAdminException("TGAdmin - user or pwd cannot be null");

        final String userCreationSuccessMsg = "Successfully created user on server.";
        String showCmd = "create user " + user + " passwd=" + pwd + "\ndisconnect\nexit";
        File cmdFile;
        try {
            cmdFile = new File(tgServer.getHome().getAbsolutePath() + "/createUserAdminScript.txt");
            Files.write(Paths.get(cmdFile.toURI()), showCmd.getBytes(StandardCharsets.UTF_8));
        } catch (IOException ioe) {
            throw new TGAdminException("TGAdmin - " + ioe.getMessage());
        }

        TGServer.NetListener netListener = tgServer.getNetListeners()[0]; // default get the 1st one
        if (tgNetListenerName != null) {
            for (TGServer.NetListener net : tgServer.getNetListeners()) {
                if (net.getName().equals(tgNetListenerName)) {
                    netListener = net;
                }
            }
        }

        String host = netListener.getHost();
        int port = netListener.getPort();
        String sysUser = tgServer.getSystemUser();
        String sysPwd = tgServer.getSystemPwd();
        String url;
        try {
            url = "tcp://" + ((netListener.isIPv6()) ? ("[" + host + ":" + port + "]") : (host + ":" + port));
        } catch (TGGeneralException e) {
            throw new TGAdminException("TGAdmin - " + e.getMessage());
        }

        TGAdmin.showOperationBanner = false;
        String output = TGAdmin.invoke(tgServer.getHome().getAbsolutePath(), url, sysUser, sysPwd, logFile,
                logLevel, cmdFile.getAbsolutePath(), -1, timeout);
        long endProcTime = System.currentTimeMillis();
        long totalProcTime = endProcTime - TGAdmin.startProcTime;

        if (output.contains(userCreationSuccessMsg)) {
            System.out.println("TGAdmin - User creation succeeded"
                    + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : ""));
            return true;
        } else {
            System.out.println(
                    "TGAdmin - User creation failed" + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : ""));
            return false;
        }
    }

    /**
     * Kill a connection synchronously. 
     * Operation blocks until it is completed.
     * 
     * @param tgServer TG server to kill connections from
     * @param tgNetListenerName Name of the net listener for TG Admin to connect to - if null connect to 1st one
     * @param sessionID specify session ID to kill
     * @param logFile TG admin log file location - Generated by admin
     * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire
     * @param timeout Number of milliseconds allowed to complete the stop server operation - If lower than 0 wait forever
     *
     * @return Output console 
     * @throws TGAdminException Admin execution fails or timeout occurs 
     */
    public static String killConnection(TGServer tgServer, String tgNetListenerName, String sessionID,
            String logFile, String logLevel, long timeout) throws TGAdminException {

        if (tgServer == null)
            throw new TGAdminException("TGAdmin - tgServer cannot be null");

        String killCmd = "kill connection " + sessionID + "\ndisconnect\nexit";
        File cmdFile;
        try {
            cmdFile = new File(tgServer.getHome().getAbsolutePath() + "/killConnectionAdminScript.txt");
            Files.write(Paths.get(cmdFile.toURI()), killCmd.getBytes(StandardCharsets.UTF_8));
        } catch (IOException ioe) {
            throw new TGAdminException("TGAdmin - " + ioe.getMessage());
        }

        TGServer.NetListener netListener = tgServer.getNetListeners()[0]; // default get the 1st one
        if (tgNetListenerName != null) {
            for (TGServer.NetListener net : tgServer.getNetListeners()) {
                if (net.getName().equals(tgNetListenerName)) {
                    netListener = net;
                }
            }
        }

        String host = netListener.getHost();
        int port = netListener.getPort();
        String user = tgServer.getSystemUser();
        String pwd = tgServer.getSystemPwd();
        String url;
        try {
            url = "tcp://" + ((netListener.isIPv6()) ? ("[" + host + ":" + port + "]") : (host + ":" + port));
        } catch (TGGeneralException e) {
            throw new TGAdminException("TGAdmin - " + e.getMessage());
        }

        TGAdmin.showOperationBanner = false;
        String output = TGAdmin.invoke(tgServer.getHome().getAbsolutePath(), url, user, pwd, logFile, logLevel,
                cmdFile.getAbsolutePath(), -1, timeout);
        long endProcTime = System.currentTimeMillis();
        long totalProcTime = endProcTime - TGAdmin.startProcTime;
        System.out.println("TGAdmin - Kill connection completed"
                + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : ""));

        return output;
    }

    /**
     * Get connections for a given user. 
     * Operation blocks until it is completed.
     * 
     * @param tgServer TG server to get connections from
     * @param tgNetListenerName Name of the net listener for TG Admin to connect to - if null connect to 1st one
     * @param user User name to get the connections from
     * @param logFile TG admin log file location - Generated by admin
     * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire
     * @param timeout Number of milliseconds allowed to complete the stop server operation - If lower than 0 wait forever
     *
     * @return Array of session IDs belonging to the user
     * @throws TGAdminException Admin execution fails or timeout occurs 
     */
    public static String[] getConnectionsByUser(TGServer tgServer, String tgNetListenerName, String user,
            String logFile, String logLevel, long timeout) throws TGAdminException {

        String output = showConnections(tgServer, tgNetListenerName, logFile, logLevel, timeout);
        Scanner scanner = new Scanner(output);
        boolean counting = false;
        //int indexClientId;
        int indexSessionId = 0;
        //int adminConnectionCount = 0;
        List<String> connectionList = new ArrayList<String>();
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.contains("Client ID")) {
                counting = true;
                //indexClientId = line.indexOf("Client ID");
                indexSessionId = line.indexOf("Session ID");
            } else if (line.contains("----------"))
                counting = false;
            else if (line.contains("connection(s) returned")) {
                counting = false;
                //adminConnectionCount = Integer.parseInt(line.substring(0, line.indexOf(' ', 0)));
            } else if (counting) {
                if (line.contains(" " + user + " "))
                    connectionList.add(line.substring(indexSessionId, line.indexOf(' ', indexSessionId)));
            }
        }
        scanner.close();
        //if (connectionList.size() != adminConnectionCount)
        //   throw new TGAdminException("TGAdmin - Not able to determine number of connections");
        return connectionList.toArray(new String[0]);
    }

}