JMX and Spring – Part 2

This post continues from Part 1 of the tutorial.

Hi, in my previous article I explained how to setup a JMX server through Spring and how to protect access to it through authentication and authorisation.

In this article I will show how to implement a simple MBean which allows users to change the level of a Log4j logger at runtime without the need to restart the application.

The Spring configuration has changed only slightly from my previous article to facilitate testing; the substance remains the same though.

The Spring configuration

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">


    <bean id="propertyConfigurer"
       class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jemos-jmx.properties</value>
                <value>file:///${user.home}/.secure/jmxconnector-credentials.properties</value>
            </list>
        </property>
    </bean>

<!-- In order to automatically detect MBeans we need to recognise Spring beans -->
    <context:component-scan base-package="uk.co.jemos.experiments.jmx.mbeans" />

<!-- This causes MBeans annotations to be recognised and MBeans to be registered with the JMX server -->
    <context:mbean-export default-domain="jemos.mbeans"/>

    <bean id="jemosJmxServer" class="org.springframework.jmx.support.ConnectorServerFactoryBean"
        depends-on="rmiRegistry">
        <property name="objectName" value="connector:name=rmi" />
        <property name="serviceUrl"
            value="service:jmx:rmi://localhost/jndi/rmi://localhost:${jemos.jmx.rmi.port}/jemosJmxConnector" />
        <property name="environment">
            <!-- the following is only valid when the sun jmx implementation is used -->
            <map>
                <entry key="jmx.remote.x.password.file" value="${user.home}/.secure/jmxremote.password" />
                <entry key="jmx.remote.x.access.file" value="${user.home}/.secure/jmxremote.access" />
            </map>
        </property>
    </bean>

    <bean id="rmiRegistry" class="org.springframework.remoting.rmi.RmiRegistryFactoryBean">
        <property name="port" value="${jemos.jmx.rmi.port}" />
    </bean>

<!-- Used for testing -->
    <bean id="clientConnector" class="org.springframework.jmx.support.MBeanServerConnectionFactoryBean"
        depends-on="jemosJmxServer">
          <property name="serviceUrl" value="service:jmx:rmi://localhost/jndi/rmi://localhost:${jemos.jmx.rmi.port}/jemosJmxConnector"/>
          <property name="environment">
            <map>
                <entry key="jmx.remote.credentials">
                  <bean factory-method="commaDelimitedListToStringArray">
                    <constructor-arg value="${jmx.username},${jmx.password}" />
                  </bean>
                </entry>
          </map>
        </property>
    </bean>

    
</beans>

The only part of the configuration which is of interest to us is the scanning of Spring components and the declaration of the MBean exporter (which causes also MBean annotations to be recognised and Spring beans to be registered with a JMX server as MBeans)

The LoggerConfigurator MBean

package uk.co.jemos.experiments.jmx.mbeans;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedOperationParameter;
import org.springframework.jmx.export.annotation.ManagedOperationParameters;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.stereotype.Component;

/**
 * MBean which allows clients to change or retrieve the logging level for a
 * Log4j Logger at runtime.
 * 
 * @author mtedone
 * 
 */
@Component
@ManagedResource(objectName = LoggerConfigurator.MBEAN_NAME, //
description = "Allows clients to set the Log4j Logger level at runtime")
public class LoggerConfigurator {
    
    public static final String MBEAN_NAME = "jemos.mbeans:type=config,name=LoggingConfiguration";

    @ManagedOperation(description = "Returns the Logger LEVEL for the given logger name")
    @ManagedOperationParameters({ @ManagedOperationParameter(description = "The Logger Name", name = "loggerName"), })
    public String getLoggerLevel(String loggerName) {

        Logger logger = Logger.getLogger(loggerName);
        Level loggerLevel = logger.getLevel();

        return loggerLevel == null ? "The logger " + loggerName
                + " has not level" : loggerLevel.toString();

    }

    @ManagedOperation(description = "Set Logger Level")
    @ManagedOperationParameters({
            @ManagedOperationParameter(description = "The Logger Name", name = "loggerName"),
            @ManagedOperationParameter(description = "The Level to which the Logger must be set", name = "loggerLevel") })
    public void setLoggerLevel(String loggerName, String loggerLevel) {

        Logger thisLogger = Logger.getLogger(this.getClass());
        thisLogger.setLevel(Level.INFO);

        Logger logger = Logger.getLogger(loggerName);

        logger.setLevel(Level.toLevel(loggerLevel, Level.INFO));

        thisLogger.info("Set logger " + loggerName + " to level "
                + logger.getLevel());

    }

}

Apart from Spring JMX annotations (in bold), this is a normal Spring bean. With those annotations however we have made an MBean of it and this bean will be registered with the JMX server at startup.

The @ManagedOperation and @ManagedOperationParameters annotations determine what gets displayed on the jconsole. One could omit these annotations, but the parameter names would not become something like p1 and p2, without giving any information on the type of parameter.

Invoking the function with, say, the value foo.bar.baz, INFO would result in the following output:

...snip

2011-08-11 21:33:36 LoggerConfigurator [INFO] Set logger foo.bar.baz to level INFO

In my next and last article for this series, I will show how to setup an MBean which alerts a listener when the HEAP memory threshold has been reached, as explained in one of my previous articles

Continue to Part 3.

Reference: JMX and Spring – Part 2 from our JCG partner Marco Tedone at the Marco Tedone’s blog blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


8 + six =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books