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:com.github.neoio.nio.util.NIOUtils.java

public static FileLock tryLock(File file) {
    FileLock toReturn = null;/* w w  w .  j a  va2 s  .c  o m*/

    try {
        RandomAccessFile raf = new RandomAccessFile(file, "rw");

        try {
            FileChannel channel = raf.getChannel();
            toReturn = channel.tryLock();
            raf.writeBytes("lock file for: " + ManagementFactory.getRuntimeMXBean().getName());
        } finally {
            if (toReturn == null)
                raf.close();
        }
    } catch (OverlappingFileLockException e) {
        toReturn = null;
    } catch (FileNotFoundException e) {
        toReturn = null;
    } catch (IOException e) {
        toReturn = null;
    }

    return toReturn;
}

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

private static void checkOpenRunFileLeaks() throws IOException {
    if (SystemUtils.IS_OS_WINDOWS) {
        return;/*from   w w  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: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));//  w w w .ja v  a  2 s . c o m

    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:org.apache.cassandra.utils.HeapUtils.java

/**
 * Retrieves the process ID from the JVM name.
 * @return the process ID or <code>null</code> if the process ID cannot be retrieved.
 *///  w  w w .ja va 2 s  .c o m
private static Long getProcessIdFromJvmName() {
    // the JVM name in Oracle JVMs is: '<pid>@<hostname>' but this might not be the case on all JVMs
    String jvmName = ManagementFactory.getRuntimeMXBean().getName();
    try {
        return Long.parseLong(jvmName.split("@")[0]);
    } catch (NumberFormatException e) {
        // ignore
    }
    return null;
}

From source file:com.gemstone.gemfire.management.internal.cli.commands.ConfigCommandsDUnitTest.java

public void testDescribeConfig() throws ClassNotFoundException, IOException {
    createDefaultSetup(null);//from   ww w . ja  v a  2  s  .  co  m
    final String controllerName = "Member2";

    /***
     * Create properties for the controller VM
     */
    final Properties localProps = new Properties();
    localProps.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
    localProps.setProperty(DistributionConfig.LOG_LEVEL_NAME, "info");
    localProps.setProperty(DistributionConfig.STATISTIC_SAMPLING_ENABLED_NAME, "true");
    localProps.setProperty(DistributionConfig.ENABLE_TIME_STATISTICS_NAME, "true");
    localProps.setProperty(DistributionConfig.NAME_NAME, controllerName);
    localProps.setProperty(DistributionConfig.GROUPS_NAME, "G1");
    getSystem(localProps);
    Cache cache = getCache();
    int ports[] = AvailablePortHelper.getRandomAvailableTCPPorts(1);
    CacheServer cs = getCache().addCacheServer();
    cs.setPort(ports[0]);
    cs.setMaxThreads(10);
    cs.setMaxConnections(9);
    cs.start();

    RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
    List<String> jvmArgs = runtimeBean.getInputArguments();

    getLogWriter().info("#SB Actual JVM Args : ");

    for (String jvmArg : jvmArgs) {
        getLogWriter().info("#SB JVM " + jvmArg);
    }

    InternalDistributedSystem system = (InternalDistributedSystem) cache.getDistributedSystem();
    DistributionConfig config = system.getConfig();
    config.setArchiveFileSizeLimit(1000);

    String command = CliStrings.DESCRIBE_CONFIG + " --member=" + controllerName;
    CommandProcessor cmdProcessor = new CommandProcessor();
    cmdProcessor.createCommandStatement(command, Collections.EMPTY_MAP).process();

    CommandResult cmdResult = executeCommand(command);

    String resultStr = commandResultToString(cmdResult);
    getLogWriter().info("#SB Hiding the defaults\n" + resultStr);

    assertEquals(true, cmdResult.getStatus().equals(Status.OK));
    assertEquals(true, resultStr.contains("G1"));
    assertEquals(true, resultStr.contains(controllerName));
    assertEquals(true, resultStr.contains("archive-file-size-limit"));
    assertEquals(true, !resultStr.contains("copy-on-read"));

    cmdResult = executeCommand(command + " --" + CliStrings.DESCRIBE_CONFIG__HIDE__DEFAULTS + "=false");
    resultStr = commandResultToString(cmdResult);
    getLogWriter().info("#SB No hiding of defaults\n" + resultStr);

    assertEquals(true, cmdResult.getStatus().equals(Status.OK));
    assertEquals(true, resultStr.contains("is-server"));
    assertEquals(true, resultStr.contains(controllerName));
    assertEquals(true, resultStr.contains("copy-on-read"));

    cs.stop();
}

From source file:org.alfresco.reporting.cron.ReportExecutionJob.java

public void executeImpl(AtomicBoolean running, JobExecutionContext context) throws JobExecutionException {

    // actually do what needs to be done
    // a cron job can only trigger 
    //   -all- ReportingContainers with same frequency
    //   -all- ReprotingContainers no matter what frequency (all-all) 
    final JobDataMap jobData = context.getJobDetail().getJobDataMap();

    // can be null, then execute all frequencies
    final String frequency = jobData.getString("frequency");

    if (logger.isDebugEnabled())
        logger.debug("executeImpl starting with frequency " + frequency);

    int startupDelayMillis = 0;
    startupDelayMillis = Integer.parseInt(jobData.getString("startDelayMinutes")) * 60000;

    if (logger.isDebugEnabled())
        logger.debug("executeImpl starting with delay " + startupDelayMillis);

    // wait system i starting
    RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean();
    if (startupDelayMillis < rb.getUptime()) {
        // we are x minutes after startup of the repository, lets roll!
        AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Void>() {
            public Void doWork() {
                Action action = actionService.createAction(ReportRootExecuter.NAME);

                boolean canRun = false; // make true if run can be successful...
                if (frequency != null) {

                    if ("hourly".equals(frequency)) {
                        action.setParameterValue(ReportRootExecuter.PARAM_FREQUENCY, frequency);
                        canRun = true;/*from w  w w . j  a  v  a  2s  .  com*/
                    } // end hourly

                    if ("daily".equals(frequency)) {
                        action.setParameterValue(ReportRootExecuter.PARAM_FREQUENCY, frequency);
                        canRun = true;
                    } // end daily

                    if ("weekly".equals(frequency)) {
                        action.setParameterValue(ReportRootExecuter.PARAM_FREQUENCY, frequency);
                        canRun = true;
                    } // end weekly

                    if ("monthly".equals(frequency)) {
                        action.setParameterValue(ReportRootExecuter.PARAM_FREQUENCY, frequency);
                        canRun = true;
                    } // end monthly

                    if (canRun) {
                        if (logger.isDebugEnabled())
                            logger.debug("executeImpl: start running action " + frequency);
                        actionService.executeAction(action, null);
                    } else {
                        logger.error(
                                "executeImpl: Confguration mistake, cannot run. Frequency has no meaningful value: "
                                        + frequency);
                    }

                } // end if frequency!=null
                else {

                    action.setParameterValue(ReportRootExecuter.PARAM_FREQUENCY, "hourly");
                    actionService.executeAction(action, null);

                    action.setParameterValue(ReportRootExecuter.PARAM_FREQUENCY, "daily");
                    actionService.executeAction(action, null);

                    action.setParameterValue(ReportRootExecuter.PARAM_FREQUENCY, "weekly");
                    actionService.executeAction(action, null);

                    action.setParameterValue(ReportRootExecuter.PARAM_FREQUENCY, "monthly");
                    actionService.executeAction(action, null);

                }

                return null;
            } // end doWork
        }, AuthenticationUtil.getSystemUserName());
    } else {
        logger.info(
                "Hey relax! Its too early to work... Let the repository get up first... Aborting this run.");
    }
}

From source file:org.eclipse.mdht.dita.ui.util.DitaUtil.java

public static ILaunch publish(IFile ditaMapFile, String antTargets, String ditavalFileName)
        throws IOException, CoreException, URISyntaxException {

    IProject ditaProject = ditaMapFile.getProject();

    IFolder ditaFolder = ditaProject.getFolder(new Path("dita"));

    IFile ditaValFile = ditaFolder.getFile(ditavalFileName);

    StringBuffer jvmArguments = new StringBuffer();
    for (String arg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
        if (arg.startsWith("-X")) {
            jvmArguments.append(arg);/*from  ww w . j  a v  a2  s.c  o m*/
            jvmArguments.append(" ");
        }
    }

    jvmArguments.append("-Dfile.encoding=UTF-8 ");

    String[] segments = ditaMapFile.getName().split("\\.");

    String ditaMapFileRoot = segments[0];

    Bundle bundle = Platform.getBundle("org.eclipse.mdht.dita.ui");

    Path path = new Path("META-INF/MANIFEST.MF");

    URL fileURL = FileLocator.find(bundle, path, null);

    Path ditadirPath = new Path("DITA-OT");

    URL ditadirURL = FileLocator.find(bundle, ditadirPath, null);

    if (ditadirURL == null) {
        return null;
    }

    ditadirURL = FileLocator.toFileURL(ditadirURL);

    InputStream in = fileURL.openStream();

    Manifest ditaPluginManifest = new Manifest(in);

    Attributes attributes = ditaPluginManifest.getMainAttributes();

    String ditaClassPath = attributes.getValue("Bundle-ClassPath");

    List<String> classpath = new ArrayList<String>();

    String ditaRequiredBundles = attributes.getValue("Require-Bundle");

    for (String requiredBundleSymbolicName : ditaRequiredBundles.split(",")) {

        // get before ;
        Bundle requiredBundle = Platform.getBundle(requiredBundleSymbolicName.split(";")[0]);

        // Assume the bundle is optional if null
        if (requiredBundle != null) {
            File file = FileLocator.getBundleFile(requiredBundle);

            IRuntimeClasspathEntry requiredBundleEntry = JavaRuntime
                    .newArchiveRuntimeClasspathEntry(new Path(file.getPath()));
            requiredBundleEntry.setClasspathProperty(IRuntimeClasspathEntry.USER_CLASSES);
            classpath.add(requiredBundleEntry.getMemento());
        }
    }

    for (String classPath : ditaClassPath.split(",")) {
        if (".".equals(classPath)) {
            URL url = FileLocator.find(bundle, new Path(""), null);
            url = FileLocator.toFileURL(url);
            IRuntimeClasspathEntry pluginEntry = JavaRuntime.newRuntimeContainerClasspathEntry(
                    new Path(url.getPath()), IRuntimeClasspathEntry.USER_CLASSES);
            classpath.add(pluginEntry.getMemento());
        } else {
            URL url = FileLocator.find(bundle, new Path(classPath), null);
            url = FileLocator.toFileURL(url);
            IRuntimeClasspathEntry toolsEntry = JavaRuntime
                    .newArchiveRuntimeClasspathEntry(new Path(url.getPath()));
            toolsEntry.setClasspathProperty(IRuntimeClasspathEntry.USER_CLASSES);
            classpath.add(toolsEntry.getMemento());
        }
    }

    ContributedClasspathEntriesEntry ccee = new ContributedClasspathEntriesEntry();

    AntHomeClasspathEntry ace = new AntHomeClasspathEntry();

    classpath.add(ace.getMemento());

    classpath.add(ccee.getMemento());

    ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();

    ILaunchConfigurationType type = launchManager
            .getLaunchConfigurationType(IAntLaunchConstants.ID_ANT_LAUNCH_CONFIGURATION_TYPE);

    URL ditaPublishBuildFileURL = fileURL = FileLocator.find(bundle, new Path("dita-publish.xml"), null);

    ditaPublishBuildFileURL = FileLocator.toFileURL(ditaPublishBuildFileURL);

    String name = launchManager.generateLaunchConfigurationName("Publish DITA");

    ILaunchConfigurationWorkingCopy workingCopy = type.newInstance(null, name);

    workingCopy.setAttribute("org.eclipse.ui.externaltools.ATTR_LOCATION", ditaPublishBuildFileURL.getPath());

    IVMInstall jre = JavaRuntime.getDefaultVMInstall();

    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_JRE_CONTAINER_PATH, jre.getName());

    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS,
            "-Djavax.xml.transform.TransformerFactory=net.sf.saxon.TransformerFactoryImpl");

    Map<String, String> antProperties = new HashMap<String, String>();

    antProperties.put("dita.dir", ditadirURL.getPath());
    antProperties.put("ditaMapFile", ditaMapFile.getLocation().toOSString());

    if (ditaValFile != null) {
        antProperties.put("args.filter", ditaValFile.getLocation().toOSString());

    }

    antProperties.put("ditaMapFileName", ditaMapFile.getName().substring(0,
            ditaMapFile.getName().length() - ditaMapFile.getFileExtension().length()));

    // antProperties.put("outputLocation", ditaProject.getLocation().toOSString());
    antProperties.put("dita.output", ditaProject.getLocation().append(antTargets).toOSString());
    antProperties.put("ditaMapFileRoot", ditaMapFileRoot);

    String fileName = getFileNameFromMap(ditaMapFile.getLocation().toOSString());
    if (StringUtils.isEmpty(fileName)) {
        fileName = ditaMapFile.getName().replace("." + ditaMapFile.getFileExtension(), "");
    }

    antProperties.put("fileName", fileName);
    antProperties.put("args.debug", "no");
    antProperties.put("ditaFilePath", ditaFolder.getLocation().toOSString());
    antProperties.put("tempFilePath", org.eclipse.mdht.dita.ui.internal.Activator.getDefault()
            .getStateLocation().append("temp").toOSString());
    antProperties.put("docProject", ditaProject.getLocation().toOSString());

    String pdfFileLocation = ditaMapFile.getName();
    pdfFileLocation = pdfFileLocation.replaceFirst(".ditamap", ".pdf");
    antProperties.put("pdflocation", pdfFileLocation);

    workingCopy.setAttribute("process_factory_id", "org.eclipse.ant.ui.remoteAntProcessFactory");
    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME,
            "org.eclipse.ant.internal.ui.antsupport.InternalAntRunner");

    workingCopy.setAttribute(
            org.eclipse.core.externaltools.internal.IExternalToolConstants.ATTR_WORKING_DIRECTORY,
            ditaProject.getLocation().toOSString());
    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, jvmArguments.toString());
    workingCopy.setAttribute(org.eclipse.ant.launching.IAntLaunchConstants.ATTR_ANT_TARGETS, antTargets);
    workingCopy.setAttribute(IAntLaunchConstants.ATTR_ANT_PROPERTIES, antProperties);
    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH, classpath);
    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_DEFAULT_CLASSPATH, false);
    workingCopy.setAttribute(IDebugUIConstants.ATTR_CONSOLE_PROCESS, false);
    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH_PROVIDER,
            "org.eclipse.ant.ui.AntClasspathProvider");
    workingCopy.setAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND, true);

    workingCopy.setAttribute(DebugPlugin.ATTR_CONSOLE_ENCODING, "UTF-8");

    workingCopy.migrate();

    return workingCopy.launch(ILaunchManager.RUN_MODE, null, false, true);
}

