Register a MBean to JMX server
163857
public static void register(String name, Object instance) {
    try {
      Class<Object> mbeanInterface = guessMBeanInterface(instance);
      ManagementFactory.getPlatformMBeanServer().registerMBean(new StandardMBean(instance, mbeanInterface), new ObjectName(name));

    } catch (MalformedObjectNameException | NotCompliantMBeanException | InstanceAlreadyExistsException | MBeanRegistrationException e) {
      throw new IllegalStateException("Can not register MBean [" + name + "]", e);
    }
  }
1105951
private JMXConnector getMBeanServerConnection(String controllerHost, int controllerPort, HashMap<String, Object> environment) throws MalformedURLException, IOException {
        JMXServiceURL serviceURL = new JMXServiceURL("REST", controllerHost, controllerPort, "/IBMJMXConnectorREST");
        return new ClientProvider().newJMXConnector(serviceURL, environment);
    }
403272
public static void registerStandardMXBeans(Registry registry) {
    for (MemoryPoolMXBean mbean : ManagementFactory.getPlatformMXBeans(MemoryPoolMXBean.class)) {
      registry.register(new MemoryPoolMeter(registry, mbean));
    }

    for (BufferPoolMXBean mbean : ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class)) {
      registry.register(new BufferPoolMeter(registry, mbean));
    }
  }
784304
private static void initJmxConn() throws IOException {
        if (jmxUrl != null) {
            JMXServiceURL url = new JMXServiceURL(jmxUrl);
            Map<String, String[]> env = null;
            if (jmxUsername != null) {
                env = Maps.newHashMap();
                String[] credentials = new String[]{jmxUsername, jmxPassword};
                env.put(JMXConnector.CREDENTIALS, credentials);
            }
            JMXConnector jmxc = JMXConnectorFactory.connect(url, env);
            conn = jmxc.getMBeanServerConnection();
        }
    }
867819
private void registerQueryMBeans(ComponentRegistry cr, Configuration cfg, SearchIntegrator searchIntegrator) {
      AdvancedCache<?, ?> cache = cr.getComponent(Cache.class).getAdvancedCache();
      // Resolve MBean server instance
      GlobalJmxStatisticsConfiguration jmxConfig = cr.getGlobalComponentRegistry().getGlobalConfiguration().globalJmxStatistics();
      if (!jmxConfig.enabled())
         return;
      if (mbeanServer == null) {
         mbeanServer = JmxUtil.lookupMBeanServer(jmxConfig.mbeanServerLookup(), jmxConfig.properties());
      }

      // Resolve jmx domain to use for query MBeans
      String queryGroupName = getQueryGroupName(jmxConfig.cacheManagerName(), cache.getName());
      String jmxDomain = JmxUtil.buildJmxDomain(jmxConfig.domain(), mbeanServer, queryGroupName);

      // Register query statistics MBean, but only enable it if Infinispan config says so
      try {
         ObjectName statsObjName = new ObjectName(jmxDomain + ":" + queryGroupName + ",component=Statistics");

         InfinispanQueryStatisticsInfo stats = new InfinispanQueryStatisticsInfo(searchIntegrator, statsObjName);
         stats.setStatisticsEnabled(cfg.jmxStatistics().enabled());

         JmxUtil.registerMBean(stats, statsObjName, mbeanServer);

         cr.registerComponent(stats, InfinispanQueryStatisticsInfo.class);
      } catch (Exception e) {
         throw new CacheException("Unable to register query statistics MBean", e);
      }

      // Register mass indexer MBean, picking metadata from repo
      ManageableComponentMetadata massIndexerCompMetadata = cr.getGlobalComponentRegistry().getComponentMetadataRepo()
            .findComponentMetadata(MassIndexer.class)
            .toManageableComponentMetadata();
      try {
         KeyTransformationHandler keyTransformationHandler = ComponentRegistryUtils.getKeyTransformationHandler(cache);
         TimeService timeService = ComponentRegistryUtils.getTimeService(cache);
         // TODO: MassIndexer should be some kind of query cache component?
         DistributedExecutorMassIndexer massIndexer = new DistributedExecutorMassIndexer(cache, searchIntegrator, keyTransformationHandler, timeService);
         ResourceDMBean mbean = new ResourceDMBean(massIndexer, massIndexerCompMetadata);
         ObjectName massIndexerObjName = new ObjectName(jmxDomain + ":"
               + queryGroupName + ",component=" + massIndexerCompMetadata.getJmxObjectName());
         JmxUtil.registerMBean(mbean, massIndexerObjName, mbeanServer);
      } catch (Exception e) {
         throw new CacheException("Unable to create MassIndexer MBean", e);
      }
   }
971711
private void registerJsonProxyBean(DefaultListableBeanFactory defaultListableBeanFactory, String className, String path) {
		BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder
				.rootBeanDefinition(JsonProxyFactoryBean.class)
				.addPropertyValue("serviceUrl", appendBasePath(path))
				.addPropertyValue("serviceInterface", className);
		
		if (objectMapper != null) {
			beanDefinitionBuilder.addPropertyValue("objectMapper", objectMapper);
		}
		
		if (contentType != null) {
			beanDefinitionBuilder.addPropertyValue("contentType", contentType);
		}
		
		defaultListableBeanFactory.registerBeanDefinition(className + "-clientProxy", beanDefinitionBuilder.getBeanDefinition());
	}
1186863
private ObjectName registerMXBean(MBeanServer pServer, Object pObject, Class pManagementInterface, String pName) throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanRegistrationException {
        ObjectName objectName = new ObjectName(pName);
        final StandardMBean mxBean = new StandardMBean(pObject, pManagementInterface, true /* MXBean */);
        pServer.registerMBean(mxBean, objectName);
        System.out.println("Registered MXBean " + objectName);
        return objectName;
    }
