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.artifactory.webapp.wicket.page.config.advanced.SystemInfoPage.java

/**
 * Return a formatted string of the system info to display
 *
 * @return//  w w  w .  j av a 2s .  c  om
 */
private String collectSystemInfo() {
    StringBuilder infoBuilder = new StringBuilder();

    StorageProperties storageProperties = ContextHelper.get().beanForType(StorageProperties.class);
    infoBuilder.append("Storage Info:").append("\n");
    addInfo(infoBuilder, "Database Type", storageProperties.getDbType().toString());
    BinaryProviderType binariesStorageType = storageProperties.getBinariesStorageType();
    addInfo(infoBuilder, "Storage Type", binariesStorageType.toString());
    if (BinaryProviderType.S3 == binariesStorageType) {
        // S3 properties
        addInfo(infoBuilder, "s3.bucket.name", storageProperties.getS3BucketName());
        addInfo(infoBuilder, "s3.bucket.path", storageProperties.getS3BucketPath());
        addInfo(infoBuilder, "s3.endpoint", storageProperties.getS3Entpoint());
        // Retry properties
        addInfo(infoBuilder, "retry.max.retries.number",
                Integer.toString(storageProperties.getMaxRetriesNumber()));
        addInfo(infoBuilder, "retry.delay.between.retries",
                Integer.toString(storageProperties.getDelayBetweenRetries()));
        // Eventually persisted properties
        addInfo(infoBuilder, "eventually.persisted.max.number.of.threads",
                Integer.toString(storageProperties.getEventuallyPersistedMaxNumberOfThread()));
        addInfo(infoBuilder, "eventually.persisted.timeout",
                Integer.toString(storageProperties.getEventuallyPersistedTimeOut()));
        addInfo(infoBuilder, "eventually.dispatcher.sleep.time",
                Long.toString(storageProperties.getEventuallyPersistedDispatcherSleepTime()));
    }

    infoBuilder.append("\n").append("System Properties:").append("\n");
    Properties properties = System.getProperties();
    //// add Artifactory version to the properties, will be alphabetically sorted later.
    properties.setProperty(ConstantValues.artifactoryVersion.getPropertyName(),
            ConstantValues.artifactoryVersion.getString());
    AddonsManager addonsManager = ContextHelper.get().beanForType(AddonsManager.class);
    addInfo(infoBuilder, "artifactory.running.mode", addonsManager.getArtifactoryRunningMode().name());
    addInfo(infoBuilder, "artifactory.running.state", ContextHelper.get().isOffline() ? "Offline" : "Online");
    addFromProperties(infoBuilder, properties);
    addHaProperties(infoBuilder);
    infoBuilder.append("\n").append("General JVM Info:").append("\n");
    OperatingSystemMXBean systemBean = ManagementFactory.getOperatingSystemMXBean();
    addInfo(infoBuilder, "Available Processors", Integer.toString(systemBean.getAvailableProcessors()));

    MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage heapMemoryUsage = memoryBean.getHeapMemoryUsage();

    addInfo(infoBuilder, "Heap Memory Usage-Committed", Long.toString(heapMemoryUsage.getCommitted()));
    addInfo(infoBuilder, "Heap Memory Usage-Init", Long.toString(heapMemoryUsage.getInit()));
    addInfo(infoBuilder, "Heap Memory Usage-Max", Long.toString(heapMemoryUsage.getMax()));
    addInfo(infoBuilder, "Heap Memory Usage-Used", Long.toString(heapMemoryUsage.getUsed()));

    MemoryUsage nonHeapMemoryUsage = memoryBean.getNonHeapMemoryUsage();
    addInfo(infoBuilder, "Non-Heap Memory Usage-Committed", Long.toString(nonHeapMemoryUsage.getCommitted()));
    addInfo(infoBuilder, "Non-Heap Memory Usage-Init", Long.toString(nonHeapMemoryUsage.getInit()));
    addInfo(infoBuilder, "Non-Heap Memory Usage-Max", Long.toString(nonHeapMemoryUsage.getMax()));
    addInfo(infoBuilder, "Non-Heap Memory Usage-Used", Long.toString(nonHeapMemoryUsage.getUsed()));

    RuntimeMXBean RuntimemxBean = ManagementFactory.getRuntimeMXBean();
    StringBuilder vmArgumentBuilder = new StringBuilder();
    List<String> vmArguments = RuntimemxBean.getInputArguments();
    if (vmArguments != null) {
        for (String vmArgument : vmArguments) {
            if (InfoWriter.shouldMaskValue(vmArgument)) {
                vmArgument = Strings.maskKeyValue(vmArgument);
            }
            vmArgumentBuilder.append(vmArgument);
            if (vmArguments.indexOf(vmArgument) != (vmArguments.size() - 1)) {
                vmArgumentBuilder.append("\n");
            }
        }
    }

    infoBuilder.append("\nJVM Arguments:\n").append(vmArgumentBuilder.toString());

    return StringUtils.removeEnd(infoBuilder.toString(), "\n");
}

