Java Code Examples for java.lang.management.ManagementFactory#getPlatformMBeanServer()

The following examples show how to use java.lang.management.ManagementFactory#getPlatformMBeanServer() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MBeanUtil.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * Register the MBean using our standard MBeanName format
 * "hadoop:service=<serviceName>,name=<nameName>"
 * Where the <serviceName> and <nameName> are the supplied parameters
 *    
 * @param serviceName
 * @param nameName
 * @param theMbean - the MBean to register
 * @return the named used to register the MBean
 */	
static public ObjectName registerMBean(final String serviceName, 
  							final String nameName,
  							final Object theMbean) {
  final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
  ObjectName name = getMBeanName(serviceName, nameName);
  try {
    mbs.registerMBean(theMbean, name);
    return name;
  } catch (InstanceAlreadyExistsException ie) {
    // Ignore if instance already exists 
  } catch (Exception e) {
    e.printStackTrace();
  }
  return null;
}
 
Example 2
Source File: ServerManager.java    From bistoury with GNU General Public License v3.0 6 votes vote down vote up
private static String getTomcatPortByMxBean() {
    String tomcatPort = "-1";
    try {
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();
        if (server != null) {
            Set<ObjectName> objectNames = server.queryNames(new ObjectName("*:type=Connector,*"),
                    Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
            tomcatPort = objectNames.iterator().next().getKeyProperty("port");
        }

    } catch (Exception e) {
        logger.error("get tomcat port error", e);
        throw Throwables.propagate(e);
    }
    return tomcatPort;
}
 
Example 3
Source File: ArgsBase.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
String []getJvmArgs()
{
  try {
    MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
    ObjectName name = new ObjectName("java.lang:type=Runtime");
    
    return (String []) mbeanServer.getAttribute(name, "InputArguments");
  } catch (Exception e) {
    log.log(Level.FINE, e.toString(), e);
    
    return null;
  }
}
 
Example 4
Source File: ModelControllerMBeanTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testMBeanServerNotification_REGISTRATION_NOTIFICATIONUsingManagementFactory() throws Exception {
    setup(new MBeanInfoAdditionalInitialization(ProcessType.STANDALONE_SERVER, new SubystemWithSingleFixedChildExtension()));
    MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();

    doTestMBeanServerNotification_REGISTRATION_NOTIFICATION(mbeanServer, true);
}
 
Example 5
Source File: GridMarshallerResourceBean.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Initialization.
 */
GridMarshallerResourceBean() {
    log = new JavaLogger();
    marshaller = new JdkMarshaller();
    mbeanSrv = ManagementFactory.getPlatformMBeanServer();
    ses = new GridTestTaskSession();
    execSvc = Executors.newSingleThreadExecutor();
    appCtx = new GenericApplicationContext();
    jobCtx = new GridTestJobContext();
    balancer = new LoadBalancer();
}
 
Example 6
Source File: FlightCommand.java    From LagMonitor with MIT License 5 votes vote down vote up
private boolean areFlightMethodsAvailable() {
    MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        ObjectName objectName = ObjectName.getInstance(DIAGNOSTIC_BEAN);
        MBeanInfo beanInfo = beanServer.getMBeanInfo(objectName);
        return Arrays.stream(beanInfo.getOperations())
                .map(MBeanFeatureInfo::getName)
                .anyMatch(op -> op.contains("jfr"));
    } catch (JMException instanceNotFoundEx) {
        return false;
    }
}
 
Example 7
Source File: StatusManager.java    From das with Apache License 2.0 5 votes vote down vote up
private static void verifyRegistration() throws Exception{
	MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
	
	if(mbs.isRegistered(getGlobalName(HAStatus.class))){
		logger.warn("DAL Management Bean has already been initialized. Please make remove your application's Context registration in server.xml under Tomcat conf folder.");
	};
}
 