515672
private void rebuildJmx()
    {
        m_mbeanServer = ManagementFactory.getPlatformMBeanServer();

        try
        {
            buildMBeanInfo();

            //
            //  Remove and reinstall from the MBean registry if it already exists.  Also
            //  remove previous instances.
            //
            ObjectName newName = getJMXName();

            if( m_mbeanServer.isRegistered(newName) )
            {
                log.debug("Removing already registered bean {}", newName);
                m_mbeanServer.unregisterMBean(newName);
            }

            if( m_jmxName != null && !newName.equals(m_jmxName) && m_mbeanServer.isRegistered(m_jmxName) )
            {
                log.debug("Removing the old bean {}", m_jmxName);
                m_mbeanServer.unregisterMBean(m_jmxName);
            }

            m_jmxName = getJMXName();

            if( m_beanInfo != null )
            {
                m_mbeanServer.registerMBean( this, m_jmxName );

                log.debug("Registered new JMX bean '{}'", m_jmxName);
            }
        }
        catch (InstanceAlreadyExistsException e)
        {
            log.debug("JMX bean '{}' already registered, continuing...");
        }
        catch (Exception e)
        {
            throw new ConfigurationException(e);
        }
    }
1222434
private MBeanServer lookupJolokiaMBeanServer() {
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();
        try {
            return server.isRegistered(JOLOKIA_MBEAN_SERVER_ONAME) ?
                    (MBeanServer) server.getAttribute(JOLOKIA_MBEAN_SERVER_ONAME, "JolokiaMBeanServer") :
                    null;
        } catch (JMException e) {
            throw new IllegalStateException("Internal: Cannot get Jolokia MBeanServer via JMX lookup: " + e, e);
        }
    }
734895
public void registerMBeans(Collection<ResourceDMBean> resourceDMBeans) throws CacheException {
      try {
         for (ResourceDMBean resource : resourceDMBeans)
            JmxUtil.registerMBean(resource, getObjectName(resource), mBeanServer);
      }
      catch (Exception e) {
         throw new CacheException("Failure while registering mbeans", e);
      }
   }
321033
public static void unregister(String name) {
    try {
      ManagementFactory.getPlatformMBeanServer().unregisterMBean(new ObjectName(name));
    } catch (Exception e) {
      LoggerFactory.getLogger(Jmx.class).warn("Can not unregister MBean [{}]", name, e);
    }
  }
1225575
public static void populateMBeanServer() {
		if(populated)
			return;
		
		synchronized (lock) {
			populated = true;
			
			if (serverMonitor == null) {
				logger.info("Creating and registering the ServerMonitor MXBean");
				try { serverMonitor = new ServerMonitor(true); } catch(Exception ex) {
					logger.warn("Can't publish ServerMonitor MXBean.", ex);
					logger.warn("Nonpublic instance of the ServerMonitor MXBean will be used in current session.");
					serverMonitor = new ServerMonitor(false);
				}
			}
			if (storageManager == null) {
				logger.info("Creating and registering the StorageManager MXBean");
				try{ storageManager = new StorageManager(true); } catch(Exception ex) {
					logger.warn("Can't publish StorageManager MXBean.", ex);
					logger.warn("Nonpublic instance of the StorageManager MXBean will be used in current session.");
					storageManager = new StorageManager(false);
				}
			}
		}
	}
180185
public synchronized ObjectName register(PublishAllBeanWrapper wrapper) throws JMException {
		ReflectionMbean mbean;
		try {
			mbean = new ReflectionMbean(wrapper);
		} catch (Exception e) {
			throw createJmException("Could not build mbean object for publish-all bean: " + wrapper.getTarget(), e);
		}
		ObjectName objectName = ObjectNameUtil.makeObjectName(wrapper.getJmxResourceInfo());
		doRegister(objectName, mbean);
		return objectName;
	}
1154182
@Override
    /** {@inheritDoc} */
    public void addMBeanServers(Set<MBeanServerConnection> servers) {
        try {
            Class locatorClass = Class.forName("org.jboss.mx.util.MBeanServerLocator");
            Method method = locatorClass.getMethod("locateJBoss");
            servers.add((MBeanServer) method.invoke(null));
        } catch (ClassNotFoundException e) { /* Ok, its *not* JBoss 4,5 or 6, continue with search ... */ } catch (NoSuchMethodException e) {
        } catch (IllegalAccessException e) {
        } catch (InvocationTargetException e) {
        }
    }
290082
private static void registerServer(Server server, Database db) {

        if (!serverMap.containsKey(server)) {
            serverMap.put(server, new HashSet());
        }

        HashSet databases = (HashSet) serverMap.get(server);

        databases.add(db);
    }
236604
public void register() {
		try {
			objectName = consObjectName(domain, type, keysString);
			MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
			mbs.registerMBean(this, objectName);
		} catch (Exception e) {
			objectName = null;
			throw new RuntimeException(e);
		}
	}
447623
public static void registerMBean(String packageName, String type, String name, Object mbean) {
		try {
			String pkg = defaultString(packageName, mbean.getClass().getPackage().getName());
			MBeanServer server = ManagementFactory.getPlatformMBeanServer();
			ObjectName on = new ObjectName(pkg + ":type=" + type + ",name=" + name);
			if (server.isRegistered(on)) {
				Say.debug("MBean with type {type} and name {name} for {package} has already been defined, ignoring", type, name, pkg);
			}
			else {
				server.registerMBean(mbean, on);
			}
		}
		catch (Exception ex) {
			Say.warn("MBean could not be registered", ex);
		}
	}