From source file:org.icgc.dcc.generator.Main.java

private String formatArguments(String[] args) {
    RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
    List<String> inputArguments = runtime.getInputArguments();

    return "java " + join(inputArguments, ' ') + " -jar " + getJarName() + " " + join(args, ' ');
}

From source file:com.alibaba.jstorm.utils.JStormUtils.java

/**
 * Gets the pid of this JVM, because Java doesn't provide a real way to do this.
 * /*from   w  w w  .j a va  2 s  .c  o  m*/
 * @return
 */
public static String process_pid() {
    String name = ManagementFactory.getRuntimeMXBean().getName();
    String[] split = name.split("@");
    if (split.length != 2) {
        throw new RuntimeException("Got unexpected process name: " + name);
    }

    return split[0];
}

From source file:org.kiji.bento.box.tools.UpgradeDaemonTool.java

/**
 * Gets the pid for this process. This won't be portable on non-UNIX systems.
 *
 * @return the pid of this JVM.// www  .j  av  a  2s. co m
 */
private Integer getPid() {
    String processString = ManagementFactory.getRuntimeMXBean().getName();
    return Integer.valueOf(processString.split("@")[0]);
}

From source file:org.liferayhub.pc.service.impl.PowerConsoleServiceImpl.java

public String runCommand(long userId, long companyId, String mode, String command) {
    String response = "";
    Date startDate = new Date();
    if ("server".equalsIgnoreCase(mode)) {
        if ("help".equalsIgnoreCase(command)) {
            response = "Commands:\n" + "help\t\t\tShow this help message\n"
                    + "version\t\t Display the version of the Liferay Portal\n"
                    + "date\t\t\tDisplay the date and time of the database server\n"
                    + "uptime\t\t  Display the uptime of the portal\n" + "adduser\t\t Add a new user";
        } else if ("version".equalsIgnoreCase(command)) {
            response = ReleaseInfo.getReleaseInfo() + " running on "
                    + StringUtil.upperCaseFirstLetter(ServerDetector.getServerId());
        } else if ("date".equalsIgnoreCase(command)) {
            response = new Date().toString();
        } else if ("uptime".equalsIgnoreCase(command)) {
            response = getUptime(PortalUtil.getUptime().getTime());
        } else if (command.toLowerCase().startsWith("adduser")) {
            response = handleAddUser(userId, companyId, command);
        }//from www.j  a va 2 s .c  o m
    } else if ("db".equalsIgnoreCase(mode)) {
        if ("help".equalsIgnoreCase(command)) {
            response = "Commands:\n" + "help\t\t\tShow this help message\n"
                    + "version\t\t Display the version of the database\n"
                    + "date\t\t\tDisplay the date and time of the database server\n"
                    + "<sql query>\t Display result of any SQL query";
        } else if ("date".equalsIgnoreCase(command)) {
            response = runSQLQuery("select now() \"\"");
        } else if ("version".equalsIgnoreCase(command)) {
            response = runSQLQuery(
                    "select '" + DBFactoryUtil.getDBFactory().getDB().getType() + "' as '', version() ''");
        } else
            response = runSQLQuery(command);
    } else if ("jvm".equalsIgnoreCase(mode)) {
        if ("help".equalsIgnoreCase(command)) {
            response = "Commands:\n" + "help\t\tShow this help message\n"
                    + "mem\t\t Display memory usage of the JVM\n"
                    + "osinfo\t  Display operating system info of the running JVM\n"
                    + "vminfo\t  Display VM info";
        } else if ("mem".equalsIgnoreCase(command)) {
            MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
            response = "Heap        : " + mem.getHeapMemoryUsage().toString();
            response += "\nNon Heap    : " + mem.getNonHeapMemoryUsage().toString();
            response += "\nFinalization: " + mem.getObjectPendingFinalizationCount() + " objects pending";
        } else if ("osinfo".equalsIgnoreCase(command)) {
            OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
            response = os.getName() + "[" + os.getArch() + "] " + os.getVersion() + " ("
                    + os.getAvailableProcessors() + " processors)";
            response += "\nLoad Average: " + os.getSystemLoadAverage();
        } else if ("vminfo".equalsIgnoreCase(command)) {
            RuntimeMXBean vm = ManagementFactory.getRuntimeMXBean();
            response = vm.getVmName() + " " + vm.getVmVersion() + " by " + vm.getVmVendor();
            response += "\n" + vm.getSpecName() + " " + vm.getSpecVersion() + " by " + vm.getSpecVendor();
            response += "\nStarted at: " + DateFormat.getInstance().format(new Date(vm.getStartTime()));
            response += "\nUptime    : " + getUptime(vm.getStartTime());
        } else {
            response = UNRECOGNIZED_COMMAND;
        }
    }
    // save command to database if it is not 'help'
    if (!command.startsWith("help")) {
        try {
            // add to history
            Date endDate = new Date();
            long id = CounterLocalServiceUtil.increment(CommandHistory.class.getName());
            CommandHistory history = CommandHistoryLocalServiceUtil.createCommandHistory(id);
            history.setCommand(command);
            history.setExecutionDate(startDate);
            history.setExecutionTime(endDate.getTime() - startDate.getTime());
            history.setMode(mode);
            history.setUserId(userId);
            CommandHistoryLocalServiceUtil.updateCommandHistory(history);
            // TODO: delete the oldest entry > MAX_HISTORY_SIZE
            // get the history size
            long historySize = 100;
            List<CommandHistory> historyList = CommandHistoryLocalServiceUtil
                    .findCommandHistoryByUserId(userId);
            if (historyList.size() >= historySize) {
                CommandHistoryLocalServiceUtil.deleteCommandHistory(historyList.get(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
    return response;
}

From source file:de.xirp.plugin.PluginLoader.java

/**
 * Checks the needs of all plugins.// w  ww  .j  a  v  a 2 s  . c o m
 * 
 * @see IPlugable#requiredLibs()
 */
@SuppressWarnings("unchecked")
private static void checkAllNeeds() {
    HashMap<String, IPlugable> plugables = new HashMap<String, IPlugable>();
    MultiValueHashMap<String, String> refs = new MultiValueHashMap<String, String>();

    // list of all plugins
    List<String> fullPluginList = new ArrayList<String>(plugins.size());
    for (PluginInfo info : plugins.values()) {
        fullPluginList.add(info.getMainClass());
    }

    ClassLoader loader = logClass.getClass().getClassLoader();

    // Read the list of available jars from the class path
    String cp = ManagementFactory.getRuntimeMXBean().getClassPath();
    // String cp = System.getProperty("java.class.path");
    // //$NON-NLS-1$
    String[] jars = cp.split(File.pathSeparator);
    List<String> jarList = new ArrayList<String>(jars.length);
    for (String jar : jars) {
        jarList.add(FilenameUtils.getName(jar));
    }
    // The initial list of current plugins equals the full list
    // every plugin which does not full fill the needs
    // it removed from this list
    currentPluginList = new ArrayList<String>(fullPluginList);
    for (PluginInfo info : plugins.values()) {
        try {
            SecurePluginView view = PluginManager.getInstance(info, Robot.NAME_NONE);
            plugables.put(info.getMainClass(), view);
            boolean check = checkNeeds(view, loader, jarList);
            if (!check) {
                // remove plugins which reference this plugin
                removeRefs(info.getMainClass());
            }
        } catch (Exception e) {
            logClass.trace(e, e);
        }
    }
    // Remove all plugins of the full list
    // which are no more contained in the current list
    for (String clazz : fullPluginList) {
        if (!currentPluginList.contains(clazz)) {
            plugins.remove(clazz);
            plugables.remove(clazz);
        }
    }
    instances = new ArrayList<IPlugable>(plugables.values());
    refs.clear();
    refs = null;
    currentPluginList.clear();
    currentPluginList = null;
    fullPluginList.clear();
    fullPluginList = null;
}

From source file:org.eclipse.gyrex.cloud.internal.NodeMetricsReporter.java

@Override
protected IStatus run(final IProgressMonitor monitor) {
    if (monitor.isCanceled()) {
        return Status.CANCEL_STATUS;
    }/*from  w w  w .  j  a va2s .c o m*/

    try {
        final Properties metrics = new Properties() {
            private static final long serialVersionUID = 1L;

            @Override
            public synchronized Enumeration<Object> keys() {
                return Collections.enumeration(keySet());
            }

            @Override
            public Set<Object> keySet() {
                return new TreeSet<Object>(super.keySet());
            }
        };
        final OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
        metrics.setProperty("os.availableProcessors",
                String.valueOf(operatingSystemMXBean.getAvailableProcessors()));
        metrics.setProperty("os.systemLoadAverage",
                String.valueOf(operatingSystemMXBean.getSystemLoadAverage()));
        metrics.setProperty("os.committedVirtualMemorySize",
                getUsingReflection(operatingSystemMXBean, "getCommittedVirtualMemorySize"));
        metrics.setProperty("os.totalSwapSpaceSize",
                getUsingReflection(operatingSystemMXBean, "getTotalSwapSpaceSize"));
        metrics.setProperty("os.freeSwapSpaceSize",
                getUsingReflection(operatingSystemMXBean, "getFreeSwapSpaceSize"));
        metrics.setProperty("os.processCpuTime",
                getUsingReflection(operatingSystemMXBean, "getProcessCpuTime"));
        metrics.setProperty("os.freePhysicalMemorySize",
                getUsingReflection(operatingSystemMXBean, "getFreePhysicalMemorySize"));
        metrics.setProperty("os.totalPhysicalMemorySize",
                getUsingReflection(operatingSystemMXBean, "getTotalPhysicalMemorySize"));
        metrics.setProperty("os.openFileDescriptorCount",
                getUsingReflection(operatingSystemMXBean, "getOpenFileDescriptorCount"));
        metrics.setProperty("os.maxFileDescriptorCount",
                getUsingReflection(operatingSystemMXBean, "getMaxFileDescriptorCount"));

        final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
        final MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
        metrics.setProperty("heap.used", String.valueOf(heapMemoryUsage.getUsed()));
        metrics.setProperty("heap.committed", String.valueOf(heapMemoryUsage.getCommitted()));
        metrics.setProperty("heap.max", String.valueOf(heapMemoryUsage.getMax()));
        metrics.setProperty("heap.init", String.valueOf(heapMemoryUsage.getInit()));
        final MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();
        metrics.setProperty("nonHeap.used", String.valueOf(nonHeapMemoryUsage.getUsed()));
        metrics.setProperty("nonHeap.committed", String.valueOf(nonHeapMemoryUsage.getCommitted()));
        metrics.setProperty("nonHeap.max", String.valueOf(nonHeapMemoryUsage.getMax()));
        metrics.setProperty("nonHeap.init", String.valueOf(nonHeapMemoryUsage.getInit()));

        final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        metrics.setProperty("thread.count", String.valueOf(threadMXBean.getThreadCount()));
        metrics.setProperty("thread.peak", String.valueOf(threadMXBean.getPeakThreadCount()));
        metrics.setProperty("thread.totalStarted", String.valueOf(threadMXBean.getTotalStartedThreadCount()));

        final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        metrics.setProperty("uptime", String.valueOf(runtimeMXBean.getUptime()));

        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final NodeInfo nodeInfo = CloudState.getNodeInfo();
        metrics.store(out, String.valueOf(nodeInfo));
        ZooKeeperGate.get().writeRecord(IZooKeeperLayout.PATH_NODES_METRICS.append(nodeInfo.getNodeId()),
                CreateMode.PERSISTENT, out.toByteArray());
        if (CloudDebug.nodeMetrics) {
            LOG.debug("Node metrics reported successfully.{}{}", SystemUtils.LINE_SEPARATOR,
                    new String(out.toByteArray(), CharEncoding.ISO_8859_1));
        }
    } catch (final Exception e) {
        LOG.warn("Failed to update node metrics. {}", e.getMessage());
    } finally {
        // reschedule
        schedule(DELAY);
    }

    return Status.OK_STATUS;
}

From source file:com.arpnetworking.test.junitbenchmarks.JsonBenchmarkConsumer.java

/**
 * Retrieve the argument list used to launch this JVM.
 *
 * @return The argument list used to launch this JVM.
 *//* ww  w . j av  a 2 s.c om*/
protected List<String> getJvmArguments() {
    return ManagementFactory.getRuntimeMXBean().getInputArguments();
}

From source file:org.apache.solr.handler.admin.SystemInfoHandler.java

/**
 * Get JVM Info - including memory info//ww  w  . j a  v a 2  s  .c  o m
 */
public static SimpleOrderedMap<Object> getJvmInfo() {
    SimpleOrderedMap<Object> jvm = new SimpleOrderedMap<Object>();
    jvm.add("version", System.getProperty("java.vm.version"));
    jvm.add("name", System.getProperty("java.vm.name"));

    Runtime runtime = Runtime.getRuntime();
    jvm.add("processors", runtime.availableProcessors());

    long used = runtime.totalMemory() - runtime.freeMemory();
    // not thread safe, but could be thread local
    DecimalFormat df = new DecimalFormat("#.#");
    double percentUsed = ((double) (used) / (double) runtime.maxMemory()) * 100;

    SimpleOrderedMap<Object> mem = new SimpleOrderedMap<Object>();
    mem.add("free", humanReadableUnits(runtime.freeMemory(), df));
    mem.add("total", humanReadableUnits(runtime.totalMemory(), df));
    mem.add("max", humanReadableUnits(runtime.maxMemory(), df));
    mem.add("used", humanReadableUnits(used, df) + " (%" + df.format(percentUsed) + ")");
    jvm.add("memory", mem);

    // JMX properties -- probably should be moved to a different handler
    SimpleOrderedMap<Object> jmx = new SimpleOrderedMap<Object>();
    try {
        RuntimeMXBean mx = ManagementFactory.getRuntimeMXBean();
        jmx.add("bootclasspath", mx.getBootClassPath());
        jmx.add("classpath", mx.getClassPath());

        // the input arguments passed to the Java virtual machine
        // which does not include the arguments to the main method.
        jmx.add("commandLineArgs", mx.getInputArguments());
        // a map of names and values of all system properties.
        //jmx.add( "SYSTEM PROPERTIES", mx.getSystemProperties());

        jmx.add("startTime", new Date(mx.getStartTime()));
        jmx.add("upTimeMS", mx.getUptime());
    } catch (Exception e) {
        log.warn("Error getting JMX properties", e);
    }
    jvm.add("jmx", jmx);
    return jvm;
}

From source file:org.apache.eagle.policy.executor.PolicyProcessExecutor.java

private void initMetricReportor() {
    String host = config.getString(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE
            + "." + EagleConfigConstants.HOST);
    int port = config.getInt(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE + "."
            + EagleConfigConstants.PORT);

    String username = config.hasPath(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE
            + "." + EagleConfigConstants.USERNAME)
                    ? config.getString(EagleConfigConstants.EAGLE_PROPS + "."
                            + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.USERNAME)
                    : null;/*  www  . ja va 2 s  . c  o m*/
    String password = config.hasPath(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE
            + "." + EagleConfigConstants.PASSWORD)
                    ? config.getString(EagleConfigConstants.EAGLE_PROPS + "."
                            + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.PASSWORD)
                    : null;

    registry = new MetricRegistry();
    listener = new EagleServiceReporterMetricListener(host, port, username, password);

    baseDimensions = new HashMap<>();
    baseDimensions = new HashMap<String, String>();
    baseDimensions.put(Constants.ALERT_EXECUTOR_ID, executorId);
    baseDimensions.put(Constants.PARTITIONSEQ, String.valueOf(partitionSeq));
    baseDimensions.put(Constants.SOURCE, ManagementFactory.getRuntimeMXBean().getName());
    baseDimensions.put(EagleConfigConstants.APPLICATION,
            config.getString(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.APPLICATION));
    baseDimensions.put(EagleConfigConstants.SITE,
            config.getString(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.SITE));

    dimensionsMap = new HashMap<String, Map<String, String>>();
}