Example usage for org.springframework.jmx.support JmxUtils locateMBeanServer

List of usage examples for org.springframework.jmx.support JmxUtils locateMBeanServer

Introduction

In this page you can find the example usage for org.springframework.jmx.support JmxUtils locateMBeanServer.

Prototype

public static MBeanServer locateMBeanServer() throws MBeanServerNotFoundException 

Source Link

Document

Attempt to find a locally running MBeanServer .

Usage

From source file:net.sourceforge.vulcan.spring.mbean.MbeanServerLocator.java

@Override
public void afterPropertiesSet() throws NamingException {
    try {//from  w  w  w.  j a va2s.c o m
        mbeanServer = JmxUtils.locateMBeanServer();
    } catch (MBeanServerNotFoundException e) {
        super.afterPropertiesSet();
    }
}

From source file:com.brienwheeler.lib.jmx.MBeanRegistrationSupport.java

public static void registerMBean(Object mbean) {
    try {/*from   w w  w  .  j a  v a  2 s.c o  m*/
        ObjectNamingStrategy namingStrategy = new IdentityNamingStrategy();
        ObjectName objectName = namingStrategy.getObjectName(mbean, null);

        MBeanRegistrationSupport registrar = new MBeanRegistrationSupport();
        registrar.setServer(JmxUtils.locateMBeanServer());

        // if item qualifies as MBean, export it directly
        if (JmxUtils.isMBean(mbean.getClass())) {
            registrar.doRegister(mbean, objectName);
            return;
        }

        // assemble MBean info (from annotations by default)
        ModelMBean modelMBean = new RequiredModelMBean();
        modelMBean.setManagedResource(mbean, MR_TYPE_OBJECT_REFERENCE);
        MBeanInfoAssembler mBeanInfoAssembler = new MetadataMBeanInfoAssembler(
                new AnnotationJmxAttributeSource());
        modelMBean.setModelMBeanInfo(mBeanInfoAssembler.getMBeanInfo(mbean, objectName.getCanonicalName()));
        registrar.doRegister(modelMBean, objectName);
    } catch (Exception e) {
        throw new JmxRegisterException("error registering MBean", e);
    }
}

From source file:com.mtgi.analytics.aop.config.v11.PersisterChainConfigurationTest.java

@Test
public void testXmlPersisterConfiguration() throws Exception {
    assertNotNull("custom tracking manager configured", multiTracking);
    assertEquals("application name set", "testApp", multiTracking.getApplication());
    assertEquals("correct persister type provided", ChainingEventPersisterImpl.class,
            multiTracking.getPersister().getClass());

    ChainingEventPersisterImpl persister = (ChainingEventPersisterImpl) multiTracking.getPersister();
    BehaviorEventPersister[] delegates = persister.getDelegates().toArray(new BehaviorEventPersister[0]);
    assertEquals("all delegates registered", 3, delegates.length);
    assertEquals("first delegate has correct type", XmlBehaviorEventPersisterImpl.class,
            delegates[0].getClass());//from   ww w  .ja  v  a 2  s  .  co  m
    assertEquals("second delegate has correct type", StatisticsMBeanEventPersisterImpl.class,
            delegates[1].getClass());
    assertSame("third delegate is reference to top-level bean", customPersister, delegates[2]);

    //verify that MBeans have been registered
    MBeanServer server = JmxUtils.locateMBeanServer();
    assertNotNull("manager mbean found", server.getMBeanInfo(
            new ObjectName("testApp:package=com.mtgi.analytics,group=multiTracking,name=BeetManager")));
}

From source file:com.mtgi.analytics.jmx.StatisticsMBeanEventPersisterTest.java

@Test
public void testMbeanRegistration()
        throws FailingHttpStatusCodeException, IOException, SQLException, JMException, InterruptedException {
    ObjectName[] all = {/* www  . ja va  2 s.c o  m*/
            ObjectName.getInstance("testApp:type=http-request-monitor,name=/testApp/test/invoke.do"),
            ObjectName.getInstance("testApp:type=http-request-monitor,name=/testApp/test/invoke.do,"
                    + "nested=method_com.mtgi.analytics.jmx.StatisticsMBeanEventPersisterTest$Service.save"),
            ObjectName.getInstance("testApp:type=http-request-monitor,name=/testApp/test/invoke.do,"
                    + "nested=method_com.mtgi.analytics.jmx.StatisticsMBeanEventPersisterTest$Service.save,"
                    + "nested[2]=jdbc_executeBatch") };

    MBeanServer jmx = JmxUtils.locateMBeanServer();
    for (ObjectName on : all)
        assertFalse("statistics mbean " + on + " is not yet registered", jmx.isRegistered(on));

    assertEquals("no data in test db yet", 0, countRecords());
    webClient.getPage(baseUrl + "/testApp/test/invoke.do?id=1&value=hello");
    assertEquals("test service invoked", 1, countRecords());

    //verify that we receive updated statistics for each of our monitored events
    for (ObjectName on : all)
        waitForCount(on, 1);

    //post again, and verify that the now-registered mbeans are updated.
    webClient.getPage(baseUrl + "/testApp/test/invoke.do?id=2&value=world");
    assertEquals("test service invoked", 2, countRecords());
    for (ObjectName on : all)
        waitForCount(on, 2);
}