Example 8
Source File: GetDiagnosticOptions.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    List<HotSpotDiagnosticMXBean> list =
        ManagementFactory.getPlatformMXBeans(HotSpotDiagnosticMXBean.class);
    HotSpotDiagnosticMXBean mbean = list.get(0);
    checkDiagnosticOptions(mbean);

    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    mbean = ManagementFactory.newPlatformMXBeanProxy(mbs,
                HOTSPOT_DIAGNOSTIC_MXBEAN_NAME,
                HotSpotDiagnosticMXBean.class);
    checkDiagnosticOptions(mbean);
}
 
Example 9
Source File: JmxUtil.java    From ns4_gear_watchdog with Apache License 2.0 5 votes vote down vote up
public static MBeanServer getMBeanServer() {
    MBeanServer server;
    //if (!MBeanServerFactory.findMBeanServer(null).isEmpty()) {
    //    server = MBeanServerFactory.findMBeanServer(null).get(0);
    //} else {
    server = ManagementFactory.getPlatformMBeanServer();
    //}
    return server;
}
 
Example 10
Source File: ServerConstants.java    From mapleLemon with GNU General Public License v2.0 5 votes vote down vote up
public static void registerMBean() {
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        instance = new ServerConstants();
        mBeanServer.registerMBean(instance, new ObjectName("constants:type=ServerConstants"));
    } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) {
        FileoutputUtil.log(e.getMessage());
        FileoutputUtil.log("Error registering Shutdown MBean");
    }
}
 
Example 11
Source File: JMXJsonServlet.java    From datacollector with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize this servlet.
 */
@Override
public void init() throws ServletException {
  // Retrieve the MBean server
  mBeanServer = ManagementFactory.getPlatformMBeanServer();
  jsonFactory = new JsonFactory();
}
 
Example 12
Source File: MBeanRegistration.java    From development with Apache License 2.0 4 votes vote down vote up
public MBeanRegistration(String mbeanRegistrationName, EJBClientFacade clientFacade) {
    this.mbeanRegistrationName = mbeanRegistrationName;
    this.clientFacade = clientFacade;
    mbeanServer = ManagementFactory.getPlatformMBeanServer();
}
 
Example 13
Source File: MXBeanInteropTest1.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
public void run(Map<String, Object> args) {

        System.out.println("MXBeanInteropTest1::run: Start") ;
        int errorCount = 0 ;

        try {
            // JMX MbeanServer used inside single VM as if remote.
            // MBeanServer mbs = MBeanServerFactory.newMBeanServer();
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

            JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
            JMXConnectorServer cs =
                JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
            cs.start();

            JMXServiceURL addr = cs.getAddress();
            JMXConnector cc = JMXConnectorFactory.connect(addr);
            MBeanServerConnection mbsc = cc.getMBeanServerConnection();

            // Print out registered java.lang.management MXBeans found
            // in the remote jvm.
            printMBeans(mbsc) ;

            // For each possible kind of JDK 5 defined MXBean, we retrieve its
            // MBeanInfo and print it and we call all getters and print
            // their output.
            errorCount += doClassLoadingMXBeanTest(mbsc) ;
            errorCount += doMemoryMXBeanTest(mbsc) ;
            errorCount += doThreadMXBeanTest(mbsc) ;
            errorCount += doRuntimeMXBeanTest(mbsc) ;
            errorCount += doOperatingSystemMXBeanTest(mbsc) ;
            errorCount += doCompilationMXBeanTest(mbsc) ;
            errorCount += doGarbageCollectorMXBeanTest(mbsc) ;
            errorCount += doMemoryManagerMXBeanTest(mbsc) ;
            errorCount += doMemoryPoolMXBeanTest(mbsc) ;

            // Terminate the JMX Client
            cc.close();

        } catch(Exception e) {
            Utils.printThrowable(e, true) ;
            throw new RuntimeException(e);
        }

        if ( errorCount == 0 ) {
            System.out.println("MXBeanInteropTest1::run: Done without any error") ;
        } else {
            System.out.println("MXBeanInteropTest1::run: Done with "
                    + errorCount
                    + " error(s)") ;
            throw new RuntimeException("errorCount = " + errorCount);
        }
    }
 