From source file:org.opendaylight.latency.util.LatencyPacketParserUtil.java

/**
 * @param nodeConnectorId// w  ww . jav a  2  s  .com
 * @return extra authenticator for lldp security
 * @throws NoSuchAlgorithmException
 */
public static byte[] getValueForLLDPPacketIntegrityEnsuring(final NodeConnectorId nodeConnectorId)
        throws NoSuchAlgorithmException {
    String finalKey;
    if (LLDPActivator.getLldpSecureKey() != null && !LLDPActivator.getLldpSecureKey().isEmpty()) {
        finalKey = LLDPActivator.getLldpSecureKey();
    } else {
        finalKey = ManagementFactory.getRuntimeMXBean().getName();
    }
    final String pureValue = nodeConnectorId + finalKey;

    final byte[] pureBytes = pureValue.getBytes();
    HashFunction hashFunction = Hashing.md5();
    Hasher hasher = hashFunction.newHasher();
    HashCode hashedValue = hasher.putBytes(pureBytes).hash();
    return hashedValue.asBytes();
}

From source file:org.craftercms.commons.monitoring.VersionMonitor.java

@SuppressWarnings("unchecked")
private void initRuntime() {
    RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
    java_version = runtime.getSpecVersion();
    java_vendor = runtime.getSpecVendor();
    java_runtime = runtime.getSpecName();
    java_vm = runtime.getVmName();/*from w  ww  .  j  a v  a  2  s . co  m*/
    jvm_input_arguments = StringUtils.join(runtime.getInputArguments());
    jvm_implementation_version = runtime.getVmVersion();
    jvm_vendor = runtime.getVmVendor();
    jvm_version = runtime.getSpecVersion();
}

From source file:com.janrain.backplane.server.metrics.MetricsAccumulator.java

private Map<String, Object> outputJVMUsage() {

    long mb = 1048576;

    Map<String, Object> out = new LinkedHashMap<String, Object>();

    long startTime = ManagementFactory.getRuntimeMXBean().getStartTime();
    int totalLiveThreads = ManagementFactory.getThreadMXBean().getThreadCount();
    double loadAverage = ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage();
    MemoryUsage mu = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();

    String startTimeString = BackplaneConfig.ISO8601.format(new Date(startTime));

    out.put("type", "jvm");
    out.put("unit", "mb");
    out.put("heap_used", mu.getUsed() / mb);
    out.put("heap_free", (mu.getMax() - mu.getUsed()) / mb);
    out.put("heap_max", mu.getMax() / mb);
    out.put("jvm_start_time", startTimeString);
    out.put("total_live_threads", totalLiveThreads);
    out.put("load_average_minute", String.format("%2.2f", loadAverage));

    return out;/*from  w ww  . j  a v a  2 s  . c o  m*/

}