Example usage for java.lang.management ManagementFactory getPlatformMBeanServer

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

Introduction

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

Prototype

public static synchronized MBeanServer getPlatformMBeanServer() 

Source Link

Document

Returns the platform javax.management.MBeanServer MBeanServer .

Usage

From source file:org.apache.streams.jackson.DatumStatusCounterDeserializer.java

@Override
public DatumStatusCounterBroadcast deserialize(JsonParser jsonParser,
        DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    try {//from  w  ww  .  j  a  va2 s  . c  o  m
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();

        DatumStatusCounterBroadcast datumStatusCounterBroadcast = new DatumStatusCounterBroadcast();
        JsonNode attributes = jsonParser.getCodec().readTree(jsonParser);

        ObjectName name = new ObjectName(attributes.get("canonicalName").asText());
        MBeanInfo info = server.getMBeanInfo(name);
        datumStatusCounterBroadcast.setName(name.toString());

        for (MBeanAttributeInfo attribute : Arrays.asList(info.getAttributes())) {
            try {
                switch (attribute.getName()) {
                case "Failed":
                    datumStatusCounterBroadcast
                            .setFailed((boolean) server.getAttribute(name, attribute.getName()));
                    break;
                case "Passed":
                    datumStatusCounterBroadcast
                            .setPassed((boolean) server.getAttribute(name, attribute.getName()));
                    break;
                }
            } catch (Exception e) {
                LOGGER.error("Exception trying to deserialize DatumStatusCounterBroadcast object: {}", e);
            }
        }

        return datumStatusCounterBroadcast;
    } catch (Exception e) {
        LOGGER.error("Exception trying to deserialize DatumStatusCounterBroadcast object: {}", e);
        return null;
    }
}

From source file:org.apache.synapse.commons.snmp.SynapseMOScalar.java

@Override
public Variable getValue() {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {//from   w w  w  . j av  a 2  s.co m
        Object obj = mbs.getAttribute(objectName, attribute);
        if (obj instanceof Integer) {
            return new Integer32((Integer) obj);
        }

        if (snmpVersion > SnmpConstants.version1) {
            if (obj instanceof Long) {
                return new Counter64(((Long) obj).longValue());
            } else if (obj instanceof Date) {
                return new Counter64(((Date) obj).getTime());
            }
        }

        return new OctetString(obj.toString());
    } catch (Exception e) {
        log.error("Unexpected error while retrieving the value of OID: " + getID(), e);
        return null;
    }
}

From source file:org.apache.streams.jackson.ThroughputQueueDeserializer.java

@Override
public ThroughputQueueBroadcast deserialize(JsonParser jsonParser,
        DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    try {//from w  ww.  ja  v a  2 s .c o m
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();

        ThroughputQueueBroadcast throughputQueueBroadcast = new ThroughputQueueBroadcast();
        JsonNode attributes = jsonParser.getCodec().readTree(jsonParser);

        ObjectName name = new ObjectName(attributes.get("canonicalName").asText());
        MBeanInfo info = server.getMBeanInfo(name);
        throughputQueueBroadcast.setName(name.toString());

        for (MBeanAttributeInfo attribute : Arrays.asList(info.getAttributes())) {
            try {
                switch (attribute.getName()) {
                case "CurrentSize":
                    throughputQueueBroadcast
                            .setCurrentSize((long) server.getAttribute(name, attribute.getName()));
                    break;
                case "AvgWait":
                    throughputQueueBroadcast
                            .setAvgWait((double) server.getAttribute(name, attribute.getName()));
                    break;
                case "MaxWait":
                    throughputQueueBroadcast.setMaxWait((long) server.getAttribute(name, attribute.getName()));
                    break;
                case "Removed":
                    throughputQueueBroadcast.setRemoved((long) server.getAttribute(name, attribute.getName()));
                    break;
                case "Added":
                    throughputQueueBroadcast.setAdded((long) server.getAttribute(name, attribute.getName()));
                    break;
                case "Throughput":
                    throughputQueueBroadcast
                            .setThroughput((double) server.getAttribute(name, attribute.getName()));
                    break;
                }
            } catch (Exception e) {
                LOGGER.error("Exception while trying to deserialize ThroughputQueueBroadcast object: {}", e);
            }
        }

        return throughputQueueBroadcast;
    } catch (Exception e) {
        return null;
    }
}

