Example usage for java.lang.management RuntimeMXBean getName

List of usage examples for java.lang.management RuntimeMXBean getName

Introduction

In this page you can find the example usage for java.lang.management RuntimeMXBean getName.

Prototype

public String getName();

Source Link

Document

Returns the name representing the running Java virtual machine.

Usage

From source file:it.isislab.dmason.util.SystemManagement.Worker.thrower.DMasonWorkerWithGui.java

public static DMasonWorkerWithGui newInstance(String args[]) {
    RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();

    ///*from  w  w w. j  a  va  2 s  .  c o m*/
    // Get name representing the running Java virtual machine.
    // It returns something like 6460@AURORA. Where the value
    // before the @ symbol is the PID.
    //
    String jvmName = bean.getName();

    //Used for log4j properties
    System.setProperty("logfile.name", "worker" + jvmName);

    //Used for log4j properties
    System.setProperty("steplog.name", "workerStep" + jvmName);

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss_SS");
    Date date = new Date();
    dateFormat.format(date);

    System.setProperty("timestamp", date.toLocaleString());

    System.setProperty("paramsfile.name", "params");
    try {
        File logPath = new File("Logs/workers");
        if (logPath.exists())
            FileUtils.cleanDirectory(logPath);
    } catch (IOException e) {
        //not a problem
    }

    logger = Logger.getLogger(DMasonWorker.class.getCanonicalName());
    logger.debug("StartWorker " + VERSION);

    autoStart = false;

    String ip = null;
    String port = null;
    String topic = "";
    updated = false;
    isBatch = false;
    topicPrefix = "";

    // ip, post, autoconnect
    if (args.length == 3) {
        ip = args[0];
        port = args[1];
        if (args[2].equals("autoconnect")) {
            autoStart = true;
        }
    }
    // ip, post, topic, event 
    if (args.length == 4) {
        autoStart = true;
        if (args[3].equals("update")) {
            updated = true;
        }
        if (args[3].equals("reset")) {
            updated = false;
            isBatch = false;
        }
        if (args[3].contains("Batch")) {
            updated = false;
            isBatch = true;
            topicPrefix = args[3];
        }
        ip = args[0];
        port = args[1];
        topic = args[2];
    }

    /*if(args.length == 2 && args[0].equals("auto"))
    {   autoStart = true;
       updated = true;
       topic = args[1];
    }
    if(args.length == 1 && args[0].equals("auto"))
    {   autoStart = true;
    }*/
    return new DMasonWorkerWithGui(autoStart, updated, isBatch, topic, ip, port);
}

From source file:it.isislab.dmason.util.SystemManagement.Worker.Updater.java