From source file:com.brienwheeler.lib.jmx.logging.Log4jMBeanExporter.java

@SuppressWarnings("unchecked")
private synchronized void shutdown() {
    shutdown = true;/*w  w  w  . ja v  a  2  s .  co m*/
    killDelayedThread();

    MBeanServer server = JmxUtils.locateMBeanServer();
    HierarchyDynamicMBean hdm = hierarchyDynamicMBean.get();
    for (ObjectName registeredName : registeredNames) {
        try {
            server.unregisterMBean(registeredName);

            // The AbstractDynamicMBean base class of the HierarchyDynamicMBean tracks these names too
            // and will later try to unregister them and throw warning log messages unless we violate its
            // privacy and clean out its internal bookkeeping
            Field fld = ReflectionUtils.findField(hdm.getClass(), "mbeanList", Vector.class);
            fld.setAccessible(true);
            Vector<ObjectName> mbeanList = (Vector<ObjectName>) ReflectionUtils.getField(fld, hdm);
            mbeanList.remove(registeredName);
        } catch (Exception e) {
            log.error("Error unregistering " + registeredName.getCanonicalName(), e);
        }
    }
    registeredNames.clear();

    if (registeredHierarchy) {
        try {
            ObjectName mbo = new ObjectName(LOG4J_HIERARCHY_DEFAULT);
            server.unregisterMBean(mbo);
        } catch (Exception e) {
            log.error("Error unregistering Log4j MBean Hierarchy", e);
        }
        registeredHierarchy = false;
    }
}

From source file:com.mtgi.analytics.aop.config.v11.XmlPersisterConfigurationTest.java

@Test
public void testXmlPersisterConfiguration() throws Exception {
    assertNotNull("custom tracking manager configured", xmlTracking);
    assertEquals("application name set", "testApp", xmlTracking.getApplication());
    assertEquals("correct persister type provided", XmlBehaviorEventPersisterImpl.class,
            xmlTracking.getPersister().getClass());

    XmlBehaviorEventPersisterImpl persister = (XmlBehaviorEventPersisterImpl) xmlTracking.getPersister();
    assertFalse("default setting overridden", persister.isBinary());
    assertFalse("default setting overridden", persister.isCompress());

    File location = new File(persister.getFile());
    assertTrue("custom file name [" + persister.getFile() + "]", location.getName().startsWith("xml-tracking"));
    assertEquals("custom XML attributes can be post-processed by property resolver",
            new File(System.getProperty("java.io.tmpdir")).getCanonicalPath(),
            location.getParentFile().getCanonicalPath());

    TaskExecutor executor = xmlTracking.getExecutor();
    assertSame("application executor is used", testExecutor, executor);

    List<String> triggers = Arrays.asList(testScheduler.getTriggerNames("beet"));
    assertEquals("flush and rotate jobs scheduled in application scheduler", 2, triggers.size());
    assertTrue("flush job scheduled", triggers.contains("xmlTracking_flush_trigger"));
    assertTrue("rotate job scheduled",
            triggers.contains("org.springframework.scheduling.quartz.CronTriggerBean_rotate_trigger"));

    SchedulerFactory factory = new StdSchedulerFactory();
    assertEquals("private scheduler was not created", 1, factory.getAllSchedulers().size());
    assertSame(testScheduler, factory.getAllSchedulers().iterator().next());

    //verify that MBeans have been registered
    MBeanServer server = JmxUtils.locateMBeanServer();
    assertNotNull("manager mbean found", server.getMBeanInfo(
            new ObjectName("testApp:package=com.mtgi.analytics,group=xmlTracking,name=BeetManager")));
    ObjectName logName = new ObjectName("testApp:package=com.mtgi.analytics,group=xmlTracking,name=BeetLog");
    assertNotNull("log mbean found", server.getMBeanInfo(logName));

    assertEquals(persister.getFileSize(), server.getAttribute(logName, "FileSize"));
}

From source file:com.mtgi.analytics.jmx.StatisticsMBeanEventPersisterTest.java

