Example usage for java.lang Process waitFor

List of usage examples for java.lang Process waitFor

Introduction

In this page you can find the example usage for java.lang Process waitFor.

Prototype

public abstract int waitFor() throws InterruptedException;

Source Link

Document

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.

Usage

From source file:Run2.java

public static void main(String[] args) throws java.io.IOException {
    if (args.length != 1) {
        System.err.println("usage: java Run pathname");
        return;/*from  www . j a  v a2s  . co m*/
    }

    Process p = Runtime.getRuntime().exec(args[0]);

    InputStream is = p.getInputStream();
    int b;
    while ((b = is.read()) != -1)
        System.out.print((char) b);

    try {
        System.out.println("Exit status = " + p.waitFor());
    } catch (InterruptedException e) {
    }
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    ProcessBuilder launcher = new ProcessBuilder();
    Map<String, String> environment = launcher.environment();
    launcher.redirectErrorStream(true);/* ww  w  . j  a  v a 2  s. c  o m*/
    launcher.directory(new File("c:\\"));

    environment.put("name", "var");
    launcher.command("notepad.exe");
    Process p = launcher.start(); // And launch a new process
    BufferedReader output = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line;
    while ((line = output.readLine()) != null)
        System.out.println(line);

    // The process should be done now, but wait to be sure.
    p.waitFor();

}

From source file:ExecDemoLs.java

public static void main(String argv[]) throws IOException {

    final Process p; // Process tracks one external native process
    BufferedReader is; // reader for output of process
    String line;//from  ww w  . j a va  2  s .  c om

    p = Runtime.getRuntime().exec(PROGRAM);

    // Optional: start a thread to wait for the process to terminate.
    // Don't just wait in main line, but here set a "done" flag and
    // use that to control the main reading loop below.
    Thread waiter = new Thread() {
        public void run() {
            try {
                p.waitFor();
            } catch (InterruptedException ex) {
                // OK, just quit.
                return;
            }
            System.out.println("Program terminated!");
            done = true;
        }
    };
    waiter.start();

    // getInputStream gives an Input stream connected to
    // the process p's standard output (and vice versa). We use
    // that to construct a BufferedReader so we can readLine() it.
    is = new BufferedReader(new InputStreamReader(p.getInputStream()));

    while (!done && ((line = is.readLine()) != null))
        System.out.println(line);

    return;
}

From source file:azkaban.execapp.AzkabanExecutorServer.java

/**
 * Azkaban using Jetty//from  w w w. j  a  v  a  2  s .c  o  m
 *
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws Exception {
    // Redirect all std out and err messages into log4j
    StdOutErrRedirect.redirectOutAndErrToLog();

    logger.info("Starting Jetty Azkaban Executor...");
    Props azkabanSettings = AzkabanServer.loadProps(args);

    if (azkabanSettings == null) {
        logger.error("Azkaban Properties not loaded.");
        logger.error("Exiting Azkaban Executor Server...");
        return;
    }

    // Setup time zone
    if (azkabanSettings.containsKey(DEFAULT_TIMEZONE_ID)) {
        String timezone = azkabanSettings.getString(DEFAULT_TIMEZONE_ID);
        System.setProperty("user.timezone", timezone);
        TimeZone.setDefault(TimeZone.getTimeZone(timezone));
        DateTimeZone.setDefault(DateTimeZone.forID(timezone));

        logger.info("Setting timezone to " + timezone);
    }

    app = new AzkabanExecutorServer(azkabanSettings);

    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            try {
                logTopMemoryConsumers();
            } catch (Exception e) {
                logger.info(("Exception when logging top memory consumers"), e);
            }

            String host = app.getHost();
            int port = app.getPort();
            try {
                logger.info(String.format("Removing executor(host: %s, port: %s) entry from database...", host,
                        port));
                app.getExecutorLoader().removeExecutor(host, port);
            } catch (ExecutorManagerException ex) {
                logger.error(String.format("Exception when removing executor(host: %s, port: %s)", host, port),
                        ex);
            }

            logger.warn("Shutting down executor...");
            try {
                app.shutdownNow();
            } catch (Exception e) {
                logger.error("Error while shutting down http server.", e);
            }
        }

        public void logTopMemoryConsumers() throws Exception, IOException {
            if (new File("/bin/bash").exists() && new File("/bin/ps").exists()
                    && new File("/usr/bin/head").exists()) {
                logger.info("logging top memeory consumer");

                java.lang.ProcessBuilder processBuilder = new java.lang.ProcessBuilder("/bin/bash", "-c",
                        "/bin/ps aux --sort -rss | /usr/bin/head");
                Process p = processBuilder.start();
                p.waitFor();

                InputStream is = p.getInputStream();
                java.io.BufferedReader reader = new java.io.BufferedReader(new InputStreamReader(is));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    logger.info(line);
                }
                is.close();
            }
        }
    });
}

From source file:ServerStatus.java

License:asdf

/**
 * @param args the command line arguments
 *//*from w ww. ja va2  s. c o m*/