public static void uploadLog(UpdateData up, String updateDir, boolean isBatch) {
    String hostname = "";
    String jvmName = "";
    String balanceLog = "Balance";
    String workerLog = "workerStep";
    String paramsFile = "params.conf";
    logPath = "Logs/workers/";

    if (up.getFTPAddress() == null)
        return;/*from  w ww . j av  a2  s.co m*/

    FTPIP = up.getFTPAddress().getIPaddress();
    FTPPORT = up.getFTPAddress().getPort();

    System.out.println("FPT: " + FTPIP + "PORT: " + FTPPORT);
    FTPClient client = connect(FTPIP, Integer.parseInt(FTPPORT));

    login(client);

    try {
        InetAddress addr = InetAddress.getLocalHost();

        // Get IP Address
        //byte[] ipAddr = addr.getAddress();

        // Get hostname
        hostname = addr.getHostName();
    } catch (UnknownHostException e) {
    }

    RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();

    //
    // Get name representing the running Java virtual machine.
    // It returns something like 6460@AURORA. Where the value
    // before the @ symbol is the PID.
    //
    jvmName = bean.getName();

    /*try {
       client.createDirectory(dateFormat.format(date)+"@"+hostname);
    } catch (IllegalStateException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } catch (IOException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } catch (FTPIllegalReplyException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    } catch (FTPException e1) {
       isDirExists = true;
    }*/

    try {

        if (client == null)
            return;

        client.changeDirectory(updateDir);

        File blog = new File(logPath + balanceLog + jvmName + ".log");
        if (blog.exists())
            client.upload(blog);
        else
            System.out.println("File not found");

        File wlog = new File(logPath + workerLog + jvmName + ".log");
        if (wlog.exists())
            client.upload(wlog);
        else
            System.out.println("File not found");

        File params = new File(logPath + paramsFile);
        if (params.exists())
            client.upload(params);
        else
            System.out.println("File not found");

        ArrayList<File> fileToBackup = new ArrayList<File>();
        fileToBackup.add(params);
        fileToBackup.add(blog);
        fileToBackup.add(wlog);

        backupLog(updateDir, fileToBackup);
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FTPIllegalReplyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FTPException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FTPDataTransferException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FTPAbortedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.ery.ertc.estorm.util.JVM.java

/**
 * Get the number of opened filed descriptor for the runtime jvm. If Oracle java, it will use the com.sun.management interfaces.
 * Otherwise, this methods implements it (linux only).
 * //www.  j a v  a 2 s. c o m
 * @return number of open file descriptors for the jvm
 */
public long getOpenFileDescriptorCount() {

    Long ofdc;

    if (!ibmvendor) {
        ofdc = runUnixMXBeanMethod("getOpenFileDescriptorCount");
        return (ofdc != null ? ofdc.longValue() : -1);
    }
    InputStream in = null;
    BufferedReader output = null;
    try {
        // need to get the PID number of the process first
        RuntimeMXBean rtmbean = ManagementFactory.getRuntimeMXBean();
        String rtname = rtmbean.getName();
        String[] pidhost = rtname.split("@");

        // using linux bash commands to retrieve info
        Process p = Runtime.getRuntime()
                .exec(new String[] { "bash", "-c", "ls /proc/" + pidhost[0] + "/fdinfo | wc -l" });
        in = p.getInputStream();
        output = new BufferedReader(new InputStreamReader(in));
        String openFileDesCount;
        if ((openFileDesCount = output.readLine()) != null)
            return Long.parseLong(openFileDesCount);
    } catch (IOException ie) {
        LOG.warn("Not able to get the number of open file descriptors", ie);
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                LOG.warn("Not able to close the InputStream", e);
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                LOG.warn("Not able to close the InputStream", e);
            }
        }
    }
    return -1;
}

From source file:com.smartmarmot.orabbix.Orabbixmon.java

@Override
public void run() {
    try {/*w w w  . ja v a 2s  .  c om*/
        Configurator cfg = null;
        try {
            cfg = new Configurator(configFile);
        } catch (Exception e) {
            SmartLogger.logThis(Level.ERROR, "Error while creating configurator with " + configFile + " " + e);
        }
        RuntimeMXBean rmxb = ManagementFactory.getRuntimeMXBean();
        String pid = rmxb.getName();
        SmartLogger.logThis(Level.INFO,
                Constants.PROJECT_NAME + " started with pid:" + pid.split("@")[0].toString());
        // System.out.print("pid: "+pid.split("@")[0].toString());
        String pidfile = cfg.getPidFile();
        try {
            Utility.writePid(pid.split("@")[0].toString(), pidfile);
        } catch (Exception e) {
            SmartLogger.logThis(Level.ERROR, "Error while trying to write pidfile " + e);
        }

        Locale.setDefault(Locale.US);

        DBConn[] myDBConn = cfg.getConnections();

        if (myDBConn == null) {
            SmartLogger.logThis(Level.ERROR, "ERROR on main - Connections is null");
            throw new Exception("ERROR on main - Connections is null");

        } else if (myDBConn.length == 0) {
            SmartLogger.logThis(Level.ERROR, "ERROR on main - Connections is empty");
            throw new Exception("ERROR on main - Connections is empty");
        }

        /**
         * retrieve maxThread
         */
        Integer maxThread = 0;
        try {
            maxThread = cfg.getMaxThread();
        } catch (Exception e) {
            SmartLogger.logThis(Level.WARN,
                    "MaxThread not defined calculated maxThread = " + myDBConn.length * 3);
        }
        if (maxThread == null)
            maxThread = 0;
        if (maxThread == 0) {
            maxThread = myDBConn.length * 3;
        }

        ExecutorService executor = Executors.newFixedThreadPool(maxThread.intValue());
        /**
         * populate qbox
         */
        Hashtable<String, Querybox> qbox = new Hashtable<String, Querybox>();
        for (int i = 0; i < myDBConn.length; i++) {
            Querybox qboxtmp = Configurator.buildQueryBoxbyDBName(myDBConn[i].getName());
            qbox.put(myDBConn[i].getName(), qboxtmp);
        } // for (int i = 0; i < myDBConn.length; i++) {

        cfg = null;
        /**
         * daemon begin here
         */
        while (running) {
            /**
             * istantiate a new configurator
             */
            Configurator c = new Configurator(configFile);

            /*
             * here i rebuild DB's List
             */
            if (!c.isEqualsDBList(myDBConn)) {

                // rebuild connections DBConn[]

                myDBConn = c.rebuildDBList(myDBConn);
                for (int i = 1; i < myDBConn.length; i++) {
                    if (!qbox.containsKey(myDBConn[i].getName())) {
                        Querybox qboxtmp = Configurator.buildQueryBoxbyDBName(myDBConn[i].getName());
                        qbox.put(myDBConn[i].getName(), qboxtmp);
                    }
                }
            } // if (!c.isEqualsDBList(myDBConn)) {

            /*
             * ready to run query
             */

            for (int i = 0; i < myDBConn.length; i++) {
                Querybox actqb = qbox.get(myDBConn[i].getName());
                actqb.refresh();
                Query[] q = actqb.getQueries();

                SharedPoolDataSource spds = myDBConn[i].getSPDS();

                Hashtable<String, Integer> zabbixServers = c.getZabbixServers();
                SmartLogger.logThis(Level.DEBUG, "Ready to run DBJob for dbname ->" + myDBConn[i].getName());
                Runnable runner = new DBJob(spds, q, Constants.QUERY_LIST, zabbixServers,
                        myDBConn[i].getName());
                executor.execute(runner);

            } // for (int i = 0; i < myDBConn.length; i++) {
            Thread.sleep(60 * 1000);
            SmartLogger.logThis(Level.DEBUG, "Waking up Goood Morning");
        }
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        System.out.println("Stopping");
        e1.printStackTrace();
        stopped = true;
    }

}