Example 14
Source File: RunningStateJmx.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static void registerMBean(ProcessStateNotifier processStateNotifier, SuspendController suspendController, RunningModeControl runningModeControl, boolean isServer) {
    try {
        final ObjectName name = new ObjectName(OBJECT_NAME);
        final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
        final RunningStateJmxMBean mbean = new RunningStateJmx(name, runningModeControl, isServer);
        if (server.isRegistered(name)) {
            server.unregisterMBean(name);
        }
        server.registerMBean(mbean, name);
        registerStateListener(mbean, processStateNotifier);
        if (suspendController != null) {
            suspendController.addListener(new OperationListener() {
                @Override
                public void suspendStarted() {
                    mbean.setRunningState(mbean.getRunningState(), RunningState.SUSPENDING);
                }

                @Override
                public void complete() {
                    mbean.setRunningState(mbean.getRunningState(), RunningState.SUSPENDED);
                }

                @Override
                public void cancelled() {
                    if(mbean.getRunningState() == RunningState.STARTING) {
                        mbean.setRunningState(RunningState.STARTING, RunningState.SUSPENDED);
                    }
                    if (mbean.getRunningMode() == RunningMode.NORMAL) {
                        mbean.setRunningState(mbean.getRunningState(), RunningState.NORMAL);
                    } else {
                        mbean.setRunningState(mbean.getRunningState(),RunningState.ADMIN_ONLY);
                    }
                }

                @Override
                public void timeout() {
                }
            });
        } else {
            mbean.setRunningState(null, RunningState.STARTING);
        }
    } catch (InstanceAlreadyExistsException | InstanceNotFoundException | MBeanRegistrationException | MalformedObjectNameException | NotCompliantMBeanException e) {
        throw new RuntimeException(e);
    }
}
 