public static void main(String[] args)
        throws InterruptedException, FileNotFoundException, IOException, ParseException {
    FileReader reader = null;
    ArrayList<BankInfo2> BankArray = new ArrayList<BankInfo2>();
    reader = new FileReader(args[0]);
    JSONParser jp = new JSONParser();
    JSONObject doc = (JSONObject) jp.parse(reader);
    JSONObject banks = (JSONObject) doc.get("banks");
    //Set bankKeys = banks.keySet();
    //Object [] bankNames = bankKeys.toArray();
    Object[] bankNames = banks.keySet().toArray();
    for (int i = 0; i < bankNames.length; i++) {

        //System.out.println(bankNames[i]);
        String bname = (String) bankNames[i];
        BankInfo2 binfo = new BankInfo2(bname);
        JSONObject banki = (JSONObject) banks.get(bname);
        JSONArray chain = (JSONArray) banki.get("chain");
        int chainLength = chain.size();
        //System.out.println(chainLength);
        for (Object chain1 : chain) {

            JSONObject serv = (JSONObject) chain1;
            ServerInfo sinfo = new ServerInfo((String) serv.get("ip"), serv.get("port").toString(),
                    serv.get("start_delay").toString(), serv.get("lifetime").toString(),
                    serv.get("receive").toString(), serv.get("send").toString());
            binfo.servers.add(sinfo);
            //System.out.println(serv.get("ip") + ":" + serv.get("port"));
        }
        BankArray.add(binfo);
    }
    //System.out.println("Done Processing Servers");
    JSONArray clients = (JSONArray) doc.get("clients");
    ArrayList<ClientInfo> clientsList = new ArrayList<ClientInfo>();
    for (int i = 0; i < clients.size(); i++) {
        JSONObject client_i = (JSONObject) clients.get(i);
        //This is for hard coded requests in the json file
        //System.out.println(client_i);
        //System.out.println(client_i.getClass());
        String typeOfClient = client_i.get("requests").getClass().toString();

        //This is for a client that has hardCoded requests
        if (typeOfClient.equals("class org.json.simple.JSONArray")) {
            //System.out.println("JSONArray");
            JSONArray requests = (JSONArray) client_i.get("requests");
            ClientInfo c = new ClientInfo(client_i.get("reply_timeout").toString(),
                    client_i.get("request_retries").toString(), client_i.get("resend_head").toString());
            c.prob_failure = client_i.get("prob_failure").toString();
            c.msg_send_delay = client_i.get("msg_delay").toString();
            System.out.println(
                    "Successfully added prob failure and msg_send " + c.prob_failure + "," + c.msg_send_delay);
            ArrayList<RequestInfo> req_list = new ArrayList<RequestInfo>();
            for (int j = 0; j < requests.size(); j++) {
                JSONObject request_j = (JSONObject) requests.get(j);
                String req = request_j.get("request").toString();
                String bank = request_j.get("" + "bank").toString();
                String acc = request_j.get("account").toString();
                String seq = request_j.get("seq_num").toString();
                String amt = null;
                try {
                    amt = request_j.get("amount").toString();
                } catch (NullPointerException e) {
                    //System.out.println("Amount not specified.");
                }
                RequestInfo r;
                if (amt == null) {
                    r = new RequestInfo(req, bank, acc, seq);
                } else {
                    r = new RequestInfo(req, bank, acc, amt, seq);
                }
                //RequestInfo r = new RequestInfo(request_j.get("request").toString(), request_j.get("bank").toString(), request_j.get("account").toString(), request_j.get("amount").toString());
                req_list.add(r);
            }
            c.requests = req_list;
            c.PortNumber = 60000 + i;
            clientsList.add(c);
            //System.out.println(client_i);
        }
        //This is for Random client requests
        else if (typeOfClient.equals("class org.json.simple.JSONObject")) {
            JSONObject randomReq = (JSONObject) client_i.get("requests");
            String seed = randomReq.get("seed").toString();
            String num_requests = randomReq.get("num_requests").toString();
            String prob_balance = randomReq.get("prob_balance").toString();
            String prob_deposit = randomReq.get("prob_deposit").toString();
            String prob_withdraw = randomReq.get("prob_withdrawal").toString();
            String prob_transfer = randomReq.get("prob_transfer").toString();
            //ClientInfo c = new ClientInfo(true, seed, num_requests, prob_balance, prob_deposit, prob_withdraw, prob_transfer);
            ClientInfo c = new ClientInfo(client_i.get("reply_timeout").toString(),
                    client_i.get("request_retries").toString(), client_i.get("resend_head").toString(), seed,
                    num_requests, prob_balance, prob_deposit, prob_withdraw, prob_transfer);
            c.PortNumber = 60000 + i;
            clientsList.add(c);
        }
    }
    //System.out.println(clients.size());
    double lowerPercent = 0.0;
    double upperPercent = 1.0;
    double result;
    String bankChainInfoMaster = "";
    for (int x = 0; x < BankArray.size(); x++) {
        BankInfo2 analyze = BankArray.get(x);
        String chain = analyze.bank_name + "#";
        //analyze.servers
        for (int j = 0; j < analyze.servers.size(); j++) {
            if (analyze.servers.get(j).Start_delay.equals("0")) {
                if (j == 0) {
                    chain += analyze.servers.get(j).Port;
                } else {
                    chain += "#" + analyze.servers.get(j).Port;
                }
            }
        }
        if (x == 0) {
            bankChainInfoMaster += chain;
        } else {
            bankChainInfoMaster += "@" + chain;
        }
    }
    //System.out.println("CHAIN: "+ bankChainInfoMaster);

    String clientInfoMaster = "";
    for (int x = 0; x < clientsList.size(); x++) {
        ClientInfo analyze = clientsList.get(x);
        if (x == 0) {
            clientInfoMaster += analyze.PortNumber;
        } else {
            clientInfoMaster += "#" + analyze.PortNumber;
        }

    }
    //System.out.println("Clients: "+ clientInfoMaster);

    //RUN MASTER HERE 
    String MasterPort = "49999";
    String masterExec = "java Master " + MasterPort + " " + clientInfoMaster + " " + bankChainInfoMaster;
    Process masterProcess = Runtime.getRuntime().exec(masterExec);
    System.out.println(masterExec);
    ArrayList<ServerInfoForClient> servInfoCli = new ArrayList<ServerInfoForClient>();

    // List of all servers is saved so that we can wait for them to exit.
    ArrayList<Process> serverPros = new ArrayList<Process>();
    //ArrayList<String> execServs = new ArrayList<String>();
    for (int i = 0; i < BankArray.size(); i++) {
        BankInfo2 analyze = BankArray.get(i);
        //System.out.println(analyze.bank_name);
        //One server in the chain
        String execCmd = "java Server ";
        String hIP = "", hPort = "", tIP = "", tPort = "", bn = "";
        bn = analyze.bank_name;
        boolean joinFlag = false;
        if (analyze.servers.size() == 2 && analyze.servers.get(1).Start_delay.equals("0")) {
            joinFlag = false;
        } else {
            joinFlag = true;
        }

        if (analyze.servers.size() == 1 && joinFlag == false) {
            //if(analyze.servers.size() == 1){
            ServerInfo si = analyze.servers.get(0);
            execCmd += "HEAD_TAIL " + si.IP + ":" + si.Port;
            execCmd += " localhost:0 localhost:0 localhost:" + MasterPort + " " + si.Start_delay + " "
                    + si.Lifetime + " " + si.Receive + " " + si.Send + " " + analyze.bank_name;
            ;
            hIP = si.IP;
            hPort = si.Port;
            tIP = si.IP;
            tPort = si.Port;
            System.out.println(execCmd);
            Thread.sleep(500);
            Process pro = Runtime.getRuntime().exec(execCmd);
            serverPros.add(pro);
            //}
        } else if (analyze.servers.size() == 2 && joinFlag == true) {
            ServerInfo si = analyze.servers.get(0);
            execCmd += "HEAD_TAIL " + si.IP + ":" + si.Port;
            execCmd += " localhost:0 localhost:0 localhost:" + MasterPort + " " + si.Start_delay + " "
                    + si.Lifetime + " " + si.Receive + " " + si.Send + " " + analyze.bank_name;
            ;
            hIP = si.IP;
            hPort = si.Port;
            tIP = si.IP;
            tPort = si.Port;
            System.out.println(execCmd);
            Thread.sleep(500);
            Process pro = Runtime.getRuntime().exec(execCmd);
            serverPros.add(pro);

            execCmd = "java Server ";
            ServerInfo si2 = analyze.servers.get(1);
            execCmd += "TAIL " + si2.IP + ":" + si2.Port;
            execCmd += " localhost:0 localhost:0 localhost:" + MasterPort + " " + si2.Start_delay + " "
                    + si2.Lifetime + " " + si2.Receive + " " + si2.Send + " " + analyze.bank_name;
            ;
            hIP = si.IP;
            hPort = si.Port;
            tIP = si.IP;
            tPort = si.Port;
            System.out.println(execCmd);
            Thread.sleep(500);
            Process pro2 = Runtime.getRuntime().exec(execCmd);
            serverPros.add(pro2);
        } else {
            int icount = 0;
            for (int x = 0; x < analyze.servers.size(); x++) {
                ServerInfo si = analyze.servers.get(x);
                if (si.Start_delay.equals("0")) {
                    icount++;
                }
            }
            System.out.println("icount:" + icount);
            for (int j = 0; j < icount; j++) {
                //for(int j = 0; j < analyze.servers.size(); j++){
                execCmd = "java Server ";
                ServerInfo si = analyze.servers.get(j);
                //Head server
                if (j == 0) {
                    ServerInfo siSucc = analyze.servers.get(j + 1);
                    execCmd += "HEAD " + si.IP + ":" + si.Port + " ";
                    execCmd += "localhost:0 " + siSucc.IP + ":" + siSucc.Port + " localhost:" + MasterPort;
                    execCmd += " " + si.Start_delay + " " + si.Lifetime + " " + si.Receive + " " + si.Send + " "
                            + analyze.bank_name;
                    System.out.println(execCmd);
                    hIP = si.IP;
                    hPort = si.Port;

                }
                //Tail Server
                else if (j == (icount - 1)) {//analyze.servers.size() - 1) ){
                    ServerInfo siPred = analyze.servers.get(j - 1);
                    execCmd += "TAIL " + si.IP + ":" + si.Port + " ";
                    execCmd += siPred.IP + ":" + siPred.Port + " localhost:0 localhost:" + MasterPort;
                    execCmd += " " + si.Start_delay + " " + si.Lifetime + " " + si.Receive + " " + si.Send + " "
                            + analyze.bank_name;
                    tIP = si.IP;
                    tPort = si.Port;
                    System.out.println(execCmd);
                }
                //Middle Server
                else {
                    ServerInfo siSucc = analyze.servers.get(j + 1);
                    ServerInfo siPred = analyze.servers.get(j - 1);
                    execCmd += "MIDDLE " + si.IP + ":" + si.Port + " ";
                    execCmd += siPred.IP + ":" + siPred.Port + " " + siSucc.IP + ":" + siSucc.Port
                            + " localhost:" + MasterPort;
                    execCmd += " " + si.Start_delay + " " + si.Lifetime + " " + si.Receive + " " + si.Send + " "
                            + analyze.bank_name;
                    System.out.println(execCmd);
                }
                Thread.sleep(500);
                Process pro = Runtime.getRuntime().exec(execCmd);
                serverPros.add(pro);
            }
            for (int j = icount; j < analyze.servers.size(); j++) {
                execCmd = "java Server ";
                ServerInfo si = analyze.servers.get(j);
                ServerInfo siPred = analyze.servers.get(j - 1);
                execCmd += "TAIL " + si.IP + ":" + si.Port + " ";
                execCmd += siPred.IP + ":" + siPred.Port + " localhost:0 localhost:" + MasterPort;
                execCmd += " " + si.Start_delay + " " + si.Lifetime + " " + si.Receive + " " + si.Send + " "
                        + analyze.bank_name;
                tIP = si.IP;
                tPort = si.Port;
                System.out.println(execCmd);
                Thread.sleep(500);
                Process pro = Runtime.getRuntime().exec(execCmd);
                serverPros.add(pro);
            }
        }
        ServerInfoForClient newServInfoForCli = new ServerInfoForClient(hPort, hIP, tPort, tIP, bn);
        servInfoCli.add(newServInfoForCli);
    }
    String banksCliParam = "";
    for (int i = 0; i < servInfoCli.size(); i++) {
        ServerInfoForClient temp = servInfoCli.get(i);
        String add = "@" + temp.bank_name + "#" + temp.HeadIP + ":" + temp.HeadPort + "#" + temp.TailIP + ":"
                + temp.TailPort;
        banksCliParam += add;
    }
    banksCliParam = banksCliParam.replaceFirst("@", "");
    //System.out.println(banksCliParam);

    // List of clients is saved so that we can wait for them to exit.
    ArrayList<Process> clientPros = new ArrayList<Process>();
    for (int i = 0; i < clientsList.size(); i++) {
        ClientInfo analyze = clientsList.get(i);
        String requestsString = "";
        if (analyze.isRandom) {
            double balance = Double.parseDouble(analyze.prob_balance);
            //System.out.println(analyze.prob_balance);
            double deposit = Double.parseDouble(analyze.prob_deposit);
            double withdraw = Double.parseDouble(analyze.prob_withdraw);
            int numRequests = Integer.parseInt(analyze.num_requests);
            for (int j = 0; j < numRequests; j++) {
                result = Math.random() * (1.0 - 0.0) + 0.0;
                int randAccount = (int) (Math.random() * (10001 - 0) + 0);
                double randAmount = Math.random() * (10001.00 - 0.0) + 0;
                int adjustMoney = (int) randAmount * 100;
                randAmount = (double) adjustMoney / 100.00;
                int randBank = (int) (Math.random() * (bankNames.length - 0) + 0);
                if (result < balance) {
                    //withdrawal#clientIPPORT%bank_name%accountnum%seq#amount
                    requestsString += "@balance#localhost:" + analyze.PortNumber + "%" + bankNames[randBank]
                            + "%" + randAccount + "%" + j;
                } else if (result < (deposit + balance)) {
                    requestsString += "@deposit#localhost:" + analyze.PortNumber + "%" + bankNames[randBank]
                            + "%" + randAccount + "%" + j + "#" + randAmount;
                } else {
                    requestsString += "@withdrawal#localhost:" + analyze.PortNumber + "%" + bankNames[randBank]
                            + "%" + randAccount + "%" + j + "#" + randAmount;
                }
            }

        } else {
            for (int j = 0; j < analyze.requests.size(); j++) {

                RequestInfo req = analyze.requests.get(j);
                //System.out.println("Sequence ###" + req.sequenceNum);
                if (req.request.equals("balance")) {
                    requestsString += "@" + req.request + "#localhost:" + analyze.PortNumber + "%"
                            + req.bankName + "%" + req.accountNum + "%" + req.sequenceNum;
                } else {
                    requestsString += "@" + req.request + "#localhost:" + analyze.PortNumber + "%"
                            + req.bankName + "%" + req.accountNum + "%" + req.sequenceNum + "#" + req.amount;
                }

            }
        }
        requestsString = requestsString.replaceFirst("@", "");
        String execCommand;
        int p = 60000 + i;
        if (analyze.isRandom) {
            execCommand = "java Client localhost:" + p + " " + banksCliParam + " " + requestsString + " "
                    + analyze.reply_timeout + " " + analyze.request_retries + " " + analyze.resend_head + " "
                    + analyze.prob_failure + " " + analyze.msg_send_delay + " " + analyze.prob_balance + ","
                    + analyze.prob_deposit + "," + analyze.prob_withdraw + "," + analyze.prob_transfer;
        } else {
            execCommand = "java Client localhost:" + p + " " + banksCliParam + " " + requestsString + " "
                    + analyze.reply_timeout + " " + analyze.request_retries + " " + analyze.resend_head + " "
                    + analyze.prob_failure + " " + analyze.msg_send_delay;

        }
        Thread.sleep(500);
        System.out.println(execCommand);
        System.out.println("Client " + (i + 1) + " started");
        Process cliPro = Runtime.getRuntime().exec(execCommand);
        clientPros.add(cliPro);
        //System.out.println(requestsString);
    }
    // Wait for all the clients to terminate
    for (Process clientPro : clientPros) {
        try {
            clientPro.waitFor();
            System.out.println("Client process finished.");
        } catch (InterruptedException e) {
            System.out.println("Interrupted while waiting for client.");
        }
    }
    // Sleep for two seconds
    Thread.sleep(2000);
    // Force termination of the servers
    for (Process serverPro : serverPros) {
        serverPro.destroy();
        System.out.println("Killed server.");
    }
    masterProcess.destroy();
    System.out.println("Killed Master");
    //System.out.println("asdf");
}

