下面列出了怎么用javax.management.JMException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* List dropped messages metrics
*
* @param node the node to get the metrics from
* @return a list of dropped messages metrics objects
* @throws ReaperException any runtime exception we can catch in the process
*/
public List<DroppedMessages> getDroppedMessages(Node node) throws ReaperException {
try {
String nodeDc = getDatacenter(node);
if (nodeIsAccessibleThroughJmx(nodeDc, node.getHostname())) {
MetricsProxy proxy = MetricsProxy.create(connect(node));
return convertToDroppedMessages(MetricsProxy.convertToGenericMetrics(proxy.collectDroppedMessages(), node));
} else {
return convertToDroppedMessages(((IDistributedStorage)context.storage)
.getMetrics(
node.getClusterName(),
Optional.of(node.getHostname()),
"org.apache.cassandra.metrics",
"DroppedMessage",
DateTime.now().minusMinutes(1).getMillis()));
}
} catch (JMException | InterruptedException | IOException e) {
LOG.error("Failed collecting tpstats for host {}", node, e);
throw new ReaperException(e);
}
}
private static void initJRockitMBeansIfNeeded() {
// si jrockit, on initialise les MBeans spécifiques jrockit lors de la première demande
if (System.getProperty("java.vendor").contains("BEA")) {
try {
// initialisation des MBeans jrockit comme indiqué dans http://blogs.oracle.com/hirt/jrockit/
try {
getPlatformMBeanServer().getMBeanInfo(
new ObjectName("bea.jrockit.management:type=JRockitConsole"));
} catch (final InstanceNotFoundException e1) {
getPlatformMBeanServer().createMBean("bea.jrockit.management.JRockitConsole",
null);
LOG.debug("JRockit MBeans initialized");
}
} catch (final JMException e) {
throw new IllegalStateException(e);
}
}
}
private synchronized void registerSimonBean(Object simonBean, String name) {
if (simonBean != null && name != null) {
try {
ObjectName objectName = new ObjectName(name);
if (mBeanServer.isRegistered(objectName)) {
mBeanServer.unregisterMBean(objectName);
} else {
registeredNames.add(name);
}
mBeanServer.registerMBean(simonBean, objectName);
onManagerMessage("Simon registered under the name: " + objectName);
} catch (JMException e) {
onManagerWarning("JMX registration failed for: " + name, e);
registeredNames.remove(name);
}
}
}
@Override
public void register(Object obj, ObjectName name, boolean forceRegistration) throws JMException {
try {
Object mbean = assembler.assemble(obj, name);
if (mbean != null) {
// and register the mbean
registerMBeanWithServer(mbean, name, forceRegistration);
} else {
registerMBeanWithServer(obj, name, forceRegistration);
}
} catch (NotCompliantMBeanException e) {
LOGGER.error("Mbean {} is not compliant MBean.", name, e);
registerMBeanWithServer(obj, name, forceRegistration);
}
}
private void applyConfiguration(ScanManagerConfig bean)
throws IOException, JMException {
if (bean == null) return;
if (!sequencer.tryAcquire()) {
throw new IllegalStateException("Can't acquire lock");
}
try {
unregisterScanners();
final DirectoryScannerConfig[] scans = bean.getScanList();
if (scans == null) return;
for (DirectoryScannerConfig scan : scans) {
addDirectoryScanner(scan);
}
log.setConfig(bean.getInitialResultLogConfig());
} finally {
sequencer.release();
}
}
public void register(Object obj, ObjectName name, boolean forceRegistration) throws JMException {
try {
Object mbean = assembler.assemble(obj, name);
if (mbean != null)
// and register the mbean
registerMBeanWithServer(mbean, name, forceRegistration);
else
registerMBeanWithServer(obj, name, forceRegistration);
} catch (NotCompliantMBeanException e) {
LOG.error("Mbean " + name + " is not compliant MBean.", e);
registerMBeanWithServer(obj, name, forceRegistration);
}
}
/**
* Get MBean attribute
* @param name The bean name
* @param attrName The attribute name
* @return The data
* @exception JMException Thrown if an error occurs
*/
public static String getMBeanAttribute(String name, String attrName) throws JMException
{
MBeanServer server = getMBeanServer();
ObjectName objName = new ObjectName(name);
String value = null;
try
{
Object attr = server.getAttribute(objName, attrName);
if (attr != null)
value = attr.toString();
}
catch (JMException e)
{
value = e.getMessage();
}
return value;
}
private void applyConfiguration(ScanManagerConfig bean)
throws IOException, JMException {
if (bean == null) return;
if (!sequencer.tryAcquire()) {
throw new IllegalStateException("Can't acquire lock");
}
try {
unregisterScanners();
final DirectoryScannerConfig[] scans = bean.getScanList();
if (scans == null) return;
for (DirectoryScannerConfig scan : scans) {
addDirectoryScanner(scan);
}
log.setConfig(bean.getInitialResultLogConfig());
} finally {
sequencer.release();
}
}
private void applyConfiguration(ScanManagerConfig bean)
throws IOException, JMException {
if (bean == null) return;
if (!sequencer.tryAcquire()) {
throw new IllegalStateException("Can't acquire lock");
}
try {
unregisterScanners();
final DirectoryScannerConfig[] scans = bean.getScanList();
if (scans == null) return;
for (DirectoryScannerConfig scan : scans) {
addDirectoryScanner(scan);
}
log.setConfig(bean.getInitialResultLogConfig());
} finally {
sequencer.release();
}
}
public TaskStateModelFactory(HelixManager manager, Map<String, TaskFactory> taskFactoryRegistry,
ScheduledExecutorService taskExecutor) {
_manager = manager;
_taskFactoryRegistry = taskFactoryRegistry;
_taskExecutor = taskExecutor;
_timerTaskExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "TaskStateModelFactory-timeTask_thread");
}
});
if (_taskExecutor instanceof ThreadPoolExecutor) {
try {
_monitor = new ThreadPoolExecutorMonitor(TaskConstants.STATE_MODEL_NAME,
(ThreadPoolExecutor) _taskExecutor);
} catch (JMException e) {
LOG.warn("Error in creating ThreadPoolExecutorMonitor for TaskStateModelFactory.");
}
}
}
/**
* Test method for {@link JmxSupport#unregister(String, String, int)}.
*
* @throws JMException
* On a test failure.
*/
@Test
public void testUnregisterServerWhenNotRegistered() throws JMException {
final MBeanServer mockServer = createMock(MBeanServer.class);
final Capture<ObjectName> captureName = new Capture<ObjectName>();
expect(mockServer.isRegistered(capture(captureName))).andReturn(false);
replay(mockServer);
final JmxSupport support = new JmxSupport(mockServer);
support.unregister("subType", "foo", 1234);
verify(mockServer);
final ObjectName name = captureName.getValue();
assertThat(name, notNullValue());
assertThat(name.getDomain(), is(JmxSupport.DOMAIN_NAME));
assertThat(name.getKeyProperty("type"), is("metrics"));
assertThat(name.getKeyProperty("subType"), is("subType"));
assertThat(name.getKeyProperty("serverName"), is("foo"));
assertThat(name.getKeyProperty("index"), is("1234"));
}
void grabAndStoreCompactionStats() throws JsonProcessingException, JMException, ReaperException {
Preconditions.checkState(
context.config.isInSidecarMode(),
"grabAndStoreCompactionStats() can only be called in sidecar");
Node node = Node.builder().withHostname(context.getLocalNodeAddress()).build();
CompactionStats compactionStats = ClusterFacade.create(context).listCompactionStatsDirect(node);
((IDistributedStorage) context.storage)
.storeOperations(
localClusterName,
OpType.OP_COMPACTION,
context.getLocalNodeAddress(),
objectMapper.writeValueAsString(compactionStats));
LOG.debug("Grabbing and storing compaction stats for {}", context.getLocalNodeAddress());
}
/**
* Register all JMX MBeans
*/
private void registerMBeans() throws JMException {
String baseObjectName = "org.apache.james:type=component,component=mailetcontainer,name=processor,";
String[] processorNames = mList.getProcessorStates();
for (String processorName : processorNames) {
registerProcessorMBean(baseObjectName, processorName);
}
}
/**
*
* @return Should return the total direct memory available, result seem off
* see post http://jmonkeyengine.org/forum/topic/monitor-direct-memory-usage-in-your-app/#post-205999
*/
public static long getDirectMemoryTotalCapacity() {
try {
Long value = (Long)mbeans.getAttribute(directPool, "TotalCapacity");
return value == null ? -1 : value;
} catch (JMException ex) {
Logger.getLogger(MemoryUtils.class.getName()).log(Level.SEVERE, "Error retrieving ‘TotalCapacity’", ex);
return -1;
}
}
/**
* The agent's main: {@link #init registers} a {@link ScanManagerMXBean},
* {@link #waitForClose waits} until its state is {@link
* ScanManagerMXBean.ScanState#CLOSED CLOSED}, {@link #cleanup cleanup}
* and exits.
* @param args the command line arguments - ignored
* @throws java.io.IOException A communication problem occurred.
* @throws javax.management.JMException A JMX problem occurred.
*/
public static void main(String[] args)
throws IOException, JMException {
System.out.println("Initializing ScanManager...");
final ScanDirAgent agent = new ScanDirAgent();
agent.init();
try {
System.out.println("Waiting for ScanManager to close...");
agent.waitForClose();
} finally {
System.out.println("Cleaning up...");
agent.cleanup();
}
}
static long getUsedBufferMemory() {
if (NIO_BUFFER_POOLS.isEmpty()) {
return -1;
}
long result = 0;
try {
for (final ObjectName objectName : NIO_BUFFER_POOLS) {
// adds direct and mapped buffers
result += (Long) getAttribute(objectName, "MemoryUsed");
}
} catch (final JMException e) {
throw new IllegalStateException(e);
}
return result;
}
/**
* Cleanup after close: unregister the ScanManagerMXBean singleton.
* @throws java.io.IOException Cleanup failed for communication-related reasons.
* @throws javax.management.JMException Cleanup failed for JMX-related reasons.
*/
public void cleanup() throws IOException, JMException {
try {
((NotificationEmitter)proxy).
removeNotificationListener(listener,null,null);
} finally {
ManagementFactory.getPlatformMBeanServer().
unregisterMBean(ScanManager.SCAN_MANAGER_NAME);
}
}
/**
* Register an mbean with the platform mbean server.
*/
private void jmxRegister(final StandardMBean standardMBean,
final ObjectName beanName) throws JMException
{
// Already registered? Can happen if we don't have permission
// to unregister the MBeans.
if (mbeanServer.isRegistered(beanName))
return;
try {
AccessController
.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws JMException {
mbeanServer.registerMBean(standardMBean, beanName);
return null;
}
});
} catch (PrivilegedActionException pae) {
throw (JMException) pae.getException();
} catch (SecurityException se) {
// If we can't register the MBean then so be it.
// The application can later enabled the MBeans
// by using com.pivotal.gemfirexd.internal.mbeans.Management
}
}
/**
* The agent's main: {@link #init registers} a {@link ScanManagerMXBean},
* {@link #waitForClose waits} until its state is {@link
* ScanManagerMXBean.ScanState#CLOSED CLOSED}, {@link #cleanup cleanup}
* and exits.
* @param args the command line arguments - ignored
* @throws java.io.IOException A communication problem occurred.
* @throws javax.management.JMException A JMX problem occurred.
*/
public static void main(String[] args)
throws IOException, JMException {
System.out.println("Initializing ScanManager...");
final ScanDirAgent agent = new ScanDirAgent();
agent.init();
try {
System.out.println("Waiting for ScanManager to close...");
agent.waitForClose();
} finally {
System.out.println("Cleaning up...");
agent.cleanup();
}
}
/**
* Build an adapted MBean for the given bean instance, if possible.
* <p>The default implementation builds a JMX 1.2 StandardMBean
* for the target's MBean/MXBean interface in case of an AOP proxy,
* delegating the interface's management operations to the proxy.
* @param bean the original bean instance
* @return the adapted MBean, or {@code null} if not possible
*/
@SuppressWarnings("unchecked")
@Nullable
protected DynamicMBean adaptMBeanIfPossible(Object bean) throws JMException {
Class<?> targetClass = AopUtils.getTargetClass(bean);
if (targetClass != bean.getClass()) {
Class<?> ifc = JmxUtils.getMXBeanInterface(targetClass);
if (ifc != null) {
if (!ifc.isInstance(bean)) {
throw new NotCompliantMBeanException("Managed bean [" + bean +
"] has a target class with an MXBean interface but does not expose it in the proxy");
}
return new StandardMBean(bean, ((Class<Object>) ifc), true);
}
else {
ifc = JmxUtils.getMBeanInterface(targetClass);
if (ifc != null) {
if (!ifc.isInstance(bean)) {
throw new NotCompliantMBeanException("Managed bean [" + bean +
"] has a target class with an MBean interface but does not expose it in the proxy");
}
return new StandardMBean(bean, ((Class<Object>) ifc));
}
}
}
return null;
}
public static void main(String[] args) throws IOException, JMException {
//Just for benchmark
Spider thread = OOSpider.create(Site.me().setSleepTime(0), new PageModelPipeline() {
@Override
public void process(Object o, Task task) {
}
}, Kr36NewsModel.class).thread(20).addUrl("http://www.36kr.com/");
thread.start();
SpiderMonitor spiderMonitor = SpiderMonitor.instance();
spiderMonitor.register(thread);
}
/**
* Unregister an mbean from the JMX plaform server
* but leave it registered to this service. This
* is so that if jmx is reenabled we can reestablish
* all vaid mbeans (that are still registered with this service).
* @param mbeanName
*/
private void jmxUnregister(final ObjectName mbeanName) {
if (!mbeanServer.isRegistered(mbeanName))
return;
try {
AccessController
.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws JMException {
mbeanServer.unregisterMBean(mbeanName);
return null;
}
});
} catch (PrivilegedActionException pae) {
// TODO - this is called on shutdown where
// we don't really care about errors.
// JMException jme = (JMException) pae.getException();
//if (!(jme instanceof InstanceNotFoundException))
// throw StandardException.plainWrapException(jme);
} catch (SecurityException se) {
// Can't unregister the MBean we registered due to permission
// problems, oh-well just leave it there. We are fail-safe
// if we attempt to re-register it.
}
}
/**
* Get MBean data
* @param name The bean name
* @return The data
* @exception JMException Thrown if an error occurs
*/
public static MBeanData getMBeanData(String name) throws JMException
{
MBeanServer server = getMBeanServer();
ObjectName objName = new ObjectName(name);
MBeanInfo info = server.getMBeanInfo(objName);
return new MBeanData(objName, info);
}
/**
* Get MBean attribute object
* @param name The bean name
* @param attrName The attribute name
* @return The data
* @exception JMException Thrown if an error occurs
*/
public static Object getMBeanAttributeObject(String name, String attrName) throws JMException
{
MBeanServer server = getMBeanServer();
ObjectName objName = new ObjectName(name);
return server.getAttribute(objName, attrName);
}
@Test
public void testReadAttributeInfoHappyPath() throws JMException {
ModelMBeanInfo beanInfo = mbeanInfoAssembler.getMBeanInfo(testMbean, null, "someName");
assertNotNull(beanInfo);
assertEquals("test description", beanInfo.getDescription());
MBeanAttributeInfo[] testAttributes = beanInfo.getAttributes();
assertNotNull(testAttributes);
assertEquals(2, testAttributes.length);
int counter = 0;
for (MBeanAttributeInfo info : testAttributes) {
if (info.getName().equals("TestAttributeBoolean")) {
counter++;
assertEquals("test attribute Boolean description", info.getDescription());
assertEquals("java.lang.Boolean", info.getType());
assertTrue(info.isReadable());
assertFalse(info.isWritable());
} else if (info.getName().equals("TestAttributeString")) {
counter++;
assertEquals("test attribute String description", info.getDescription());
assertEquals("java.lang.String", info.getType());
assertTrue(info.isReadable());
assertFalse(info.isWritable());
}
}
assertEquals(2, counter);
// check the single operation
assertNotNull(beanInfo.getOperations());
assertEquals(3, beanInfo.getOperations().length);
}
/**
* Initialize the application by registering a ScanManagerMXBean in
* the platform MBeanServer
* @throws java.io.IOException Registration failed for communication-related reasons.
* @throws javax.management.JMException Registration failed for JMX-related reasons.
*/
public void init() throws IOException, JMException {
// Registers the ScanManagerMXBean singleton in the
// platform MBeanServer
//
proxy = ScanManager.register();
// Registers a NotificationListener with the ScanManagerMXBean in
// order to receive state changed notifications.
//
((NotificationEmitter)proxy).addNotificationListener(listener,null,null);
}
private void checkMBeanOperation() {
boolean canCall;
try {
canCall = Stream
.of(mbeanServer.getMBeanInfo(TOPOLOGY_MBEAN).getOperations())
.anyMatch(attr -> PLATFORM_MBEAN_OPERATION_NAME.equals(attr.getName()));
} catch (JMException e) {
LOGGER.error("MBeanServer::getMBeanInfo resulted in:", e);
canCall = false;
}
if (!canCall) {
throw new IllegalStateException("Unable to invoke MBean operation to attach a node");
}
}
public ObjectName getObjectName() throws JMException {
final StringBuilder buffer = new StringBuilder(ManagementConstants.DEFAULT_DOMAIN_NAME).append(':')
.append(ManagementConstants.BUS_ID_PROP).append('=').append(bus.getId()).append(',')
.append(ManagementConstants.TYPE_PROP).append('=').append(TYPE_VALUE).append(',');
// Added the instance id to make the ObjectName unique
String instanceId = (String)bus.getProperties().get(INSTANCE_ID);
if (StringUtils.isEmpty(instanceId)) {
instanceId = Integer.toString(bus.hashCode());
}
buffer.append(ManagementConstants.INSTANCE_ID_PROP).append('=').append(instanceId);
return new ObjectName(buffer.toString());
}
/**
* Return a set of the various bean ObjectName objects associated with the Jmx server.
*/
public Set<ObjectName> getBeanNames(String domain) throws JMException {
checkClientConnected();
try {
return mbeanConn.queryNames(ObjectName.getInstance(domain + ":*"), null);
} catch (IOException e) {
throw createJmException("Problems querying for jmx bean names: " + e, e);
}
}
/**
* Instantiates a new Dynamic MBean provider.
* @param dynamicMetrics Dynamic Metrics that are exposed by this provider
* @param description the MBean description
* @param objectName the proposed MBean ObjectName
*/
protected synchronized boolean doRegister(Collection<DynamicMetric<?, ?>> dynamicMetrics,
String description, ObjectName objectName) throws JMException {
if (_objectName != null) {
_logger.debug("Mbean {} has already been registered. Ignore register request.",
objectName.getCanonicalName());
return false;
}
updateAttributesInfo(dynamicMetrics, description);
_objectName = MBeanRegistrar.register(this, objectName);
return true;
}