javax.management.JMException Java Examples

The following examples show how to use javax.management.JMException. 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: Server.java    From ironjacamar with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #2
Source File: JmxSupportTest.java    From mongodb-async-driver with Apache License 2.0 6 votes vote down vote up
/**
 * 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"));
}
 
Example #3
Source File: ScanManager.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
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();
    }
}
 
Example #4
Source File: DefaultManagementAgent.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@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);

    }

}
 
Example #5
Source File: JmxRegisterCallback.java    From javasimon with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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);
		}
	}
}
 
Example #6
Source File: DefaultManagementAgent.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
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);

  }

}
 
Example #7
Source File: ClusterFacade.java    From cassandra-reaper with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
  }
}
 
Example #8
Source File: ScanManager.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
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();
    }
}
 
Example #9
Source File: MBeans.java    From javamelody with Apache License 2.0 6 votes vote down vote up
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);
		}
	}
}
 
Example #10
Source File: TaskStateModelFactory.java    From helix with Apache License 2.0 6 votes vote down vote up
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.");
    }
  }
}
 
Example #11
Source File: ScanManager.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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();
    }
}
 
Example #12
Source File: MetricsService.java    From cassandra-reaper with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #13
Source File: ReflectionMbeanTest.java    From simplejmx with ISC License 5 votes vote down vote up
@Test(expected = JMException.class)
public void testBadGet() throws Exception {
	BadGetName obj = new BadGetName();
	try {
		server.register(obj);
		fail("Should not get here");
	} finally {
		server.unregister(obj);
	}
}
 
Example #14
Source File: JmxClient.java    From simplejmx with ISC License 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example #15
Source File: MBeanInfoAssemblerTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #16
Source File: JmxMetricsReporter.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void registerMBean(Object mBean, ObjectName objectName) throws InstanceAlreadyExistsException, JMException {
  // remove previous bean if exists
  if (mBeanServer.isRegistered(objectName)) {
    if (log.isDebugEnabled()) {
      Set<ObjectInstance> objects = mBeanServer.queryMBeans(objectName, null);
      if (log.isDebugEnabled()) {
        log.debug("## removing existing {} bean(s) for {}, current tag={}:", objects.size(), objectName.getCanonicalName(), tag);
      }
      for (ObjectInstance inst : objects) {
        if (log.isDebugEnabled()) {
          log.debug("## - tag={}{}", mBeanServer.getAttribute(inst.getObjectName(), INSTANCE_TAG));
        }
      }
    }
    mBeanServer.unregisterMBean(objectName);
  }
  ObjectInstance objectInstance = mBeanServer.registerMBean(mBean, objectName);
  if (objectInstance != null) {
    // the websphere mbeanserver rewrites the objectname to include
    // cell, node & server info
    // make sure we capture the new objectName for unregistration
    registered.put(objectName, objectInstance.getObjectName());
  } else {
    registered.put(objectName, objectName);
  }
  if (log.isDebugEnabled()) {
    log.debug("## registered {}, tag={}", objectInstance.getObjectName().getCanonicalName(), tag);
  }
}
 
Example #17
Source File: ArtemisMBeanServerGuard.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void handleSetAttribute(MBeanServer proxy, ObjectName objectName, Attribute attribute) throws JMException, IOException {
   String dataType = null;
   MBeanInfo info = proxy.getMBeanInfo(objectName);
   for (MBeanAttributeInfo attr : info.getAttributes()) {
      if (attr.getName().equals(attribute.getName())) {
         dataType = attr.getType();
         break;
      }
   }

   if (dataType == null)
      throw new IllegalStateException("Attribute data type can not be found");

   handleInvoke(objectName, "set" + attribute.getName(), new Object[]{attribute.getValue()}, new String[]{dataType});
}
 
Example #18
Source File: ScanDirAgent.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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();
    }
}
 
Example #19
Source File: ScanDirAgent.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #20
Source File: ScanManager.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public ScanDirConfigMXBean createOtherConfigurationMBean(String name,
        String filename)
    throws JMException {
    final ScanDirConfig profile = new ScanDirConfig(filename);
    final ObjectName profName = makeScanDirConfigName(name);
    final ObjectInstance moi = mbeanServer.registerMBean(profile,profName);
    final ScanDirConfigMXBean proxy =
            JMX.newMXBeanProxy(mbeanServer,profName,
                ScanDirConfigMXBean.class,true);
    configmap.put(moi.getObjectName(),proxy);
    return proxy;
}
 
Example #21
Source File: MBeanClientInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private Object invokeAttribute(PropertyDescriptor pd, MethodInvocation invocation)
		throws JMException, IOException {

	String attributeName = JmxUtils.getAttributeName(pd, this.useStrictCasing);
	MBeanAttributeInfo inf = this.allowedAttributes.get(attributeName);
	// If no attribute is returned, we know that it is not defined in the
	// management interface.
	if (inf == null) {
		throw new InvalidInvocationException(
				"Attribute '" + pd.getName() + "' is not exposed on the management interface");
	}
	if (invocation.getMethod().equals(pd.getReadMethod())) {
		if (inf.isReadable()) {
			return this.serverToUse.getAttribute(this.objectName, attributeName);
		}
		else {
			throw new InvalidInvocationException("Attribute '" + attributeName + "' is not readable");
		}
	}
	else if (invocation.getMethod().equals(pd.getWriteMethod())) {
		if (inf.isWritable()) {
			this.serverToUse.setAttribute(this.objectName, new Attribute(attributeName, invocation.getArguments()[0]));
			return null;
		}
		else {
			throw new InvalidInvocationException("Attribute '" + attributeName + "' is not writable");
		}
	}
	else {
		throw new IllegalStateException(
				"Method [" + invocation.getMethod() + "] is neither a bean property getter nor a setter");
	}
}
 
Example #22
Source File: NodeAdditionNomadChangeProcessor.java    From terracotta-platform with Apache License 2.0 5 votes vote down vote up
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");
  }
}
 
Example #23
Source File: ManagedBus.java    From cxf with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #24
Source File: Server.java    From ironjacamar with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #25
Source File: ReflectionMbeanTest.java    From simplejmx with ISC License 5 votes vote down vote up
@Test(expected = JMException.class)
public void testBadSetNoArg() throws Exception {
	BadSetNoArg obj = new BadSetNoArg();
	try {
		server.register(obj);
	} finally {
		server.unregister(obj);
	}
}
 
Example #26
Source File: JmxClient.java    From simplejmx with ISC License 5 votes vote down vote up
/**
 * Close the client connection to the mbean server.If you want a method that throws then use {@link #closeThrow()}.
 */