From source file:ExecDemoWait.java

public static void main(String argv[]) throws IOException {

    // A Runtime object has methods for dealing with the OS
    Runtime r = Runtime.getRuntime();
    Process p; // Process tracks one external native process
    BufferedReader is; // reader for output of process
    String line;//from w  ww. ja v a2 s  . c o m

    // Our argv[0] contains the program to run; remaining elements
    // of argv contain args for the target program. This is just
    // what is needed for the String[] form of exec.
    p = r.exec(argv);

    System.out.println("In Main after exec");

    // getInputStream gives an Input stream connected to
    // the process p's standard output. Just use it to make
    // a BufferedReader to readLine() what the program writes out.
    is = new BufferedReader(new InputStreamReader(p.getInputStream()));

    while ((line = is.readLine()) != null)
        System.out.println(line);

    System.out.println("In Main after EOF");
    System.out.flush();
    try {
        p.waitFor(); // wait for process to complete
    } catch (InterruptedException e) {
        System.err.println(e); // "Can'tHappen"
        return;
    }
    System.err.println("Process done, exit status was " + p.exitValue());
    return;
}

From source file:azkaban.webapp.AzkabanWebServer.java

/**
 * Azkaban using Jetty//from w  w w .  j  a  v  a2  s.c om
 *
 * @param args
 */
public static void main(String[] args) throws Exception {
    logger.info("Starting Jetty Azkaban Web Server...");
    Props azkabanSettings = AzkabanServer.loadProps(args);

    if (azkabanSettings == null) {
        logger.error("Azkaban Properties not loaded.");
        logger.error("Exiting Azkaban...");
        return;
    }

    int maxThreads = azkabanSettings.getInt("jetty.maxThreads", DEFAULT_THREAD_NUMBER);
    boolean isStatsOn = azkabanSettings.getBoolean("jetty.connector.stats", true);
    logger.info("Setting up connector with stats on: " + isStatsOn);

    boolean ssl;
    int port;
    final Server server = new Server();
    if (azkabanSettings.getBoolean("jetty.use.ssl", true)) {
        int sslPortNumber = azkabanSettings.getInt("jetty.ssl.port", DEFAULT_SSL_PORT_NUMBER);
        port = sslPortNumber;
        ssl = true;
        logger.info(
                "Setting up Jetty Https Server with port:" + sslPortNumber + " and numThreads:" + maxThreads);

        SslSocketConnector secureConnector = new SslSocketConnector();
        secureConnector.setPort(sslPortNumber);
        secureConnector.setKeystore(azkabanSettings.getString("jetty.keystore"));
        secureConnector.setPassword(azkabanSettings.getString("jetty.password"));
        secureConnector.setKeyPassword(azkabanSettings.getString("jetty.keypassword"));
        secureConnector.setTruststore(azkabanSettings.getString("jetty.truststore"));
        secureConnector.setTrustPassword(azkabanSettings.getString("jetty.trustpassword"));
        secureConnector.setHeaderBufferSize(MAX_HEADER_BUFFER_SIZE);

        // set up vulnerable cipher suites to exclude
        List<String> cipherSuitesToExclude = azkabanSettings.getStringList("jetty.excludeCipherSuites");
        logger.info("Excluded Cipher Suites: " + String.valueOf(cipherSuitesToExclude));
        if (cipherSuitesToExclude != null && !cipherSuitesToExclude.isEmpty()) {
            secureConnector.setExcludeCipherSuites(cipherSuitesToExclude.toArray(new String[0]));
        }

        server.addConnector(secureConnector);
    } else {
        ssl = false;
        port = azkabanSettings.getInt("jetty.port", DEFAULT_PORT_NUMBER);
        SocketConnector connector = new SocketConnector();
        connector.setPort(port);
        connector.setHeaderBufferSize(MAX_HEADER_BUFFER_SIZE);
        server.addConnector(connector);
    }

    // setting stats configuration for connectors
    for (Connector connector : server.getConnectors()) {
        connector.setStatsOn(isStatsOn);
    }

    String hostname = azkabanSettings.getString("jetty.hostname", "localhost");
    azkabanSettings.put("server.hostname", hostname);
    azkabanSettings.put("server.port", port);
    azkabanSettings.put("server.useSSL", String.valueOf(ssl));

    app = new AzkabanWebServer(server, azkabanSettings);

    boolean checkDB = azkabanSettings.getBoolean(AzkabanDatabaseSetup.DATABASE_CHECK_VERSION, false);
    if (checkDB) {
        AzkabanDatabaseSetup setup = new AzkabanDatabaseSetup(azkabanSettings);
        setup.loadTableInfo();
        if (setup.needsUpdating()) {
            logger.error("Database is out of date.");
            setup.printUpgradePlan();

            logger.error("Exiting with error.");
            System.exit(-1);
        }
    }

    try {
        JdbcExecutorLoader jdbcExecutorLoader = new JdbcExecutorLoader(azkabanSettings);
        jdbcExecutorLoader.updateExecutableJobsOnStartUp();
    } catch (Exception e) {
        logger.warn("There could be some jobs KILLED by this server restart event,"
                + "but their status still erroneously being shown as RUNNING." + "Please run the SQL "
                + "[update execution_jobs join execution_flows"
                + " on execution_jobs.exec_id = execution_flows.exec_id"
                + " set execution_jobs.status = 70 where"
                + " execution_jobs.status = 30 and execution_flows.status = 70]"
                + "on the database to rectify their status", e);
    }

    QueuedThreadPool httpThreadPool = new QueuedThreadPool(maxThreads);
    server.setThreadPool(httpThreadPool);

    String staticDir = azkabanSettings.getString("web.resource.dir", DEFAULT_STATIC_DIR);
    logger.info("Setting up web resource dir " + staticDir);
    Context root = new Context(server, "/", Context.SESSIONS);
    root.setMaxFormContentSize(MAX_FORM_CONTENT_SIZE);

    String defaultServletPath = azkabanSettings.getString("azkaban.default.servlet.path", "/index");
    root.setResourceBase(staticDir);
    ServletHolder indexRedirect = new ServletHolder(new IndexRedirectServlet(defaultServletPath));
    root.addServlet(indexRedirect, "/");
    ServletHolder index = new ServletHolder(new ProjectServlet());
    root.addServlet(index, "/index");

    ServletHolder staticServlet = new ServletHolder(new DefaultServlet());
    root.addServlet(staticServlet, "/css/*");
    root.addServlet(staticServlet, "/js/*");
    root.addServlet(staticServlet, "/images/*");
    root.addServlet(staticServlet, "/fonts/*");
    root.addServlet(staticServlet, "/favicon.ico");

    root.addServlet(new ServletHolder(new ProjectManagerServlet()), "/manager");
    root.addServlet(new ServletHolder(new ExecutorServlet()), "/executor");
    root.addServlet(new ServletHolder(new HistoryServlet()), "/history");
    root.addServlet(new ServletHolder(new ScheduleServlet()), "/schedule");
    root.addServlet(new ServletHolder(new JMXHttpServlet()), "/jmx");
    root.addServlet(new ServletHolder(new TriggerManagerServlet()), "/triggers");
    root.addServlet(new ServletHolder(new StatsServlet()), "/stats");
    root.addServlet(new ServletHolder(new AboutServlet()), "/about");
    root.addServlet(new ServletHolder(new FileEditorServlet()), "/fileeditor");

    ServletHolder restliHolder = new ServletHolder(new RestliServlet());
    restliHolder.setInitParameter("resourcePackages", "azkaban.restli");
    root.addServlet(restliHolder, "/restli/*");

    String viewerPluginDir = azkabanSettings.getString("viewer.plugin.dir", "plugins/viewer");
    loadViewerPlugins(root, viewerPluginDir, app.getVelocityEngine());

    // triggerplugin
    String triggerPluginDir = azkabanSettings.getString("trigger.plugin.dir", "plugins/triggers");
    Map<String, TriggerPlugin> triggerPlugins = loadTriggerPlugins(root, triggerPluginDir, app);
    app.setTriggerPlugins(triggerPlugins);
    // always have basic time trigger
    // TODO: find something else to do the job
    app.getTriggerManager().start();

    root.setAttribute(ServerConstants.AZKABAN_SERVLET_CONTEXT_KEY, app);
    try {
        server.start();
    } catch (Exception e) {
        logger.warn(e);
        Utils.croak(e.getMessage(), 1);
    }

    Runtime.getRuntime().addShutdownHook(new Thread() {

        public void run() {
            try {
                logTopMemoryConsumers();
            } catch (Exception e) {
                logger.info(("Exception when logging top memory consumers"), e);
            }

            logger.info("Shutting down http server...");
            try {
                app.close();
                server.stop();
                server.destroy();
            } catch (Exception e) {
                logger.error("Error while shutting down http server.", e);
            }
            logger.info("kk thx bye.");
        }

        public void logTopMemoryConsumers() throws Exception, IOException {
            if (new File("/bin/bash").exists() && new File("/bin/ps").exists()
                    && new File("/usr/bin/head").exists()) {
                logger.info("logging top memeory consumer");

                java.lang.ProcessBuilder processBuilder = new java.lang.ProcessBuilder("/bin/bash", "-c",
                        "/bin/ps aux --sort -rss | /usr/bin/head");
                Process p = processBuilder.start();
                p.waitFor();

                InputStream is = p.getInputStream();
                java.io.BufferedReader reader = new java.io.BufferedReader(new InputStreamReader(is));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    logger.info(line);
                }
                is.close();
            }
        }
    });
    logger.info("Server running on " + (ssl ? "ssl" : "") + " port " + port + ".");
}

