Monday, July 23, 2007

Exposing the stereo knobs

As I mentioned in my last post, I'm about to implement an algorithm that involves a bunch of constant coefficients that we might be wanting to play around with. In order to make them easy to play with at runtime, we'll go the JMX route.

First, the service code will just have the coefficients injected as dependencies:

public class MagicalAlgorithmServiceImpl {
 protected int coefficientOne;
 protected int coefficientTwo;

 public void setCoefficientOne(int one) { ... }
 public void setCoefficientTwo(int two) { ... }

 public int performMagic() { ... }
}

Naturally, in the Spring application context, we'll create the bean like so, so it can be easily modified at build/startup time, using Maven resource filtering:

<bean id="magicalAlgorithmService" class="com.blogspot.codeartisan.magic.magicalAlgorithmServiceImpl">
 <property name="coefficientOne" value="${magic.coefficientOne}">
 <property name="coefficientTwo" value="${magic.coefficientTwo}">
</bean>

Now, we just need to define a management interface:

public interface MagicManager {
  public void setCoefficientOne(int one);
  public void setCoefficientTwo(int two);
}

Now, we make the MagicAlgorithmServiceImpl implement MagicManager.

Then if you've managed to get a JMX port exposed through your container (here's how to do it for Tomcat), all you need to do to expose this functionality via JMX is to use Spring's MBeanExporter:

<bean id="mbeanServer" class="java.lang.management.ManagementFactory" factory-method="getPlatformMBeanServer"/>

<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter" lazy-init="false">
  <property name="server" ref="mbeanServer"/>
  <property name="beans">
    <map>
      <entry key="MyApp:type=Twiddling,name=magicAlgorithm" value-ref="magicalAlgorithmService"/>
    </map>
  </property>
  <property name="assembler">
    <bean class="org.springframework.jmx.export.assembler.InterfaceBasedMBeanInfoAssembler">
      <property name="interfaceMappings">
        <props>
          <prop key="Fancast:type=Twiddling,name=magicAlgorithm">com.blogspot.codeartisan.magic.MagicManager</prop>
        </props>
      </property>
    </bean>
  </property>
</bean>

That's it. Now you can twiddle with the stereo knobs at runtime via a JMX console.

0 comments: