Example usage for java.lang.management ManagementFactory getRuntimeMXBean

List of usage examples for java.lang.management ManagementFactory getRuntimeMXBean

Introduction

In this page you can find the example usage for java.lang.management ManagementFactory getRuntimeMXBean.

Prototype

public static RuntimeMXBean getRuntimeMXBean() 

Source Link

Document

Returns the managed bean for the runtime system of the Java virtual machine.

Usage

From source file:org.noroomattheinn.utils.Utils.java

public static List<String> getJVMArgs() {
    RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
    return runtimeMxBean.getInputArguments();
}

From source file:de.prozesskraft.pkraft.Manager.java

/**
 * ermittelt die pid dieses manager-laufs
 * @return/*from   w  ww  . j  a v a 2 s  . c om*/
 */
private static String getPid() {
    String fullPid = ManagementFactory.getRuntimeMXBean().getName();

    String[] splitPid = fullPid.split("@");

    return splitPid[0];
}

From source file:com.smartmarmot.dbforbix.DBforBix.java

public static void writePid(String _pidfile) throws Exception {
    RuntimeMXBean rmxb = ManagementFactory.getRuntimeMXBean();
    String pid = rmxb.getName();//from w  ww. ja  v  a  2 s .c  o  m
    try {

        File target = new File(_pidfile);

        File newTarget = new File(target.getAbsoluteFile().getCanonicalPath());
        target = null;

        if (newTarget.exists()) {
            boolean success = newTarget.delete();
            if (!success) {
                DBforBix.LOG.log(Level.ERROR, "Delete: deletion failed " + newTarget.getAbsolutePath());
            }
        }
        if (!newTarget.exists()) {
            FileOutputStream fout = new FileOutputStream(newTarget);
            new PrintStream(fout).print(pid);
            fout.close();
        }

    } catch (IOException e) {
        DBforBix.LOG.log(Level.ERROR, "Unable to write to file " + _pidfile + " error:" + e);
    }
}

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   ww w .  ja  va  2 s .  c  o  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.seleniumtests.browserfactory.BrowserInfo.java

/**
 * get /*from  w  ww  . j av  a 2 s . co  m*/
 * @return
 */
public List<Long> getProgramPid(String programName, List<Long> existingPids) {
    final String jvmName = ManagementFactory.getRuntimeMXBean().getName();
    final int index = jvmName.indexOf('@');

    OSUtility osUtility = OSUtilityFactory.getInstance();

    if (index == 0) {
        return new ArrayList<>();
    }
    try {
        String processId = Long.toString(Long.parseLong(jvmName.substring(0, index)));
        List<Long> driverProcesses = osUtility.getChildProcessPid(Long.parseLong(processId),
                programName + osUtility.getProgramExtension(), existingPids);
        return driverProcesses;
    } catch (Exception e) {
        logger.warn("could not get driver pid", e);
        return new ArrayList<>();
    }
}

From source file:org.tango.server.ServerManager.java

/**
 * WARNING: it is jvm dependent (works for sun')
 *
 * @throws DevFailed/*from   w ww. j ava  2 s .  com*/
 */
private void initPIDAndHostName() throws DevFailed {

    final RuntimeMXBean rmxb = ManagementFactory.getRuntimeMXBean();
    final String pidAndHost = rmxb.getName();
    final String[] splitted = pidAndHost.split("@");
    if (splitted.length > 1) {
        pid = splitted[0];
    }

    try {
        final InetAddress addr;
        if (ORBManager.OAI_ADDR != null && !ORBManager.OAI_ADDR.isEmpty()) {
            addr = InetAddress.getByName(ORBManager.OAI_ADDR);
        } else {
            addr = InetAddress.getLocalHost();
        }
        hostName = addr.getCanonicalHostName();
    } catch (final UnknownHostException e) {
        DevFailedUtils.throwDevFailed(e);
    }

    logger.debug("pid: " + pid);
    logger.debug("hostName: " + hostName);

}

From source file:org.archive.crawler.Heritrix.java

/**
 * Setup global system properties that may be of use elsewhere.
 * //from ww  w.  j  av a 2 s .  co  m
 * @param port
 */
protected void setupGlobalProperties(int port) {
    if (System.getProperty("heritrix.port") == null) {
        System.setProperty("heritrix.port", port + "");
    }

    String hostname = "localhost.localdomain";
    if (System.getProperty("heritrix.hostname") == null) {
        try {
            hostname = InetAddress.getLocalHost().getCanonicalHostName();
        } catch (UnknownHostException ue) {
            logger.warning("Failed getHostAddress for this host: " + ue);
        }
        System.setProperty("heritrix.hostname", hostname);
    }

    // while not guaranteed, on our platforms of interest this name
    // always seems to be PID@HOSTNAME
    String runtimeName = ManagementFactory.getRuntimeMXBean().getName();
    if (System.getProperty("heritrix.runtimeName") == null) {
        System.setProperty("heritrix.runtimeName", runtimeName);
    }
    if (System.getProperty("heritrix.pid") == null && runtimeName.matches("\\d+@\\S+")) {
        System.setProperty("heritrix.pid", runtimeName.substring(0, runtimeName.indexOf("@")));
    }
}

From source file:com.codesourcery.installer.Installer.java

/**
 * Initializes the install platform.//  www. ja v  a 2  s. com
 * 
 * @throws CoreException on failure
 */
private void initializeInstallPlatform() throws CoreException {
    try {
        Bundle bundle = Platform.getBundle(Installer.ID);
        String os = Platform.getOS();
        String arch = Platform.getOSArch();

        // Temporary directory
        String tempDirValue = System.getProperty("java.io.tmpdir");
        if (tempDirValue == null)
            fail("No temporary directory available, aborting.");
        IPath tempPath = new Path(tempDirValue);
        File tempDir = tempPath.toFile();
        if (!tempDir.exists())
            fail("Temporary directory does not exist, aborting.");

        // Install monitor prefix
        final String monPrefix = MessageFormat.format("{0}-{1}-{2}",
                new Object[] { IInstallConstants.INSTALL_MONITOR_NAME, os, arch });
        // Install monitor filename
        String monSrcName = monPrefix;
        if (isWindows()) {
            monSrcName += "." + IInstallConstants.EXTENSION_EXE;
        }

        // Install monitor included with installer
        URL url = FileLocator.find(bundle, new Path("/exe/" + monSrcName), null); //$NON-NLS-1$
        url = FileLocator.resolve(url);
        File monSrcFile = new File(url.getFile());
        // Install monitor temporary path
        IPath monTempPath = tempPath.append(monPrefix + "-" + UUID.randomUUID().toString()
                + (isWindows() ? "." + IInstallConstants.EXTENSION_EXE : ""));
        File monTempFile = monTempPath.toFile();

        // Copy install monitor
        FileUtils.copyFile(monSrcFile, monTempFile);
        // Set execute attribute
        monTempFile.setExecutable(true);

        // Get the installer PID (only works for a SUN JVM)
        String runtimeName = ManagementFactory.getRuntimeMXBean().getName();
        int seperator = runtimeName.indexOf('@');
        String pid = runtimeName.substring(0, seperator);

        // Redistributables directory (if available)
        String redistPath = null;
        File redistDir = getInstallFile(IInstallConstants.REDIST_DIRECTORY);
        if ((redistDir != null) && redistDir.exists())
            redistPath = redistDir.getAbsolutePath();

        IPath monitorLogPath = getLogPath().append(IInstallConstants.INSTALL_MONITOR_NAME + ".log");
        // Create the install monitor
        installPlatform = new InstallPlatform(monTempFile.getAbsolutePath(), redistPath, pid,
                monitorLogPath.toOSString());
    } catch (Exception e) {
        fail(InstallMessages.Error_FailedInstallMonitor, e);
    }
}

From source file:eg.nileu.cis.nilestore.main.CLI.java

private void writePidFile(String dir) {
    String name = ManagementFactory.getRuntimeMXBean().getName();
    String pid = name.split("@")[0];
    try {//from  w  w  w  . j a  va2  s  .c om
        FileUtils.writeLine(pid, FileUtils.JoinPath(dir, "nilestore.pid"));
    } catch (IOException e) {
        System.err.println("Error during writing nilestore.pid : " + e.getMessage());
        System.exit(-1);
    }
}

From source file:io.ecarf.core.utils.Utils.java

/**
 * Log the CPU stats/*from   w  ww.  j a v  a 2  s.c o m*/
 */
public static void logCpuStats() {
    OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory
            .getOperatingSystemMXBean();
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    int availableProcessors = operatingSystemMXBean.getAvailableProcessors();
    long upTime = runtimeMXBean.getUptime();
    double loadAverage = operatingSystemMXBean.getSystemLoadAverage();
    log.info("Available processors: " + availableProcessors);
    log.info("JVM upTime (ms): " + upTime);
    log.info("CPU load average: " + loadAverage);
}