From source file:de.prozesskraft.ptest.Launch.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    //      try//from  w ww  .  ja  v a 2  s  .  c om
    //      {
    //         if (args.length != 3)
    //         {
    //            System.out.println("Please specify processdefinition file (xml) and an outputfilename");
    //         }
    //         
    //      }
    //      catch (ArrayIndexOutOfBoundsException e)
    //      {
    //         System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString());
    //      }

    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Launch.class) + "/" + "../etc/ptest-launch.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option ospl = OptionBuilder.withArgName("DIR").hasArg()
            .withDescription("[mandatory] directory with sample input data")
            //            .isRequired()
            .create("spl");

    Option oinstancedir = OptionBuilder.withArgName("DIR").hasArg()
            .withDescription("[mandatory, default: .] directory where the test will be performed")
            //            .isRequired()
            .create("instancedir");

    Option ocall = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory, default: random call in spl-directory] file with call-string")
            //            .isRequired()
            .create("call");

    Option oaltapp = OptionBuilder.withArgName("STRING").hasArg()
            .withDescription(
                    "[optional] alternative app. this String replaces the first line of the .call-file.")
            //            .isRequired()
            .create("altapp");

    Option oaddopt = OptionBuilder.withArgName("STRING").hasArg()
            .withDescription("[optional] add an option to the call.")
            //            .isRequired()
            .create("addopt");

    Option onolaunch = new Option("nolaunch",
            "only create instance directory, copy all spl files, but do NOT launch the process");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(ospl);
    options.addOption(oinstancedir);
    options.addOption(ocall);
    options.addOption(oaltapp);
    options.addOption(oaddopt);
    options.addOption(onolaunch);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        commandline = parser.parse(options, args);
    } catch (Exception exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        exiter();
    }

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("launch", options);
        System.exit(0);
    }

    else if (commandline.hasOption("v")) {
        System.out.println("web:     " + web);
        System.out.println("author: " + author);
        System.out.println("version:" + version);
        System.out.println("date:     " + date);
        System.exit(0);
    }

    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    boolean error = false;
    String spl = null;
    String instancedir = null;
    String call = null;
    String altapp = null;
    ArrayList<String> addopt = new ArrayList<String>();

    // spl initialisieren
    if (commandline.hasOption("spl")) {
        spl = commandline.getOptionValue("spl");
    } else {
        System.err.println("option -spl is mandatory");
        error = true;
    }

    // instancedir initialisieren
    if (commandline.hasOption("instancedir")) {
        instancedir = commandline.getOptionValue("instancedir");
    } else {
        instancedir = System.getProperty("user.dir");
    }

    // call initialisieren
    if (commandline.hasOption("call")) {
        call = commandline.getOptionValue("call");
    }

    // altapp initialisieren
    if (commandline.hasOption("altapp")) {
        altapp = commandline.getOptionValue("altapp");
    }

    // addopt initialisieren
    if (commandline.hasOption("addopt")) {
        for (String actString : commandline.getOptionValues("addopt")) {
            addopt.add(actString);
        }
    }

    // wenn fehler, dann exit
    if (error) {
        exiter();
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/

    // das erste spl-objekt geben lassen
    Spl actSpl = new Splset(spl).getSpl().get(0);

    // den call, result und altapp ueberschreiben
    actSpl.setName("default");

    if (call != null) {
        actSpl.setCall(new java.io.File(call));
    }
    if (actSpl.getCall() == null) {
        System.err.println("error: no call information found");
        System.exit(1);
    }

    if (altapp != null) {
        actSpl.setAltapp(altapp);
    }

    if (addopt.size() > 0) {
        actSpl.setAddopt(addopt);
    }

    actSpl.setResult(null);

    // das instancedir erstellen
    java.io.File actSplInstanceDir = new java.io.File(instancedir);
    System.err.println("info: creating directory " + actSplInstanceDir.getCanonicalPath());
    actSplInstanceDir.mkdirs();

    // Inputdaten in das InstanceDir exportieren
    actSpl.exportInput(actSplInstanceDir);

    // exit, wenn --nolaunch
    if (commandline.hasOption("nolaunch")) {
        System.err.println("info: exiting, because of -nolaunch");
        System.exit(0);
    }

    // das logfile des Syscalls (zum debuggen des programms "process syscall" gedacht)
    String AbsLogSyscallWrapper = actSplInstanceDir.getCanonicalPath() + "/.log";
    String AbsStdout = actSplInstanceDir.getCanonicalPath() + "/.stdout.txt";
    String AbsStderr = actSplInstanceDir.getCanonicalPath() + "/.stderr.txt";
    String AbsPid = actSplInstanceDir.getCanonicalPath() + "/.pid";

    // beim starten von syscall werden parameter mit whitespaces an diesen auseinandergeschnitten und der nachfolgende aufruf schlaeft fehl
    // deshalb sollen whitespaces durch eine 'zeichensequenz' ersetzt werden
    // syscall ersetzt die zeichensequenz wieder zurueck in ein " "
    ArrayList<String> callFuerSyscall = actSpl.getCallAsArrayList();
    ArrayList<String> callFuerSyscallMitTrennzeichen = new ArrayList<String>();
    for (String actString : callFuerSyscall) {
        callFuerSyscallMitTrennzeichen.add(actString.replaceAll("\\s+", "%WHITESPACE%"));
    }

    try {
        // den Aufrufstring fuer die externe App (process syscall --version 0.6.0)) splitten
        // beim aufruf muss das erste argument im path zu finden sein, sonst gibt die fehlermeldung 'no such file or directory'
        ArrayList<String> processSyscallWithArgs = new ArrayList<String>(
                Arrays.asList(ini.get("apps", "pkraft-syscall").split(" ")));

        // die sonstigen argumente hinzufuegen
        processSyscallWithArgs.add("-call");
        processSyscallWithArgs.add(String.join(" ", callFuerSyscallMitTrennzeichen));
        //         processSyscallWithArgs.add("\""+call+"\"");
        processSyscallWithArgs.add("-stdout");
        processSyscallWithArgs.add(AbsStdout);
        processSyscallWithArgs.add("-stderr");
        processSyscallWithArgs.add(AbsStderr);
        processSyscallWithArgs.add("-pid");
        processSyscallWithArgs.add(AbsPid);
        processSyscallWithArgs.add("-mylog");
        processSyscallWithArgs.add(AbsLogSyscallWrapper);
        processSyscallWithArgs.add("-maxrun");
        processSyscallWithArgs.add("" + 3000);

        // erstellen prozessbuilder
        ProcessBuilder pb = new ProcessBuilder(processSyscallWithArgs);

        // erweitern des PATHs um den prozesseigenen path
        //         Map<String,String> env = pb.environment();
        //         String path = env.get("PATH");
        //         log("debug", "$PATH="+path);
        //         path = this.parent.getAbsPath()+":"+path;
        //         env.put("PATH", path);
        //         log("info", "path: "+path);

        // setzen der aktuellen directory (in der syscall ausgefuehrt werden soll)
        java.io.File directory = new java.io.File(instancedir);
        System.err.println("info: setting execution directory to: " + directory.getCanonicalPath());
        pb.directory(directory);

        // zum debuggen ein paar ausgaben
        //         java.lang.Process p1 = Runtime.getRuntime().exec("date >> ~/tmp.debug.work.txt");
        //         p1.waitFor();
        //         java.lang.Process p2 = Runtime.getRuntime().exec("ls -la "+this.getParent().getAbsdir()+" >> ~/tmp.debug.work.txt");
        //         p2.waitFor();
        //         java.lang.Process pro = Runtime.getRuntime().exec("nautilus");
        //         java.lang.Process superpro = Runtime.getRuntime().exec(processSyscallWithArgs.toArray(new String[processSyscallWithArgs.size()]));
        //         p3.waitFor();

        System.err.println("info: calling: " + pb.command());

        // starten des prozesses
        java.lang.Process sysproc = pb.start();

        // einfangen der stdout- und stderr des subprozesses
        InputStream is_stdout = sysproc.getInputStream();
        InputStream is_stderr = sysproc.getErrorStream();

        // Send your InputStream to an InputStreamReader:
        InputStreamReader isr_stdout = new InputStreamReader(is_stdout);
        InputStreamReader isr_stderr = new InputStreamReader(is_stderr);

        // That needs to go to a BufferedReader:
        BufferedReader br_stdout = new BufferedReader(isr_stdout);
        BufferedReader br_stderr = new BufferedReader(isr_stderr);

        //         // oeffnen der OutputStreams zu den Ausgabedateien
        //         FileWriter fw_stdout = new FileWriter(sStdout);
        //         FileWriter fw_stderr = new FileWriter(sStderr);

        // zeilenweise in die files schreiben
        String line_out = new String();
        String line_err = new String();

        while (br_stdout.readLine() != null) {
        }

        //         while (((line_out = br_stdout.readLine()) != null) || ((line_err = br_stderr.readLine()) != null))
        //         {
        //            if (!(line_out == null))
        //            {
        //               System.out.println(line_out);
        //               System.out.flush();
        //            }
        //            if (!(line_err == null))
        //            {
        //               System.err.println(line_err);
        //               System.err.flush();
        //            }
        //         }

        int exitValue = sysproc.waitFor();

        //         fw_stdout.close();
        //         fw_stderr.close();

        System.err.println("exitvalue: " + exitValue);

        sysproc.destroy();

        System.exit(exitValue);

        //         alternativer aufruf
        //         java.lang.Process sysproc = Runtime.getRuntime().exec(StringUtils.join(args_for_syscall, " "));

        //         log("info", "call executed. pid="+sysproc.hashCode());

        // wait 2 seconds for becoming the pid-file visible
        //         Thread.sleep(2000);

        //         int exitValue = sysproc.waitFor();

        //         // der prozess soll bis laengstens
        //         if(exitValue != 0)
        //         {
        //            System.err.println("error: call returned a value indicating an error: "+exitValue);
        //         }
        //         else
        //         {
        //            System.err.println("info: call returned value: "+exitValue);
        //         }

        //         System.err.println("info: "+new Date().toString());
        //         System.err.println("info: bye");
        //
        //         sysproc.destroy();
        //
        //         System.exit(sysproc.exitValue());
    } catch (Exception e2) {
        System.err.println("error: " + e2.getMessage());
        System.exit(1);
    }

}