private void waitForCount(ObjectName id, int count) throws JMException, InterruptedException {
    MBeanServer jmx = JmxUtils.locateMBeanServer();
    long start = System.currentTimeMillis();
    int actual = -1;
    do {//from w  w  w . j a  v  a 2  s .c  o m
        if (jmx.isRegistered(id))
            actual = ((Number) jmx.getAttribute(id, "Count")).intValue();
        if (actual < count)
            Thread.sleep(10);
    } while (actual < count && (System.currentTimeMillis() - start) < 300000);
    assertEquals("events received for " + id, actual, count);
}

From source file:fr.xebia.management.statistics.ProfileAspect.java

public void afterPropertiesSet() throws Exception {
    if (this.server == null) {
        this.server = JmxUtils.locateMBeanServer();
    }/* ww  w  .  ja v  a2  s  .  c o m*/

    this.mbeanExporter = new AnnotationMBeanExporter();
    this.mbeanExporter.setEnsureUniqueRuntimeObjectNames(false);
    this.mbeanExporter.setServer(this.server);
    this.mbeanExporter.setAutodetectMode(MBeanExporter.AUTODETECT_NONE);
    this.mbeanExporter.afterPropertiesSet();
}

From source file:com.brienwheeler.lib.jmx.logging.Log4jMBeanExporter.java

private synchronized int registerMBeansInternal() {
    // protect against JMX invocation while shutting down
    if (shutdown)
        return 0;

    MBeanServer server = JmxUtils.locateMBeanServer();

    HierarchyDynamicMBean hdm;//from w  w w.j  a  va  2s . c  o  m
    synchronized (this.getClass()) {
        boolean usedNew = hierarchyDynamicMBean.compareAndSet(null, new HierarchyDynamicMBean());
        hdm = hierarchyDynamicMBean.get();
        if (usedNew) {
            try {
                ObjectName mbo = new ObjectName(LOG4J_HIERARCHY_DEFAULT);
                server.registerMBean(hdm, mbo);
                registeredHierarchy = true;
                // Add the root logger to the Hierarchy MBean
                hdm.addLoggerMBean(Logger.getRootLogger().getName());
            } catch (Exception e) {
                log.error("Error initializing Log4jMBeanExporter", e);
                return 0;
            }
        }
    }

    // Get each logger from the Log4J Repository and add it to
    // the Hierarchy MBean created above.
    LoggerRepository r = LogManager.getLoggerRepository();

    Enumeration<?> loggers = r.getCurrentLoggers();
    int count = 0;

    while (loggers.hasMoreElements()) {
        String name = ((Logger) loggers.nextElement()).getName();
        // this name definition copied from HierarchyDynamicMBean
        ObjectName objectName;
        try {
            objectName = new ObjectName("log4j", "logger", name);
        } catch (Exception e) {
            log.error("Error creating JMX name for " + name, e);
            continue;
        }

        if (!server.isRegistered(objectName)) {
            if (log.isDebugEnabled()) {
                log.debug("[contextInitialized]: Registering " + name);
            }
            registeredNames.add(hdm.addLoggerMBean(name));
            count++;
        }
    }

    log.debug("registered " + count + " new Log4j MBeans");
    return count;
}

From source file:fr.xebia.management.ServletContextAwareMBeanServerFactory.java

public void afterPropertiesSet() throws Exception {

    if (this.server == null) {
        this.server = JmxUtils.locateMBeanServer();
    }/*from ww  w .  ja v a  2 s  .c  o m*/

    Assert.notNull(this.servletContext, "servletContext can NOT be null");

    objectNameExtraAttributes.put("path", servletContext.getContextPath());

    if ("org.apache.catalina.core.ApplicationContextFacade".equals(servletContext.getClass().getName())) {

        Field applicationContextFacadeContextField = Class
                .forName("org.apache.catalina.core.ApplicationContextFacade").getDeclaredField("context");
        applicationContextFacadeContextField.setAccessible(true);

        Field applicationContextContextField = Class.forName("org.apache.catalina.core.ApplicationContext")
                .getDeclaredField("context");
        applicationContextContextField.setAccessible(true);

        Field standardContextHostNameField = Class.forName("org.apache.catalina.core.StandardContext")
                .getDeclaredField("hostName");
        standardContextHostNameField.setAccessible(true);

        Object applicationContext = applicationContextFacadeContextField.get(servletContext);
        Object standardContext = applicationContextContextField.get(applicationContext);
        String hostName = (String) standardContextHostNameField.get(standardContext);

        objectNameExtraAttributes.put("host", hostName);
    }
    logger.trace("Extra objectname attributes : {}" + this.objectNameExtraAttributes);
}