From source file:org.apache.streams.jackson.MemoryUsageDeserializer.java

@Override
public MemoryUsageBroadcast deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
        throws IOException, JsonProcessingException {
    try {/*from   ww  w .  j a v  a2  s.  c  om*/
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();

        MemoryUsageBroadcast memoryUsageBroadcast = new MemoryUsageBroadcast();
        JsonNode attributes = jsonParser.getCodec().readTree(jsonParser);

        ObjectName name = new ObjectName(attributes.get("canonicalName").asText());
        MBeanInfo info = server.getMBeanInfo(name);
        memoryUsageBroadcast.setName(name.toString());

        for (MBeanAttributeInfo attribute : Arrays.asList(info.getAttributes())) {
            switch (attribute.getName()) {
            case "Verbose":
                memoryUsageBroadcast.setVerbose((boolean) server.getAttribute(name, attribute.getName()));
                break;
            case "ObjectPendingFinalizationCount":
                memoryUsageBroadcast.setObjectPendingFinalizationCount(
                        Long.parseLong(server.getAttribute(name, attribute.getName()).toString()));
                break;
            case "HeapMemoryUsage":
                memoryUsageBroadcast.setHeapMemoryUsage(
                        (Long) ((CompositeDataSupport) server.getAttribute(name, attribute.getName()))
                                .get("used"));
                break;
            case "NonHeapMemoryUsage":
                memoryUsageBroadcast.setNonHeapMemoryUsage(
                        (Long) ((CompositeDataSupport) server.getAttribute(name, attribute.getName()))
                                .get("used"));
                break;
            }
        }

        return memoryUsageBroadcast;
    } catch (Exception e) {
        LOGGER.error("Exception trying to deserialize MemoryUsageDeserializer object: {}", e);
        return null;
    }
}

From source file:org.apache.streams.jackson.StreamsTaskCounterDeserializer.java

@Override
public StreamsTaskCounterBroadcast deserialize(JsonParser jsonParser,
        DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    try {/* w w  w.jav a 2 s.c  o m*/
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();

        StreamsTaskCounterBroadcast streamsTaskCounterBroadcast = new StreamsTaskCounterBroadcast();
        JsonNode attributes = jsonParser.getCodec().readTree(jsonParser);

        ObjectName name = new ObjectName(attributes.get("canonicalName").asText());
        MBeanInfo info = server.getMBeanInfo(name);
        streamsTaskCounterBroadcast.setName(name.toString());

        for (MBeanAttributeInfo attribute : Arrays.asList(info.getAttributes())) {
            try {
                switch (attribute.getName()) {
                case "ErrorRate":
                    streamsTaskCounterBroadcast
                            .setErrorRate((double) server.getAttribute(name, attribute.getName()));
                    break;
                case "NumEmitted":
                    streamsTaskCounterBroadcast
                            .setNumEmitted((long) server.getAttribute(name, attribute.getName()));
                    break;
                case "NumReceived":
                    streamsTaskCounterBroadcast
                            .setNumReceived((long) server.getAttribute(name, attribute.getName()));
                    break;
                case "NumUnhandledErrors":
                    streamsTaskCounterBroadcast
                            .setNumUnhandledErrors((long) server.getAttribute(name, attribute.getName()));
                    break;
                case "AvgTime":
                    streamsTaskCounterBroadcast
                            .setAvgTime((double) server.getAttribute(name, attribute.getName()));
                    break;
                case "MaxTime":
                    streamsTaskCounterBroadcast
                            .setMaxTime((long) server.getAttribute(name, attribute.getName()));
                    break;
                }
            } catch (Exception e) {
                LOGGER.error("Exception while trying to deserialize StreamsTaskCounterBroadcast object: {}", e);
            }
        }

        return streamsTaskCounterBroadcast;
    } catch (Exception e) {
        LOGGER.error("Exception while trying to deserialize StreamsTaskCounterBroadcast object: {}", e);
        return null;
    }
}

From source file:org.xwiki.management.internal.DefaultJMXBeanRegistration.java

@Override
public void registerMBean(Object mbean, String name) {
    // Make sure we never fail since XWiki should execute correctly even if there's no MBean Server running.
    try {// w  w  w .  j  a v a 2s  .c  o  m
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName oname = new ObjectName(OBJECTNAME_PREFIX + name);
        mbs.registerMBean(mbean, oname);
        this.logger.debug("Registered resource with name [{}]", name);
    } catch (Exception e) {
        // Failed to register the MBean, log a warning
        this.logger.warn("Failed to register resource with name [{}]. Reason = [{}]", name,
                ExceptionUtils.getMessage(e));
    }
}

From source file:ca.simplegames.micro.controllers.StatsController.java

public void execute(MicroContext context, Map configuration) throws ControllerException {
    Map<String, Object> systemInfo = new HashMap<String, Object>();
    Map<String, Object> osMap = new HashMap<String, Object>();
    MBeanServerConnection mbeanServer = ManagementFactory.getPlatformMBeanServer();

    OperatingSystemMXBean sunOperatingSystemMXBean = null;
    try {// w  w w  .  j a v  a  2  s .com
        sunOperatingSystemMXBean = ManagementFactory.newPlatformMXBeanProxy(mbeanServer,
                ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
    } catch (IOException e) {
        throw new ControllerException(e.getMessage());
    }

    Runtime rt = Runtime.getRuntime();
    long totalMemory = rt.totalMemory() / MEGA_BYTE;
    long freeMemory = rt.freeMemory() / MEGA_BYTE;
    long usedMemory = totalMemory - freeMemory;

    final long p100 = (int) Math.round(((double) freeMemory / (double) totalMemory) * 100);

    Map<String, Long> memInfo = new HashMap<String, Long>();

    memInfo.put("total", totalMemory);
    memInfo.put("used", usedMemory);
    memInfo.put("free", freeMemory);
    memInfo.put("percent_free", p100);

    systemInfo.put("memory", memInfo);
    systemInfo.put("powered_by", POWERED_BY_MICRO);

    //cpu usage in milli secs
    long currentCpuUsage = sunOperatingSystemMXBean.getProcessCpuTime() / 1000000;
    osMap.put("cpu_usage", currentCpuUsage);
    osMap.put("available_processors", sunOperatingSystemMXBean.getAvailableProcessors());
    osMap.put("system_load_average", sunOperatingSystemMXBean.getSystemLoadAverage());
    osMap.put("committed_virtual_memory_size", sunOperatingSystemMXBean.getCommittedVirtualMemorySize());
    osMap.put("free_physical_memory_size", sunOperatingSystemMXBean.getFreePhysicalMemorySize());
    osMap.put("total_physical_memory_size", sunOperatingSystemMXBean.getTotalPhysicalMemorySize());
    osMap.put("free_swap_space_size", sunOperatingSystemMXBean.getFreeSwapSpaceSize());
    osMap.put("total_swap_space_size", sunOperatingSystemMXBean.getTotalSwapSpaceSize());

    systemInfo.put("os", osMap);

    List<GarbageCollectorMXBean> gc = ManagementFactory.getGarbageCollectorMXBeans();
    List<Map> gcInfo = new ArrayList<Map>();

    for (GarbageCollectorMXBean aGc : gc) {
        Map<String, Object> gcMap = new HashMap<String, Object>();
        gcMap.put("name", aGc.getName());
        gcMap.put("collection_count", aGc.getCollectionCount());
        gcMap.put("collection_time", aGc.getCollectionTime());

        gcInfo.add(gcMap);
    }

    systemInfo.put("gc", gcInfo);

    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    Map<String, Object> threadInfoMap = new HashMap<String, Object>(); // more to come ;)
    threadInfoMap.put("peak_thread_count", threadMXBean.getPeakThreadCount());
    threadInfoMap.put("thread_count", threadMXBean.getThreadCount());
    threadInfoMap.put("total_started_thread_count", threadMXBean.getTotalStartedThreadCount());

    long[] deadlockedThreads = threadMXBean.findMonitorDeadlockedThreads();
    threadInfoMap.put("dead_locked_thread_count", deadlockedThreads != null ? deadlockedThreads.length : 0);
    systemInfo.put("thread_info", threadInfoMap);

    JSONObject sysinfoJson = new JSONObject(Collections.singletonMap("system_info", systemInfo));

    String sysinfoString = null;
    try {
        sysinfoString = context.getRequest().getParameter("pretty") != null ? sysinfoJson.toString(2)
                : sysinfoJson.toString();
    } catch (JSONException e) {
        e.printStackTrace();
        throw new ControllerException(e.getMessage());
    }

    context.getRackResponse().withContentType(Mime.mimeType(JSON_TYPE)).withBody(sysinfoString)
            .withContentLength(sysinfoString.length()).with(Rack.MESSAGE_STATUS, HttpServletResponse.SC_OK);

    context.halt();
}

From source file:com.espertech.esper.metrics.jmx.CommonJMXUtil.java

private static void unregisterMbean(ObjectName name) {
    try {//w ww .  jav  a 2  s.c o m
        ManagementFactory.getPlatformMBeanServer().unregisterMBean(name);
    } catch (Exception e) {
        log.error("Error unregistering mbean: " + e.getMessage(), e);
    }
}

From source file:org.jolokia.jmx.JolokiaMBeanServerTest.java

@Test
public void simple() throws NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanException,
        MalformedObjectNameException, AttributeNotFoundException, ReflectionException,
        InstanceNotFoundException, ParseException, InvalidTargetObjectTypeException, NoSuchMethodException,
        IntrospectionException {//from   w w  w .  j  av  a2s .  c  o  m
    JolokiaMBeanServer server = new JolokiaMBeanServer();

    ObjectName oName = new ObjectName("test:type=jsonMBean");
    server.registerMBean(new JsonAnnoTest(), oName);

    CompositeData chiliCD = (CompositeData) server.getAttribute(oName, "Chili");
    assertEquals((String) chiliCD.get("name"), "Bhut Jolokia");
    assertEquals(chiliCD.get("scoville"), 1000000L);

    MBeanServer pServer = ManagementFactory.getPlatformMBeanServer();
    String chiliS = (String) pServer.getAttribute(oName, "Chili");
    JSONObject chiliJ = (JSONObject) new JSONParser().parse(chiliS);
    assertEquals(chiliJ.get("name"), "Bhut Jolokia");
    assertEquals(chiliJ.get("scoville"), 1000000L);

    server.unregisterMBean(oName);
    Assert.assertFalse(pServer.isRegistered(oName));
    Assert.assertFalse(server.isRegistered(oName));
}

From source file:co.paralleluniverse.common.monitoring.Monitor.java

public void registerMBean() {
    try {//from  w ww  .  j ava2 s  .  c  o  m
        LOG.info("Registering MBean {}", name);
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName mxbeanName = new ObjectName(name);
        mbs.registerMBean(this, mxbeanName);

        this.registered = true;
    } catch (InstanceAlreadyExistsException ex) {
        throw new RuntimeException(ex);
    } catch (MBeanRegistrationException ex) {
        throw new RuntimeException(ex);
    } catch (NotCompliantMBeanException ex) {
        throw new AssertionError(ex);
    } catch (MalformedObjectNameException ex) {
        throw new AssertionError(ex);
    }
}