From source file:emma.Emma.java

/**
 * @param args the command line arguments
 *///  w w  w .j  a v  a2 s  .  c  o  m
public static void main(String[] args) {
    try {
        Measure.start();

        // create dbs            
        // memory
        d_m = new BasicDataSource();
        d_m.setDriverClassName("org.hsqldb.jdbc.JDBCDriver");
        d_m.setUrl("jdbc:hsqldb:mem:emma");
        d_m.setUsername("sa");
        d_m.setPassword("");
        mem = d_m.getConnection();
        s_m = mem.createStatement();
        s_m.executeUpdate(
                "CREATE TABLE entries (entriesindex BIGINT, hash VARCHAR(42), filepath VARCHAR(255), name VARCHAR(255), alt VARCHAR(255), url VARCHAR(255), img VARCHAR(255), actors VARCHAR(2048), f_exists BOOLEAN, desc VARCHAR(2048));");
        // persistent
        d_p = new BasicDataSource();
        d_p.setDriverClassName("org.hsqldb.jdbc.JDBCDriver");
        d_p.setUrl("jdbc:hsqldb:file:settings");
        d_p.setUsername("sa");
        d_p.setPassword("");
        pers = d_p.getConnection();
        s_p = pers.createStatement();
        s_p.executeUpdate(
                "CREATE TABLE IF NOT EXISTS settings (settingsindex BIGINT, key VARCHAR(255), value VARCHAR(255));");

        // default settings
        Settings.setOnce("communicate", "false");

        try {
            String line;
            Process p = Runtime.getRuntime().exec("sleep 0");
            try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
                while ((line = input.readLine()) != null) {
                    System.out.println(line);
                }
            }
            int c = p.waitFor();
            int a = 0;
        } catch (IOException | InterruptedException err) {
            //err.printStackTrace();
        }

        /*
        try {
        Logger LOG = LoggerFactory.getLogger(Emma.class);
        org.apache.http.client.HttpClient httpClient = new SimpleHttpClientBuilder().build();
        HttpTools httpTools = new HttpTools(httpClient);
        TmdbFind find = new TmdbFind("ca7d0fb887a7be06bfee3a557f6e2238", httpTools);
        FindResults result = find.find("tt0468569", ExternalSource.IMDB_ID, "de");
        System.out.println(result.toString());
        } catch (Exception e) {
        System.err.println(e.toString());
        }     
        */

        // build image cache
        ImageCache.read();

        // create http server
        InetSocketAddress addr = new InetSocketAddress(9980);
        HttpServer server = HttpServer.create(addr, 0);
        server.createContext("/", new FileHandler());
        server.createContext("/select", new StorageHandler());
        server.createContext("/insert", new StorageHandler());
        server.createContext("/update", new StorageHandler());
        server.createContext("/delete", new StorageHandler());
        server.createContext("/config", new ConfigHandler());
        server.createContext("/chat", new ChatHandler());
        server.createContext("/misc", new MiscHandler());
        server.setExecutor(Executors.newFixedThreadPool(12));
        server.start();

        debug(">" + Measure.resultMs());
    } catch (SQLException | IOException e) {
        System.err.println(e.toString());
    } finally {

    }
}