Example 15
Source File: CounterMonitorDeadlockTest.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
void run() throws Exception {
    final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    final ObjectName observedName = new ObjectName("a:b=c");
    final ObjectName monitorName = new ObjectName("a:type=Monitor");
    mbs.registerMBean(new CounterMonitor(), monitorName);
    final CounterMonitorMBean monitorProxy =
        JMX.newMBeanProxy(mbs, monitorName, CounterMonitorMBean.class);
    final TestMBean observedProxy =
        JMX.newMBeanProxy(mbs, observedName, TestMBean.class);

    final Runnable sensitiveThing = new Runnable() {
        public void run() {
            doSensitiveThing(monitorProxy, observedName);
        }
    };

    final Runnable nothing = new Runnable() {
        public void run() {}
    };

    final Runnable withinGetAttribute =
        (when == When.IN_GET_ATTRIBUTE) ? sensitiveThing : nothing;

    mbs.registerMBean(new Test(withinGetAttribute), observedName);
    monitorProxy.addObservedObject(observedName);
    monitorProxy.setObservedAttribute("Thing");
    monitorProxy.setInitThreshold(100);
    monitorProxy.setGranularityPeriod(10L); // 10 ms
    monitorProxy.setNotify(true);
    monitorProxy.start();

    final int initGetCount = observedProxy.getGetCount();
    int getCount = initGetCount;
    for (int i = 0; i < 500; i++) { // 500 * 10 = 5 seconds
        getCount = observedProxy.getGetCount();
        if (getCount != initGetCount)
            break;
        Thread.sleep(10);
    }
    if (getCount <= initGetCount)
        throw new Exception("Test failed: presumable deadlock");
    // This won't show up as a deadlock in CTRL-\ or in
    // ThreadMXBean.findDeadlockedThreads(), because they don't
    // see that thread A is waiting for thread B (B.join()), and
    // thread B is waiting for a lock held by thread A

    // Now we know the monitor has observed the initial value,
    // so if we want to test notify behaviour we can trigger by
    // exceeding the threshold.
    if (when == When.IN_NOTIFY) {
        final AtomicInteger notifCount = new AtomicInteger();
        final NotificationListener listener = new NotificationListener() {
            public void handleNotification(Notification n, Object h) {
                Thread t = new Thread(sensitiveThing);
                t.start();
                try {
                    t.join();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                notifCount.incrementAndGet();
            }
        };
        mbs.addNotificationListener(monitorName, listener, null, null);
        observedProxy.setThing(1000);
        for (int i = 0; i < 500 && notifCount.get() == 0; i++)
            Thread.sleep(10);
        if (notifCount.get() == 0)
            throw new Exception("Test failed: presumable deadlock");
    }

}
 
Example 16
Source File: JMXMonConnectionPool.java    From jmeter-plugins with Apache License 2.0 4 votes vote down vote up
/**
 * Start a connection thread if none are running
 * @param attributes jmx connection attributes
 * @param wait if true wait the current thread until the end of the connection attempt
 */
protected synchronized void tryConnect(final Hashtable attributes, boolean wait)
{
	if (isLocalConnection()) {
		log.debug("Using local PlatformMBeanServer connection");
		connection = ManagementFactory.getPlatformMBeanServer();
		return;
	}
	connectionAttemptFlag = true;
	
	connectionAttemptThread = new Thread(new Runnable() {
		
		@Override
		public void run() {
			try {
				JMXServiceURL u = new JMXServiceURL(jmxUrl);
				log.debug("Create new connection url = " + jmxUrl);
	            connector = JMXConnectorFactory.connect(u, attributes);
	            connection = connector.getMBeanServerConnection();
	            
            } catch (MalformedURLException ex) {
                //throw new RuntimeException(ex);
                log.error("Malformed JMX url", ex);
            } catch (IOException ex) {
                log.error("IOException reading JMX", ex);
            }
			finally {
				connectionAttemptFlag = false;
			}
		}
	});
	
	connectionAttemptThread.start();
	
	if (wait)
		try {
			connectionAttemptThread.join();
		} catch (InterruptedException e) {
			log.warn("Connection thread has been interrupted", e);
		}
	
}
 
Example 17
Source File: TomcatGenericExports.java    From tomcat_exporter with Apache License 2.0 4 votes vote down vote up
private void addRequestProcessorMetrics(List<MetricFamilySamples> mfs) {
    try {
        final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
        ObjectName filterName = new ObjectName(jmxDomain + ":type=GlobalRequestProcessor,name=*");
        Set<ObjectInstance> mBeans = server.queryMBeans(filterName, null);

        if (mBeans.size() > 0) {
            List<String> labelNameList = Collections.singletonList("name");

            GaugeMetricFamily requestProcessorBytesReceivedGauge = new GaugeMetricFamily(
                    "tomcat_requestprocessor_received_bytes",
                    "Number of bytes received by this request processor",
                    labelNameList);

            GaugeMetricFamily requestProcessorBytesSentGauge = new GaugeMetricFamily(
                    "tomcat_requestprocessor_sent_bytes",
                    "Number of bytes sent by this request processor",
                    labelNameList);

            GaugeMetricFamily requestProcessorProcessingTimeGauge = new GaugeMetricFamily(
                    "tomcat_requestprocessor_time_seconds",
                    "The total time spend by this request processor",
                    labelNameList);

            CounterMetricFamily requestProcessorErrorCounter = new CounterMetricFamily(
                    "tomcat_requestprocessor_error_count",
                    "The number of error request served by this request processor",
                    labelNameList);

            CounterMetricFamily requestProcessorRequestCounter = new CounterMetricFamily(
                    "tomcat_requestprocessor_request_count",
                    "The number of request served by this request processor",
                    labelNameList);

            for (final ObjectInstance mBean : mBeans) {
                List<String> labelValueList = Collections.singletonList(mBean.getObjectName().getKeyProperty("name").replaceAll("[\"\\\\]", ""));

                requestProcessorBytesReceivedGauge.addMetric(
                        labelValueList,
                        ((Long) server.getAttribute(mBean.getObjectName(), "bytesReceived")).doubleValue());

                requestProcessorBytesSentGauge.addMetric(
                        labelValueList,
                        ((Long) server.getAttribute(mBean.getObjectName(), "bytesSent")).doubleValue());

                requestProcessorProcessingTimeGauge.addMetric(
                        labelValueList,
                        ((Long) server.getAttribute(mBean.getObjectName(), "processingTime")).doubleValue() / 1000.0);

                requestProcessorErrorCounter.addMetric(
                        labelValueList,
                        ((Integer) server.getAttribute(mBean.getObjectName(), "errorCount")).doubleValue());

                requestProcessorRequestCounter.addMetric(
                        labelValueList,
                        ((Integer) server.getAttribute(mBean.getObjectName(), "requestCount")).doubleValue());
            }

            mfs.add(requestProcessorBytesReceivedGauge);
            mfs.add(requestProcessorBytesSentGauge);
            mfs.add(requestProcessorProcessingTimeGauge);
            mfs.add(requestProcessorRequestCounter);
            mfs.add(requestProcessorErrorCounter);
        }
    } catch (Exception e) {
        log.error("Error retrieving metric.", e);
    }
}
 
Example 18
Source File: ManagementUtil.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public static MBeanServerConnection getPlatformMBeanServerDW() {
  if(JMXPrms.useGemfireProxies())
    return new GemfireMBeanServerConnection(ManagementService.getManagementService(CacheHelper.getCache()));
  else  return ManagementFactory.getPlatformMBeanServer();
}
 
Example 19
Source File: StringMonitorDeadlockTest.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
void run() throws Exception {
    final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    final ObjectName observedName = new ObjectName("a:b=c");
    final ObjectName monitorName = new ObjectName("a:type=Monitor");
    mbs.registerMBean(new StringMonitor(), monitorName);
    final StringMonitorMBean monitorProxy =
        JMX.newMBeanProxy(mbs, monitorName, StringMonitorMBean.class);
    final TestMBean observedProxy =
        JMX.newMBeanProxy(mbs, observedName, TestMBean.class);

    final Runnable sensitiveThing = new Runnable() {
        public void run() {
            doSensitiveThing(monitorProxy, observedName);
        }
    };

    final Runnable nothing = new Runnable() {
        public void run() {}
    };

    final Runnable withinGetAttribute =
        (when == When.IN_GET_ATTRIBUTE) ? sensitiveThing : nothing;

    mbs.registerMBean(new Test(withinGetAttribute), observedName);
    monitorProxy.addObservedObject(observedName);
    monitorProxy.setObservedAttribute("Thing");
    monitorProxy.setStringToCompare("old");
    monitorProxy.setGranularityPeriod(10L); // 10 ms
    monitorProxy.setNotifyDiffer(true);
    monitorProxy.start();

    final int initGetCount = observedProxy.getGetCount();
    int getCount = initGetCount;
    for (int i = 0; i < 500; i++) { // 500 * 10 = 5 seconds
        getCount = observedProxy.getGetCount();
        if (getCount != initGetCount)
            break;
        Thread.sleep(10);
    }
    if (getCount <= initGetCount)
        throw new Exception("Test failed: presumable deadlock");
    // This won't show up as a deadlock in CTRL-\ or in
    // ThreadMXBean.findDeadlockedThreads(), because they don't
    // see that thread A is waiting for thread B (B.join()), and
    // thread B is waiting for a lock held by thread A

    // Now we know the monitor has observed the initial value,
    // so if we want to test notify behaviour we can trigger by
    // exceeding the threshold.
    if (when == When.IN_NOTIFY) {
        final AtomicInteger notifCount = new AtomicInteger();
        final NotificationListener listener = new NotificationListener() {
            public void handleNotification(Notification n, Object h) {
                Thread t = new Thread(sensitiveThing);
                t.start();
                try {
                    t.join();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                notifCount.incrementAndGet();
            }
        };
        mbs.addNotificationListener(monitorName, listener, null, null);
        observedProxy.setThing("new");
        for (int i = 0; i < 500 && notifCount.get() == 0; i++)
            Thread.sleep(10);
        if (notifCount.get() == 0)
            throw new Exception("Test failed: presumable deadlock");
    }

}
 
Example 20
Source File: JmxMetricsRegistrar.java    From mongodb-async-driver with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new JmxMetricsRegistrar.
 */
public JmxMetricsRegistrar() {
    super();

    myServer = ManagementFactory.getPlatformMBeanServer();
}