Example usage for java.lang Process getInputStream

List of usage examples for java.lang Process getInputStream

Introduction

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

Prototype

public abstract InputStream getInputStream();

Source Link

Document

Returns the input stream connected to the normal output of the process.

Usage

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

/**
 * @param args/*from   w w  w .j  a v  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();
        }
    }
}

From source file:azkaban.webapp.AzkabanWebServer.java

/**
 * Azkaban using Jetty/*from w ww.jav  a2  s.c o  m*/
 *
 * @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:emma.Emma.java

/**
 * @param args the command line arguments
 *///from w  w w  .java2 s  . c om
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:Main.java

public static String runCommand(String[] command, String workdirectory) {
    String result = "";
    Log.d("AppUtil.class", "#" + command);
    try {//from w w w.j  av a 2 s . c  om
        ProcessBuilder builder = new ProcessBuilder(command);
        // set working directory
        if (workdirectory != null) {
            builder.directory(new File(workdirectory));
        }
        builder.redirectErrorStream(true);
        Process process = builder.start();
        InputStream in = process.getInputStream();
        byte[] buffer = new byte[1024];
        while (in.read(buffer) != -1) {
            String str = new String(buffer);
            result = result + str;
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

From source file:Main.java

public static long getMaxCpuFreq() {
    long longRet = 0;
    String result = "0";
    ProcessBuilder cmd;//from   w  w w.  j av a2s . com
    try {
        String[] args = { "/system/bin/cat", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" };
        cmd = new ProcessBuilder(args);
        Process process = cmd.start();
        InputStream in = process.getInputStream();
        byte[] re = new byte[24];
        result = "";
        while (in.read(re) != -1) {
            result = result + new String(re);
        }
        in.close();
    } catch (IOException ex) {
        ex.printStackTrace();
        result = "0";
    }

    if (result.length() != 0) {
        try {
            longRet = Long.valueOf(result.trim());
        } catch (Exception e) {
            android.util.Log.e(TAG, "");
        }
    }
    return longRet;
}

From source file:Main.java

public static String execCmd(String cmd) {

    String result = "";
    DataInputStream dis = null;/*from   w w w  .ja v a2s .  c  om*/

    try {
        Process p = Runtime.getRuntime().exec(cmd);
        dis = new DataInputStream(p.getInputStream());
        String line = null;
        while ((line = dis.readLine()) != null) {
            line += "\n";
            result += line;
        }
        p.waitFor();
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
    return result;
}

From source file:Main.java

public static void exec(String cmd) {
    Process exec;
    try {/* w ww .jav  a2s . c  o m*/
        exec = Runtime.getRuntime().exec(cmd);
        InputStream in = exec.getInputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static String system(String evaluatedContents, String failedString) {
    Runtime rt = Runtime.getRuntime();
    //System.out.println("System "+evaluatedContents);
    try {//  w w w  . ja  v  a  2s . c om
        Process p = rt.exec(evaluatedContents);
        InputStream istrm = p.getInputStream();
        InputStreamReader istrmrdr = new InputStreamReader(istrm);
        BufferedReader buffrdr = new BufferedReader(istrmrdr);
        String result = "";
        String data = "";
        while ((data = buffrdr.readLine()) != null) {
            result += data + "\n";
        }
        //System.out.println("Result = "+result);
        return result;
    } catch (Exception ex) {
        ex.printStackTrace();
        return failedString;

    }
}

From source file:com.spotify.scio.extra.transforms.ProcessUtil.java

static String getStdOut(Process p) throws IOException {
    return getStream(p.getInputStream());
}

From source file:Main.java

public static String getLocalMacAddress(Context mc) {
    String defmac = "00:00:00:00:00:00";
    InputStream input = null;//from w  w w.  j  av  a  2s  . com
    String wifimac = getWifiMacAddress(mc);
    if (null != wifimac) {
        if (!wifimac.equals(defmac))
            return wifimac;
    }
    try {

        ProcessBuilder builder = new ProcessBuilder("busybox", "ifconfig");
        Process process = builder.start();
        input = process.getInputStream();

        byte[] b = new byte[1024];
        StringBuffer buffer = new StringBuffer();
        while (input.read(b) > 0) {
            buffer.append(new String(b));
        }
        String value = buffer.substring(0);
        String systemFlag = "HWaddr ";
        int index = value.indexOf(systemFlag);
        // List <String> address = new ArrayList <String> ();
        if (0 < index) {
            value = buffer.substring(index + systemFlag.length());
            // address.add(value.substring(0,18));
            defmac = value.substring(0, 17);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return defmac;
}