@Override
public void close() {
	try {
		closeThrow();
	} catch (JMException e) {
		// ignored
	}
}
 
Example #27
Source File: ScanManager.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public ScanDirConfigMXBean createOtherConfigurationMBean(String name,
        String filename)
    throws JMException {
    final ScanDirConfig profile = new ScanDirConfig(filename);
    final ObjectName profName = makeScanDirConfigName(name);
    final ObjectInstance moi = mbeanServer.registerMBean(profile,profName);
    final ScanDirConfigMXBean proxy =
            JMX.newMXBeanProxy(mbeanServer,profName,
                ScanDirConfigMXBean.class,true);
    configmap.put(moi.getObjectName(),proxy);
    return proxy;
}
 
Example #28
Source File: JmxReporter.java    From common with Apache License 2.0 5 votes vote down vote up
private KafkaMbean addAttribute(KafkaMetric metric) {
  try {
    MetricName metricName = metric.metricName();
    String mBeanName = getMBeanName(metricName);
    if (!this.mbeans.containsKey(mBeanName))
      mbeans.put(mBeanName, new KafkaMbean(mBeanName));
    KafkaMbean mbean = this.mbeans.get(mBeanName);
    mbean.setAttribute(metricName.name() , metric);
    return mbean;
  } catch (JMException e) {
    throw new MetricsException(
        "Error creating mbean attribute for metricName :" + metric.metricName(), e);
  }
}
 
Example #29
Source File: DynamicMBeanProvider.java    From helix with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #30
Source File: StatusController.java    From telekom-workflow-engine with MIT License 5 votes vote down vote up
private void appendMbeanInformation( Map<String, List<MbeanAttributeModel>> mbeans, String selector ) throws Exception{
    Set<ObjectName> foundObjectNames = mbeanServer.queryNames( new ObjectName( selector ), null );

    for( ObjectName objectName : foundObjectNames ){
        MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo( objectName );
        String name = objectName.getKeyProperty( "name" );
        if( name == null || mbeans.containsKey(name) ){
            name = name + ":" + mbeanInfo.getDescription();
        }
        List<MbeanAttributeModel> attributes = new ArrayList<>();
        mbeans.put( name, attributes );

        for( MBeanAttributeInfo attributeInfo : mbeanInfo.getAttributes() ){
            MbeanAttributeModel attribute = new MbeanAttributeModel();
            attribute.setName( attributeInfo.getName() );
            attribute.setDescription( attributeInfo.getDescription() );
            Object attr = null;
            try {
                attr = mbeanServer.getAttribute(objectName, attribute.getName());
            } catch (JMException jme) {
                log.warn("Error while getting attribute \"" + attribute.getName() + "\", ignoring, " + jme.getMessage());
            }
            attribute.setValue( attr );
            attributes.add( attribute );
        }
    }
}