From source file:com.thoughtworks.go.server.service.support.ServerRuntimeInformationProvider.java

private void runtimeInfo(RuntimeMXBean runtimeMXBean, InformationStringBuilder builder) {
    builder.addSection("Runtime information");
    builder.append(String.format("Name - %s\n", runtimeMXBean.getName()));

    long uptime = runtimeMXBean.getUptime();
    long uptimeInSeconds = uptime / 1000;
    long numberOfHours = uptimeInSeconds / (60 * 60);
    long numberOfMinutes = (uptimeInSeconds / 60) - (numberOfHours * 60);
    long numberOfSeconds = uptimeInSeconds % 60;

    builder.append(String.format("Uptime - %s [About %s hours, %s minutes, %s seconds]\n", uptime,
            numberOfHours, numberOfMinutes, numberOfSeconds));
    builder.append(String.format("Spec Name - %s\n", runtimeMXBean.getSpecName()));
    builder.append(String.format("Spec Vendor - %s\n", runtimeMXBean.getSpecVendor()));
    builder.append(String.format("Spec Version - %s\n", runtimeMXBean.getSpecVersion()));
    builder.addSubSection("Input Arguments")
            .append(asIndentedMultilineValues(runtimeMXBean.getInputArguments()));
    builder.addSubSection("System Properties")
            .append(asIndentedMultilineValues(runtimeMXBean.getSystemProperties()));
    builder.addSubSection("Classpath").append(prettyClassPath(runtimeMXBean.getClassPath()));
    builder.addSubSection("Boot Classpath").append(prettyClassPath(runtimeMXBean.getBootClassPath()));
}

From source file:net.risesoft.soa.asf.web.controller.SystemController.java

private List<SysInfo> getVMInfo() {
    List list = new ArrayList();
    String group = "3. VM ?";
    RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
    list.add(new SysInfo("BootClassPath", rt.getBootClassPath(), group));
    list.add(new SysInfo("ClassPath", rt.getClassPath(), group));
    list.add(new SysInfo("LibraryPath", rt.getLibraryPath(), group));
    list.add(new SysInfo("ManagementSpecVersion", rt.getManagementSpecVersion(), group));
    list.add(new SysInfo("Name", rt.getName(), group));
    list.add(new SysInfo("SpecName", rt.getSpecName(), group));
    list.add(new SysInfo("SpecVendor", rt.getSpecVendor(), group));
    list.add(new SysInfo("SpecVersion", rt.getSpecVersion(), group));
    list.add(new SysInfo("VmName", rt.getVmName(), group));
    list.add(new SysInfo("VmVendor", rt.getVmVendor(), group));
    list.add(new SysInfo("VmVersion", rt.getVmVersion(), group));
    list.add(new SysInfo("StartTime", DateFormat.getDateTimeInstance().format(new Date(rt.getStartTime())),
            group));//from   www.java  2 s.c om

    list.add(new SysInfo("UpTime", this.helper.getUpTimeStr(rt.getUptime()), group));
    list.add(new SysInfo("InputArguments", rt.getInputArguments(), group));

    group = "6. ?";
    Map<String, String> sysProps = rt.getSystemProperties();
    for (Map.Entry entry : sysProps.entrySet()) {
        list.add(new SysInfo((String) entry.getKey(), entry.getValue(), group));
    }
    Collections.sort(list, new Comparator() {
        public int compare(SystemController.SysInfo o1, SystemController.SysInfo o2) {
            String key1 = o1.getKey();
            String key2 = o2.getKey();
            return key1.compareToIgnoreCase(key2);
        }
    });
    return list;
}

From source file:me.gloriouseggroll.quorrabot.Quorrabot.java

public Quorrabot(String username, String oauth, String apioauth, String clientid, String channelName,
        String owner, int baseport, InetAddress ip, String hostname, int port, double msglimit30,
        String datastore, String datastoreconfig, String youtubekey, String gamewispauth,
        String gamewisprefresh, String twitchalertstoken, String lastfmuser, String tpetoken,
        String twittertoken, String twittertokensecret, String streamtiptoken, String streamtipid,
        boolean webenable, String webauth, String webauthro, boolean musicenable, boolean usehttps,
        String timeZone, String mySqlHost, String mySqlPort, String mySqlConn, String mySqlPass,
        String mySqlUser, String mySqlName, String keystorepath, FollowersCache followersCache,
        ChannelHostCache hostCache, ChannelUsersCache channelUsersCache, SubscribersCache subscribersCache,
        String discordToken, String discordMainChannel) {
    Thread.setDefaultUncaughtExceptionHandler(com.gmt2001.UncaughtExceptionHandler.instance());

    com.gmt2001.Console.out.println();
    com.gmt2001.Console.out.println(botVersion());
    com.gmt2001.Console.out.println(botRevision());
    com.gmt2001.Console.out.println("www.quorrabot.com");
    com.gmt2001.Console.out.println();
    com.gmt2001.Console.out.println("The working directory is: " + System.getProperty("user.dir"));

    interactive = System.getProperty("interactive") != null;

    this.username = username;
    this.oauth = oauth;
    this.apioauth = apioauth;
    this.ownerName = owner;
    this.channelName = channelName.toLowerCase();
    this.baseport = baseport;
    this.ip = ip;
    this.datastore = datastore;
    this.datastoreconfig = datastoreconfig;
    this.hostCache = ChannelHostCache.instance(this.ownerName);
    this.subscribersCache = SubscribersCache.instance(this.ownerName);
    this.channelUsersCache = ChannelUsersCache.instance(this.ownerName);
    this.followersCache = FollowersCache.instance(this.ownerName);

    this.youtubekey = youtubekey;
    if (!timeZone.isEmpty()) {
        this.timeZone = timeZone;
    } else {/*from www .ja  v  a  2  s  .c  om*/
        this.timeZone = "EDT";
    }

    if (!youtubekey.isEmpty()) {
        YouTubeAPIv3.instance().SetAPIKey(youtubekey);
    }

    this.discordToken = discordToken;
    this.discordMainChannel = discordMainChannel;

    this.gamewispauth = gamewispauth;
    this.gamewisprefresh = gamewisprefresh;
    this.twitchalertstoken = twitchalertstoken;
    if (!twitchalertstoken.isEmpty()) {
        DonationHandlerAPI.instance().SetAccessToken(twitchalertstoken, "twitchalerts");
    }
    this.lastfmuser = lastfmuser;
    if (!lastfmuser.isEmpty()) {
        LastFMAPI.instance().SetUsername(lastfmuser);
    }
    this.tpetoken = tpetoken;
    if (!tpetoken.isEmpty()) {
        DonationHandlerAPI.instance().SetAccessToken(tpetoken, "tpestream");
    }
    this.streamtiptoken = streamtiptoken;
    if (!streamtiptoken.isEmpty()) {
        DonationHandlerAPI.instance().SetAccessToken(streamtiptoken, "streamtip");
    }
    this.streamtipid = streamtipid;
    if (!streamtipid.isEmpty()) {
        DonationHandlerAPI.instance().SetClientID(streamtipid, "streamtip");
    }
    this.twittertoken = twittertoken;
    this.twittertokensecret = twittertokensecret;
    if (!twittertoken.isEmpty() || !twittertokensecret.isEmpty()) {
        TwitterAPI.instance().loadAccessToken(twittertoken, twittertokensecret);
    }

    if (msglimit30 != 0) {
        Quorrabot.msglimit30 = msglimit30;
    } else {
        Quorrabot.msglimit30 = 18.75;
    }

    this.mySqlName = mySqlName;
    this.mySqlUser = mySqlUser;
    this.mySqlPass = mySqlPass;
    this.mySqlConn = mySqlConn;
    this.mySqlHost = mySqlHost;
    this.mySqlPort = mySqlPort;

    this.webenable = webenable;
    this.musicenable = musicenable;
    this.usehttps = usehttps;
    this.keystorepath = keystorepath;
    this.webauth = webauth;
    this.webauthro = webauthro;

    if (clientid.length() == 0) {
        this.clientid = "pcaalhorck7ryamyg6ijd5rtnls5pjl";
    } else {
        this.clientid = clientid;
    }

    /**
     * Create a map for multiple channels.
     */
    channels = new HashMap<>();

    /**
     * Create a map for multiple sessions.
     */
    sessions = new HashMap<>();

    /**
     * Create a map for multiple oauth tokens.
     */
    apiOAuths = new HashMap<>();

    rng = new SecureRandom();
    pollResults = new TreeMap<>();
    voters = new TreeSet<>();

    if (hostname.isEmpty()) {
        this.hostname = "irc.chat.twitch.tv";
        this.port = 6667;
    } else {
        this.hostname = hostname;
        this.port = port;
    }

    if (msglimit30 > 0) {
        this.msglimit30 = msglimit30;
    } else {
        this.msglimit30 = 18.75;
    }

    if (datastore.equalsIgnoreCase("IniStore")) {
        dataStoreObj = IniStore.instance();
    } else if (datastore.equalsIgnoreCase("mysqlstore")) {
        dataStoreObj = MySQLStore.instance();
        if (this.mySqlPort.isEmpty()) {
            this.mySqlConn = "jdbc:mariadb://" + this.mySqlHost + "/" + this.mySqlName;
        } else {
            this.mySqlConn = "jdbc:mariadb://" + this.mySqlHost + ":" + this.mySqlPort + "/" + this.mySqlName;
        }

        /**
         * Check to see if we can create a connection
         */
        if (dataStoreObj.CreateConnection(this.mySqlConn, this.mySqlUser, this.mySqlPass) == null) {
            com.gmt2001.Console.out
                    .println("Could not create a connection with MySql. QuorraBot now shutting down...");
            System.exit(0);
        }

        if (IniStore.instance().GetFileList().length > 0) {
            ini2MySql(true);
        } else if (SqliteStore.instance().GetFileList().length > 0) {
            sqlite2MySql();
        }
    } else {
        dataStoreObj = SqliteStore.instance();
        if (datastore.isEmpty() && IniStore.instance().GetFileList().length > 0
                && SqliteStore.instance().GetFileList().length == 0) {
            ini2sqlite(true);
        }
    }
    TwitchAPIv3.instance().SetClientID(this.clientid);
    TwitchAPIv3.instance().SetOAuth(apioauth);

    this.init();

    this.tcechannel = Channel.instance("tcechannel", this.ownerName, this.apioauth, EventBus.instance(),
            this.ownerName);
    //Give the bot some time in between sessions so to be sure the stream channel connects last
    //This needs to be done in order for the parser to detect which chat channel to use
    try {
        Thread.sleep(2000);
    } catch (Exception e) {
        //
    }
    this.channel = Channel.instance(this.channelName, this.username, this.oauth, EventBus.instance(),
            this.ownerName);

    if (SystemUtils.IS_OS_LINUX && !interactive) {
        try {
            java.lang.management.RuntimeMXBean runtime = java.lang.management.ManagementFactory
                    .getRuntimeMXBean();
            int pid = Integer.parseInt(runtime.getName().split("@")[0]);

            File f = new File("/var/run/QuorraBot." + this.username.toLowerCase() + ".pid");

            try (FileOutputStream fs = new FileOutputStream(f, false)) {
                PrintStream ps = new PrintStream(fs);
                ps.print(pid);
            }
            f.deleteOnExit();
        } catch (SecurityException | IllegalArgumentException | IOException ex) {
            com.gmt2001.Console.err.printStackTrace(ex);
        }
    }

}

From source file:me.mast3rplan.phantombot.PhantomBot.java

public PhantomBot(Properties pbProperties) {

    /* Set the exeption handler */
    Thread.setDefaultUncaughtExceptionHandler(com.gmt2001.UncaughtExceptionHandler.instance());

    /* Start loading the bot information */
    print("");/*ww w .  ja v  a 2  s .  co  m*/
    print(botVersion());
    print(botRevision());
    print(getBotCreator());
    print(botDevelopers());
    print(getWebSite());
    print("");

    /* System interactive */
    interactive = (System.getProperty("interactive") != null);

    /* Assign properties passed in to local instance. */
    this.pbProperties = pbProperties;

    /* Set the default bot variables */
    this.botName = this.pbProperties.getProperty("user").toLowerCase();
    this.channelName = this.pbProperties.getProperty("channel").toLowerCase();
    this.ownerName = this.pbProperties.getProperty("owner").toLowerCase();
    this.apiOAuth = this.pbProperties.getProperty("apioauth", "");
    this.oauth = this.pbProperties.getProperty("oauth");

    /* Set the web variables */
    this.youtubeOAuth = this.pbProperties.getProperty("ytauth");
    this.youtubeOAuthThro = this.pbProperties.getProperty("ytauthro");
    this.youtubeKey = this.pbProperties.getProperty("youtubekey", "");
    this.basePort = Integer.parseInt(this.pbProperties.getProperty("baseport", "25000"));
    this.webOAuth = this.pbProperties.getProperty("webauth");
    this.webOAuthThro = this.pbProperties.getProperty("webauthro");
    this.webEnabled = this.pbProperties.getProperty("webenable", "true").equalsIgnoreCase("true");
    this.musicEnabled = this.pbProperties.getProperty("musicenable", "true").equalsIgnoreCase("true");
    this.useHttps = this.pbProperties.getProperty("usehttps", "false").equalsIgnoreCase("true");

    /* Set the datastore variables */
    this.dataStoreType = this.pbProperties.getProperty("datastore", "");
    this.dataStoreConfig = this.pbProperties.getProperty("datastoreconfig", "");

    /* Set the Twitter variables */
    this.twitterUsername = this.pbProperties.getProperty("twitterUser", "");
    this.twitterConsumerToken = this.pbProperties.getProperty("twitter_consumer_key", "");
    this.twitterConsumerSecret = this.pbProperties.getProperty("twitter_consumer_secret", "");
    this.twitterAccessToken = this.pbProperties.getProperty("twitter_access_token", "");
    this.twitterSecretToken = this.pbProperties.getProperty("twitter_secret_token", "");
    this.twitterAuthenticated = false;

    /* Set the Discord variables */
    this.discordToken = this.pbProperties.getProperty("discord_token", "");

    /* Set the GameWisp variables */
    this.gameWispOAuth = this.pbProperties.getProperty("gamewispauth", "");
    this.gameWispRefresh = this.pbProperties.getProperty("gamewisprefresh", "");

    /* Set the TwitchAlerts variables */
    this.twitchAlertsKey = this.pbProperties.getProperty("twitchalertskey", "");
    this.twitchAlertsLimit = Integer.parseInt(this.pbProperties.getProperty("twitchalertslimit", "5"));

    /* Set the StreamTip variables */
    this.streamTipOAuth = this.pbProperties.getProperty("streamtipkey", "");
    this.streamTipClientId = this.pbProperties.getProperty("streamtipid", "");
    this.streamTipLimit = Integer.parseInt(this.pbProperties.getProperty("streamtiplimit", "5"));

    /* Set the TipeeeStream variables */
    this.tipeeeStreamOAuth = this.pbProperties.getProperty("tipeeestreamkey", "");
    this.tipeeeStreamLimit = Integer.parseInt(this.pbProperties.getProperty("tipeeestreamlimit", "5"));

    /* Set the MySql variables */
    this.mySqlName = this.pbProperties.getProperty("mysqlname", "");
    this.mySqlUser = this.pbProperties.getProperty("mysqluser", "");
    this.mySqlPass = this.pbProperties.getProperty("mysqlpass", "");
    this.mySqlHost = this.pbProperties.getProperty("mysqlhost", "");
    this.mySqlPort = this.pbProperties.getProperty("mysqlport", "");

    /* twitch cache */
    PhantomBot.twitchCacheReady = "false";

    /* Set the SSL info */
    this.httpsFileName = this.pbProperties.getProperty("httpsFileName", "");
    this.httpsPassword = this.pbProperties.getProperty("httpsPassword", "");

    /* Set the timeZone */
    PhantomBot.timeZone = this.pbProperties.getProperty("logtimezone", "GMT");

    /* Set the panel username login for the panel to use */
    this.panelUsername = this.pbProperties.getProperty("paneluser", "panel");

    /* Set the panel password login for the panel to use */
    this.panelPassword = this.pbProperties.getProperty("panelpassword", "panel");

    /* Enable/disable devCommands */
    this.devCommands = this.pbProperties.getProperty("devcommands", "false").equalsIgnoreCase("true");

    /* Toggle for the old servers. */
    this.legacyServers = this.pbProperties.getProperty("legacyservers", "false").equalsIgnoreCase("true");

    /*
     * Set the message limit for session.java to use, note that Twitch rate limits at 100 messages in 30 seconds
     * for moderators.  For non-moderators, the maximum is 20 messages in 30 seconds. While it is not recommended
     * to go above anything higher than 18.75 in case the bot is ever de-modded, the option is available but is
     * capped at 80.0. 
     */
    PhantomBot.messageLimit = Double.parseDouble(this.pbProperties.getProperty("msglimit30", "18.75"));
    if (PhantomBot.messageLimit > 80.0) {
        PhantomBot.messageLimit = 80.0;
    } else if (PhantomBot.messageLimit < 18.75) {
        PhantomBot.messageLimit = 18.75;
    }

    /* Set the whisper limit for session.java to use. -- Currently Not Used -- */
    PhantomBot.whisperLimit = Double.parseDouble(this.pbProperties.getProperty("whisperlimit60", "60.0"));

    /* Set the client id for the twitch api to use */
    this.clientId = this.pbProperties.getProperty("clientid", "7wpchwtqz7pvivc3qbdn1kajz42tdmb");

    /* Set any SQLite backup options. */
    this.backupSQLiteAuto = this.pbProperties.getProperty("backupsqliteauto", "false").equalsIgnoreCase("true");
    this.backupSQLiteHourFrequency = Integer
            .parseInt(this.pbProperties.getProperty("backupsqlitehourfreqency", "24"));
    this.backupSQLiteKeepDays = Integer.parseInt(this.pbProperties.getProperty("backupsqlitekeepdays", "5"));

    /* Load up a new SecureRandom for the scripts to use */
    random = new SecureRandom();

    /* Create a map for multiple channels. */
    channels = new HashMap<>();

    /* Create a map for multiple sessions. */
    sessions = new HashMap<>();

    /* Create a map for multiple oauth tokens. */
    apiOAuths = new HashMap<>();

    /* Load the datastore */
    if (dataStoreType.equalsIgnoreCase("inistore")) {
        dataStore = IniStore.instance();
    } else if (dataStoreType.equalsIgnoreCase("mysqlstore")) {
        dataStore = MySQLStore.instance();
        if (this.mySqlPort.isEmpty()) {
            this.mySqlConn = "jdbc:mysql://" + this.mySqlHost + "/" + this.mySqlName + "?useSSL=false";
        } else {
            this.mySqlConn = "jdbc:mysql://" + this.mySqlHost + ":" + this.mySqlPort + "/" + this.mySqlName
                    + "?useSSL=false";
        }
        /* Check to see if we can create a connection */
        if (dataStore.CreateConnection(this.mySqlConn, this.mySqlUser, this.mySqlPass) == null) {
            print("Could not create a connection with MySql. PhantomBot now shutting down...");
            System.exit(0);
        }
        /* Convert to MySql */
        if (IniStore.instance().GetFileList().length > 0) {
            ini2MySql(true);
        } else if (SqliteStore.instance().GetFileList().length > 0) {
            sqlite2MySql();
        }
    } else {
        dataStoreType = "sqlite3store";
        dataStore = SqliteStore.instance();
        /* Create indexes. */
        if (!dataStore.exists("settings", "tables_indexed")) {
            print("Creating SQLite3 Indexes. This might take time...");
            dataStore.CreateIndexes();
            dataStore.set("settings", "tables_indexed", "true");
            print("Completed Creating SQLite3 Indexes!");
        }
        /* Convert the initstore to sqlite if the inistore exists and the db is empty */
        if (IniStore.instance().GetFileList().length > 0 && SqliteStore.instance().GetFileList().length == 0) {
            ini2Sqlite(true);
        }
    }

    /* Set the client Id in the Twitch api. */
    TwitchAPIv3.instance().SetClientID(this.clientId);

    /* Set the oauth key in the Twitch api. */
    if (!this.apiOAuth.isEmpty()) {
        TwitchAPIv3.instance().SetOAuth(this.apiOAuth);
    }

    /* Set the TwitchAlerts OAuth key and limiter. */
    if (!twitchAlertsKey.isEmpty()) {
        TwitchAlertsAPIv1.instance().SetAccessToken(twitchAlertsKey);
        TwitchAlertsAPIv1.instance().SetDonationPullLimit(twitchAlertsLimit);
    }

    /* Set the YouTube API Key if provided. */
    if (!this.youtubeKey.isEmpty()) {
        YouTubeAPIv3.instance().SetAPIKey(this.youtubeKey);
    }

    /* Set the StreamTip OAuth key, Client ID and limiter. */
    if (!streamTipOAuth.isEmpty() && !streamTipClientId.isEmpty()) {
        StreamTipAPI.instance().SetAccessToken(streamTipOAuth);
        StreamTipAPI.instance().SetDonationPullLimit(streamTipLimit);
        StreamTipAPI.instance().SetClientId(streamTipClientId);
    }

    /* Set the TipeeeStream oauth key. */
    if (!tipeeeStreamOAuth.isEmpty()) {
        TipeeeStreamAPIv1.instance().SetOauth(tipeeeStreamOAuth);
        TipeeeStreamAPIv1.instance().SetLimit(tipeeeStreamLimit);
    }

    /* Start things and start loading the scripts. */
    this.init();

    /* Start a channel instance to create a session, and then connect to WS-IRC @ Twitch. */
    this.channel = Channel.instance(this.channelName, this.botName, this.oauth, EventBus.instance());

    /* Start a host checking instance. */
    if (apiOAuth.length() > 0 && checkModuleEnabled("./handlers/hostHandler.js")) {
        this.wsHostIRC = TwitchWSHostIRC.instance(this.channelName, this.apiOAuth, EventBus.instance());
    }

    /* Start a pubsub instance here. */
    if (this.oauth.length() > 0 && checkDataStore("chatModerator", "moderationLogs")) {
        this.pubSubEdge = TwitchPubSub.instance(this.channelName,
                TwitchAPIv3.instance().getChannelId(this.channelName),
                TwitchAPIv3.instance().getChannelId(this.botName), this.oauth);
    }

    /* Check if the OS is Linux. */
    if (SystemUtils.IS_OS_LINUX && !interactive) {
        try {
            java.lang.management.RuntimeMXBean runtime = java.lang.management.ManagementFactory
                    .getRuntimeMXBean();
            int pid = Integer.parseInt(runtime.getName().split("@")[0]);

            File file = new File("PhantomBot." + this.botName.toLowerCase() + ".pid");

            try (FileOutputStream fs = new FileOutputStream(file, false)) {
                PrintStream ps = new PrintStream(fs);
                ps.print(pid);
            }
            file.deleteOnExit();
        } catch (SecurityException | IllegalArgumentException | IOException ex) {
            com.gmt2001.Console.err.printStackTrace(ex);
        }
    }
}

From source file:org.apache.asterix.test.runtime.LangExecutionUtil.java

private static void checkOpenRunFileLeaks() throws IOException {
    if (SystemUtils.IS_OS_WINDOWS) {
        return;//ww  w.j  a v a 2  s . co m
    }
    // Only run the check on Linux and MacOS.
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    String processName = runtimeMXBean.getName();
    String processId = processName.split("@")[0];

    // Checks whether there are leaked run files from operators.
    Process process = Runtime.getRuntime()
            .exec(new String[] { "bash", "-c", "lsof -p " + processId + "|grep waf|wc -l" });
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
        int runFileCount = Integer.parseInt(reader.readLine().trim());
        if (runFileCount != 0) {
            System.out.print(takeDumpJSON(ManagementFactory.getThreadMXBean()));
            outputLeakedOpenFiles(processId);
            throw new AssertionError("There are " + runFileCount + " leaked run files.");
        }
    }
}

From source file:org.apache.hadoop.hbase.io.TestHeapSize.java

@BeforeClass
public static void beforeClass() throws Exception {
    // Print detail on jvm so we know what is different should below test fail.
    RuntimeMXBean b = ManagementFactory.getRuntimeMXBean();
    LOG.info("name=" + b.getName());
    LOG.info("specname=" + b.getSpecName());
    LOG.info("specvendor=" + b.getSpecVendor());
    LOG.info("vmname=" + b.getVmName());
    LOG.info("vmversion=" + b.getVmVersion());
    LOG.info("vmvendor=" + b.getVmVendor());
    Map<String, String> p = b.getSystemProperties();
    LOG.info("properties=" + p);
}