Example usage for java.lang.management ManagementFactory getOperatingSystemMXBean

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

Introduction

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

Prototype

public static OperatingSystemMXBean getOperatingSystemMXBean() 

Source Link

Document

Returns the managed bean for the operating system on which the Java virtual machine is running.

Usage

From source file:com.aol.advertising.qiao.management.metrics.StatsCalculator.java

@SuppressWarnings("restriction")
public void init() {
    OperatingSystemMXBean bean = ManagementFactory.getOperatingSystemMXBean();
    if (bean instanceof com.sun.management.OperatingSystemMXBean) {
        availProcessors = bean.getAvailableProcessors();
        osMxBean = (com.sun.management.OperatingSystemMXBean) bean;
    }//from   www . j a v  a2  s  . c  o m

}

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

/**
 * Get system info//from   w ww.  j  av  a  2  s  .c  om
 */
public static SimpleOrderedMap<Object> getSystemInfo() throws Exception {
    SimpleOrderedMap<Object> info = new SimpleOrderedMap<Object>();

    OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
    info.add("name", os.getName());
    info.add("version", os.getVersion());
    info.add("arch", os.getArch());

    // Java 1.6
    addGetterIfAvaliable(os, "systemLoadAverage", info);

    // com.sun.management.UnixOperatingSystemMXBean
    addGetterIfAvaliable(os, "openFileDescriptorCount", info);
    addGetterIfAvaliable(os, "maxFileDescriptorCount", info);

    // com.sun.management.OperatingSystemMXBean
    addGetterIfAvaliable(os, "committedVirtualMemorySize", info);
    addGetterIfAvaliable(os, "totalPhysicalMemorySize", info);
    addGetterIfAvaliable(os, "totalSwapSpaceSize", info);
    addGetterIfAvaliable(os, "processCpuTime", info);

    try {
        if (!os.getName().toLowerCase(Locale.ENGLISH).startsWith("windows")) {
            // Try some command line things
            info.add("uname", execute("uname -a"));
            info.add("ulimit", execute("ulimit -n"));
            info.add("uptime", execute("uptime"));
        }
    } catch (Throwable ex) {
    } // ignore
    return info;
}

From source file:it.damore.tomee.envmonitor.services.EnvMonitorService.java

@GET
@Path("monitor")
@Produces({ MediaType.APPLICATION_JSON })
public EnvironmentConfig getEnvConfig() throws IllegalAccessException, InvocationTargetException {
    logger.info("received a request...");

    int mb = 1024 * 1024;
    //Getting the runtime reference from system
    Runtime runtime = Runtime.getRuntime();

    EnvironmentConfig b = new EnvironmentConfig();
    b.setMaxMemory(runtime.maxMemory() / mb);
    b.setFreeMemory(runtime.freeMemory() / mb);
    b.setTotalMemory(runtime.totalMemory() / mb);
    b.setSystemProperties(System.getProperties());

    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    LocalRuntimeMXBean myRuntimeMXBean = new LocalRuntimeMXBean();
    BeanUtils.copyProperties(myRuntimeMXBean, runtimeMXBean);
    b.setRuntimeMXBean(myRuntimeMXBean);

    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    LocalMemoryMXBean myMemoryMXBean = new LocalMemoryMXBean();
    myMemoryMXBean.setHeapMemoryUsage(memoryMXBean.getHeapMemoryUsage());
    myMemoryMXBean.setNonHeapMemoryUsage(memoryMXBean.getNonHeapMemoryUsage());
    myMemoryMXBean.setObjectPendingFinalizationCount(memoryMXBean.getObjectPendingFinalizationCount());
    b.setMemoryMXBean(myMemoryMXBean);//w  w w . ja  v a2 s  .  co m

    OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    LocalOperatingSystemMXBean myOperatingSystemMXBean = new LocalOperatingSystemMXBean();
    BeanUtils.copyProperties(myOperatingSystemMXBean, operatingSystemMXBean);
    b.setOperatingSystemMXBean(myOperatingSystemMXBean);

    return b;
}

From source file:org.pepstock.jem.node.NodeInfoUtility.java

/**
  * Factory creates a NodeInfo copying a set of information from Member
  * object of Hazelcast framework. NodeInfo will use Uuid of Member as the
  * key.// www .j a  va 2s . c  om
  * 
  * @see org.pepstock.jem.node.NodeInfo
  * @param member member object of Hazelcast framework
  * @param info node info to load
  * @throws NodeException if any exception occurs
  */
public static final void loadNodeInfo(Member member, NodeInfo info) throws NodeException {
    String jemVersion = getManifestAttribute(ConfigKeys.JEM_MANIFEST_VERSION);
    // sets the version
    if (jemVersion != null) {
        info.setJemVersion(jemVersion);
    }
    // set uuid of member of hazelcast as key
    info.setKey(member.getUuid());
    // set status starting at the beginning
    info.setStatus(Status.STARTING);
    // sets boolean if has affinity loader

    // for net info of member, loads all info inside of nodeinfo
    // port of RMI will be set later
    InetSocketAddress address = member.getInetSocketAddress();
    info.setPort(address.getPort());
    info.setIpaddress(address.getAddress().getHostAddress());

    // sets label to be displayed by GRS
    info.setLabel(info.getIpaddress() + ":" + info.getPort());

    // sets execution environment
    info.setExecutionEnvironment(Main.EXECUTION_ENVIRONMENT);
    // use JMX to extract current process id
    info.setProcessId(ManagementFactory.getRuntimeMXBean().getName());

    // extracts the name using the MXBean result
    String hostname = StringUtils.substringAfter(info.getProcessId(), "@");
    info.setHostname(hostname);

    // extracts from operating ssytem MXbean all info about the ssytem
    OperatingSystemMXBean bean = ManagementFactory.getOperatingSystemMXBean();
    info.getNodeInfoBean().setSystemArchitecture(bean.getArch());
    info.getNodeInfoBean().setAvailableProcessors(bean.getAvailableProcessors());
    info.getNodeInfoBean().setSystemName(bean.getName());

    // uses SIGAR to get total memory and the user used by JEM to start
    try {
        info.getNodeInfoBean().setTotalMemory(SIGAR.getMem().getTotal());
        ProcCredName cred = SIGAR.getProcCredName(SIGAR.getPid());
        info.setUser(cred.getUser());
    } catch (SigarException e) {
        throw new NodeException(e.getMessage(), e);
    }
    // informs the node itself that it has been loaded
    info.loaded();
}

From source file:de.tbuchloh.kiskis.cracker.PasswordCracker.java

public String crackPassword() {
    final Long totalEstimation = _passwordCreator.estimateTotalCount();
    _progressListener.notifyTotalCount(totalEstimation);
    _progressListener.notifyStartTime(System.currentTimeMillis());

    final AtomicBoolean found = new AtomicBoolean(false);
    final Callable<String> callable = new Callable<String>() {

        @Override//from  w w  w . jav a  2s  .  c  o m
        public String call() throws Exception {
            String guess;
            while (!found.get() && (guess = _passwordCreator.create()) != null) {
                _progressListener.notifyTry(guess);
                if (_tester.test(guess)) {
                    found.set(true);
                    return guess;
                }
            }
            return null;
        }
    };

    final int cpus = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
    LOG.info(String.format("Found %1$d cpus ...", cpus));
    final ExecutorService threadPool = Executors.newFixedThreadPool(cpus);
    final Collection<Callable<String>> tasks = new ArrayList<Callable<String>>();
    for (int i = 0; i < cpus; ++i) {
        tasks.add(callable);
    }
    try {
        final List<Future<String>> futures = threadPool.invokeAll(tasks);
        for (final Future<String> future : futures) {
            final String guessedPwd = future.get();
            if (guessedPwd != null) {
                return guessedPwd;
            }
        }
        return null;
    } catch (final InterruptedException e) {
        throw new KisKisRuntimeException("InterruptedException", e);
    } catch (final ExecutionException e) {
        throw new KisKisRuntimeException("ExecutionException", e);
    }
}

From source file:edu.usu.sdl.openstorefront.web.rest.service.Application.java

@GET
@RequireAdmin// www  .j a v a  2  s . com
@APIDescription("Gets the application system status")
@Produces({ MediaType.APPLICATION_JSON })
@DataType(ApplicationStatus.class)
@Path("/status")
public Response getApplicationStatus() {
    OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    List<GarbageCollectorMXBean> garbageCollectorMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

    ApplicationStatus applicationStatus = new ApplicationStatus();
    applicationStatus.setApplicationVersion(PropertiesManager.getApplicationVersion());
    applicationStatus.setProcessorCount(operatingSystemMXBean.getAvailableProcessors());
    applicationStatus.setSystemLoad(operatingSystemMXBean.getSystemLoadAverage());
    applicationStatus.setSystemProperties(runtimeMXBean.getSystemProperties());

    applicationStatus.getHeapMemoryStatus().setName("Heap");
    applicationStatus.getHeapMemoryStatus().setDetails(memoryMXBean.getHeapMemoryUsage().toString());
    applicationStatus.getHeapMemoryStatus()
            .setInitKb(memoryMXBean.getHeapMemoryUsage().getInit() != 0
                    ? memoryMXBean.getHeapMemoryUsage().getInit() / 1024
                    : 0);
    applicationStatus.getHeapMemoryStatus()
            .setUsedKb(memoryMXBean.getHeapMemoryUsage().getUsed() != 0
                    ? memoryMXBean.getHeapMemoryUsage().getUsed() / 1024
                    : 0);
    applicationStatus.getHeapMemoryStatus()
            .setMaxKb(memoryMXBean.getHeapMemoryUsage().getMax() != 0
                    ? memoryMXBean.getHeapMemoryUsage().getMax() / 1024
                    : 0);
    applicationStatus.getHeapMemoryStatus()
            .setCommitedKb(memoryMXBean.getHeapMemoryUsage().getCommitted() != 0
                    ? memoryMXBean.getHeapMemoryUsage().getCommitted() / 1024
                    : 0);

    applicationStatus.getNonHeapMemoryStatus().setName("Non-Heap");
    applicationStatus.getNonHeapMemoryStatus().setDetails(memoryMXBean.getNonHeapMemoryUsage().toString());
    applicationStatus.getNonHeapMemoryStatus()
            .setInitKb(memoryMXBean.getNonHeapMemoryUsage().getInit() != 0
                    ? memoryMXBean.getNonHeapMemoryUsage().getInit() / 1024
                    : 0);
    applicationStatus.getNonHeapMemoryStatus()
            .setUsedKb(memoryMXBean.getNonHeapMemoryUsage().getUsed() != 0
                    ? memoryMXBean.getNonHeapMemoryUsage().getUsed() / 1024
                    : 0);
    applicationStatus.getNonHeapMemoryStatus()
            .setMaxKb(memoryMXBean.getNonHeapMemoryUsage().getMax() != 0
                    ? memoryMXBean.getNonHeapMemoryUsage().getMax() / 1024
                    : 0);
    applicationStatus.getNonHeapMemoryStatus()
            .setCommitedKb(memoryMXBean.getNonHeapMemoryUsage().getCommitted() != 0
                    ? memoryMXBean.getNonHeapMemoryUsage().getCommitted() / 1024
                    : 0);

    applicationStatus.setLiveThreadCount(threadMXBean.getThreadCount());
    applicationStatus.setTotalThreadCount(threadMXBean.getTotalStartedThreadCount());

    applicationStatus.setStartTime(new Date(runtimeMXBean.getStartTime()));
    applicationStatus.setUpTime(TimeUtil.millisToString(runtimeMXBean.getUptime()));

    for (GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMXBeans) {
        applicationStatus.getGarbageCollectionInfos()
                .add(TimeUtil.millisToString(garbageCollectorMXBean.getCollectionTime()) + " - ("
                        + garbageCollectorMXBean.getCollectionCount() + ")");
    }

    for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) {
        MemoryPoolStatus memoryPoolStatus = new MemoryPoolStatus();
        memoryPoolStatus.setName(memoryPoolMXBean.getName() + " - " + memoryPoolMXBean.getType());
        memoryPoolStatus.setDetails(memoryPoolMXBean.getUsage().toString());
        memoryPoolStatus.setInitKb(
                memoryPoolMXBean.getUsage().getInit() != 0 ? memoryPoolMXBean.getUsage().getInit() / 1024 : 0);
        memoryPoolStatus.setUsedKb(
                memoryPoolMXBean.getUsage().getUsed() != 0 ? memoryPoolMXBean.getUsage().getUsed() / 1024 : 0);
        memoryPoolStatus.setMaxKb(
                memoryPoolMXBean.getUsage().getMax() != 0 ? memoryPoolMXBean.getUsage().getMax() / 1024 : 0);
        memoryPoolStatus.setCommitedKb(memoryPoolMXBean.getUsage().getCommitted() != 0
                ? memoryPoolMXBean.getUsage().getCommitted() / 1024
                : 0);

        applicationStatus.getMemoryPools().add(memoryPoolStatus);
    }

    return sendSingleEntityResponse(applicationStatus);
}

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 ww  .ja  va2  s  .  c  om*/

    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:org.paxle.core.monitorable.provider.impl.JmxMonitoring.java

public JmxMonitoring() {
    this.operatingSystem = ManagementFactory.getOperatingSystemMXBean();
    this.runtime = ManagementFactory.getRuntimeMXBean();

    // testing which operations are available
    this.testMethod(VAR_NAME_SYS_LOAD, this.operatingSystem, "systemLoadAverage");
    this.testMethod(VAR_NAME_OPEN_FILE_DESCR_COUNT, this.operatingSystem, "openFileDescriptorCount");
    this.testMethod(VAR_NAME_MAX_FILE_DESCR_COUNT, this.operatingSystem, "maxFileDescriptorCount");
    this.testMethod(VAR_NAME_VIRTUAL_MEMORY, this.operatingSystem, "committedVirtualMemorySize");
    this.testMethod(VAR_NAME_PHYSICAL_MEMORY, this.operatingSystem, "totalPhysicalMemorySize");
    this.testMethod(VAR_NAME_SWAP_SPACE, this.operatingSystem, "totalSwapSpaceSize");
    this.testMethod(VAR_NAME_CPU_TIME, this.operatingSystem, "processCpuTime");
    this.testMethod(VAR_NAME_UPTIME, this.runtime, "uptime");
    this.testMethod(VAR_NAME_STARTTIME, this.runtime, "startTime");
}

From source file:eu.openanalytics.rsb.component.SystemHealthResource.java

@GET
@Path("/info")
@Produces({ Constants.RSB_XML_CONTENT_TYPE, Constants.RSB_JSON_CONTENT_TYPE })
public NodeInformation getInfo(@Context final ServletContext sc) {
    final NodeInformation info = Util.REST_OBJECT_FACTORY.createNodeInformation();

    info.setName(getConfiguration().getNodeName());
    info.setHealthy(nodeHealthy.get());//from www. ja va  2s . c  o m
    info.setRsbVersion(getClass().getPackage().getImplementationVersion());
    info.setServletContainerInfo(sc.getServerInfo());

    final OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    info.setOsLoadAverage(operatingSystemMXBean.getSystemLoadAverage());

    final Runtime runtime = Runtime.getRuntime();
    info.setJvmMaxMemory(runtime.maxMemory());
    info.setJvmFreeMemory(runtime.freeMemory());

    final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    final long uptimeMilliseconds = runtimeMXBean.getUptime();
    info.setUptime(uptimeMilliseconds);
    info.setUptimeText(DurationFormatUtils.formatDurationWords(uptimeMilliseconds, true, true));

    return info;
}

From source file:org.pepstock.jem.node.system.GetJobSystemActivity.java

/**
 * Checks if job is the same of passed and returns system resources
 * consumption//  w w w. j  a  va  2s. c  o m
 * 
 * @return system activity object with all used resources by the job
 * @throws SigarException 
 * @throws Exception occurs if errors
 */
@Override
public JobSystemActivity call() throws SigarException {
    JobSystemActivity activity = new JobSystemActivity();

    // check if there's a job current in execution. If not, do nothing
    if (Main.CURRENT_TASKS.containsKey(job.getId())) {
        // Checks if the job, passed as parameter, is the same of current
        // node. If not, logs a warning

        // parse process id because the form is pid@hostname
        String pid = StringUtils.substringBefore(job.getProcessId(), "@");
        long longPid = Parser.parseLong(pid, -1L);

        // if pid is correct
        if (longPid != -1L) {
            // gets sigar clearing the cache
            Sigar sigar = new Sigar();
            SigarProxy proxyFirst = SigarProxyCache.newInstance(sigar, 0);

            // gets all processes
            OSProcess head = getProcessesTree(longPid, proxyFirst);
            // gets cpu
            long cpuFirst = getCpu(head);
            sigar.close();
            // clear SIGAR
            SigarProxyCache.clear(proxyFirst);
            // wait for another sample
            try {
                Thread.sleep(INTERVAL);
            } catch (InterruptedException e) {
                // ignore
                LogAppl.getInstance().ignore(e.getMessage(), e);
            }

            // gets sigar clearing the cache
            sigar = new Sigar();
            SigarProxy proxyLast = SigarProxyCache.newInstance(sigar, 0);
            // gets new OSprocess
            head = getProcessesTree(longPid, proxyLast);
            // gets CPU
            long cpuLast = getCpu(head);

            // calculate consumed CPU
            long cpuUsed = cpuLast - cpuFirst;
            // gets possible using the processors amount
            long totPossibleCpu = INTERVAL
                    * ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();

            double cpuUsedPercent = cpuUsed * 1D / totPossibleCpu;
            cpuUsedPercent = Math.min(Math.max(cpuUsedPercent, 0D), 1D);
            activity.setCpu(cpuLast);
            activity.setCpuPerc(cpuUsedPercent);
            // gets MEMORY
            activity.setMemory(getMemory(head));
            activity.setActive(true);
            sigar.close();

            activity.setProcess(head);
        }
    }
    return activity;
}