From source file:com.pari.nm.utils.backup.BackupRestore.java

/**
 * @param args/*from   w  ww  . jav a 2 s  .  c  o m*/
 */
public static void main(String[] args) {
    com.maverick.ssh.LicenseManager.addLicense("----BEGIN 3SP LICENSE----\r\n" + "Product : J2SSH Maverick\r\n"
            + "Licensee: Pari Networks Inc.\r\n" + "Comments: Sreenivas Devalla\r\n"
            + "Type    : Foundation License\r\n" + "Created : 20-Jun-2007\r\n" + "\r\n"
            + "3787201A027FCA5BA600F3CF9CCEF4C85068187D70F94ABC\r\n"
            + "E7D7280AAFB06CE499DC968A4CB25795475D5B79FDDD6CB4\r\n"
            + "7971A60E947E84A4DADFAB2F89E2F52470182ED2EF429A2F\r\n"
            + "2EC6D8B49CAF167605A7F56C4EB736ECA7150819FCF04DC6\r\n"
            + "01B1404EA9BC83BEAA4AB2F4FC7AB344BEC08CF9DDDAAA34\r\n"
            + "EC80C1C14FA8BB1A8B47E86D393FAECD3C0E7C450E0D1FE3\r\n" + "----END 3SP LICENSE----\r\n");
    String mode = null;
    BufferedReader br = null;

    if (args.length < 9) {
        System.err.println("BackUpDatabase: Invalid Syntax.");
        System.err.println(
                "Usage - java BackUpDatabase <ftpserver> <ftpuser> <ftppassword> <ftpdir> <ftpfile> <localdir>  <backup | recovery> ");
        System.exit(-1);
    }

    try {

        mode = args[8];
        System.out.println("Request received with mode :" + mode + "\n");
        // BackupRestore tbk = BackupRestore.getInstance();
        BackupRestore tbk = new BackupRestore();
        if ((mode != null) && (mode.length() > 0) && mode.equalsIgnoreCase("recovery")) {
            File restoreDir = new File(args[7], args[6].substring(0, args[6].length() - 4));
            System.out.println("Restore Directory :" + restoreDir + "\n");
            if (!restoreDir.exists()) {
                try {
                    FTPServerType serverType = FTPServerType.valueOf(FTPServerType.class, args[0]);
                    System.out.println("Fetching the backup File :" + args[6] + "\n");
                    System.out.println("Please wait, it may take sometime....." + "\n");

                    if (tbk.fetchAndExtractBackupFile(serverType, args[1], Integer.parseInt(args[2]), args[3],
                            args[4], args[5], args[6], args[7]) == null) {
                        System.err.println("Error : Failed to fetch the backup File.\n");
                        System.exit(-1);
                    }
                    System.out.println("Successfully fetched the backup File :" + args[6] + "\n");
                } catch (Exception e) {
                    System.out.println(
                            "Error : Exception while fetching the backup file.Failed to restore the backup File.\n");
                    e.printStackTrace();
                    System.exit(-1);
                }
            }
            try {
                Thread.sleep(10000);
            } catch (Exception ee) {
                ee.printStackTrace();
            }

            System.out.println("Starting recovery ...\n");

            if (!File.separator.equals("\\")) {
                System.out.println("Stopping the Pari Server process.\n");
                Process p = Runtime.getRuntime().exec("killall -9 pari_server");
                MyReader min = new MyReader(p.getInputStream());
                MyReader merr = new MyReader(p.getErrorStream());

                try {
                    min.join(20000);
                } catch (Exception ee) {
                }

                try {
                    merr.join(20000);
                } catch (Exception ex) {
                }
            }

            if (!File.separator.equals("\\")) {
                System.out.println("Stopping the Pari Server process.\n");
                // Process p = Runtime.getRuntime().exec("killall -9 pari_server");
                Process p = Runtime.getRuntime().exec("/etc/init.d/dash stop");
                MyReader min = new MyReader(p.getInputStream());
                MyReader merr = new MyReader(p.getErrorStream());

                try {
                    min.join(20000);
                } catch (Exception ee) {
                }

                try {
                    merr.join(20000);
                } catch (Exception ex) {
                }
            }
            System.out.println("Start recovering the backup file.\n");
            if (tbk.doRecovery(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7])) {
                System.out.println("Done recovering...\n");
                validateCSPCInstanace();
            } else {
                System.out.println("Failed to recover the backup File...\n");
            }

            try {
                Process p = null;
                String cmd = "";

                if (File.separator == "\\") {
                    cmd = "cmd /k start_server.cmd > pari.out 2>&1";
                } else {
                    cmd = "/etc/init.d/dash start";
                }

                System.err.println(cmd);
                Runtime.getRuntime().exec(cmd);
                Boolean flag = false;
                int count = 0;
                String[] nccmStatusCheckCmd = { "/bin/sh", "-c",
                        "netstat -an  | grep 42605 | grep LISTEN | wc -l" };

                do {
                    count++;
                    Thread.sleep(60000);
                    // The command output will be 1 if NCCM server started and Listening on port 42605 otherwise it
                    // will return 0
                    p = Runtime.getRuntime().exec(nccmStatusCheckCmd);
                    int ex = -1;
                    try {
                        ex = p.waitFor();
                    } catch (InterruptedException e) {
                        System.out.println("Normal execution, exception: " + e);
                    }
                    System.out.println("Normal execution, exit value: " + ex);
                    br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                    String thisLine = null;
                    while ((thisLine = br.readLine()) != null) {
                        System.out.println("Command Execution Result:" + thisLine);
                        if (thisLine.equals("1")) {
                            flag = true;
                            break;
                        }
                    }
                    System.out.println("Count - " + count);
                    BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                    while ((thisLine = error.readLine()) != null) {
                        System.out.println(thisLine);
                    }

                } while ((!flag) && count < 30);

                if (flag) {
                    // System.out.println("NCCM Server came to listening state: after " + count + " mins");
                    // Runtime.getRuntime().exec("sh $DASH_HOME/webui/tomcat/bin/shutdown.sh");
                    Thread.sleep(60000);
                    System.out.println("NCCM Server came to listening state: after " + count + " mins");
                    // Runtime.getRuntime().exec("sh $DASH_HOME/webui/tomcat/bin/startup.sh");
                } else {
                    System.out.println("NCCM Server didn't come to listening state: last " + count + " mins");
                    System.out.println("Please verify NCCM Server and start tomcat server manually.");
                }
                System.exit(1);
            } catch (Exception ee) {
                ee.printStackTrace();
            }
        } else if ((mode != null) && (mode.length() > 0) && mode.equalsIgnoreCase("ftplist")) {
            PariFTP pftp = new PariFTP("10.100.1.20", "guest", "guest", "/");
            String[] list = pftp.getRemoteListing();

            System.out.println("List of Files\n");

            for (int i = 0; (list != null) && (i < list.length); i++) {
                System.out.println(list[i] + "\n");
            }
        } else {
            System.out.println("Mode \t" + mode + "\t not supported\n");
        }

        System.exit(-1);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null) {
                br.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}