moving jmx.* unit tests from .testsuite -> .context

This commit is contained in:
Chris Beams
2008-12-17 00:39:28 +00:00
parent b4b8303375
commit 72854849d9
75 changed files with 72 additions and 25 deletions

View File

@@ -0,0 +1,58 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.interceptor;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/**
* Trivial interceptor that can be introduced in a chain to display it.
*
* @author Rod Johnson
*/
public class NopInterceptor implements MethodInterceptor {
private int count;
/**
* @see org.aopalliance.intercept.MethodInterceptor#invoke(MethodInvocation)
*/
public Object invoke(MethodInvocation invocation) throws Throwable {
increment();
return invocation.proceed();
}
public int getCount() {
return this.count;
}
protected void increment() {
++count;
}
public boolean equals(Object other) {
if (!(other instanceof NopInterceptor)) {
return false;
}
if (this == other) {
return true;
}
return this.count == ((NopInterceptor) other).count;
}
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jmx;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
/**
* Base JMX test class that pre-loads an ApplicationContext from a user-configurable file. Override the
* {@link #getApplicationContextPath()} method to control the configuration file location.
*
* @author Rob Harrop
* @author Juergen Hoeller
*/
public abstract class AbstractJmxTests extends AbstractMBeanServerTests {
private ConfigurableApplicationContext ctx;
protected final void onSetUp() throws Exception {
ctx = loadContext(getApplicationContextPath());
}
protected final void onTearDown() throws Exception {
if (ctx != null) {
ctx.close();
}
}
protected String getApplicationContextPath() {
return "org/springframework/jmx/applicationContext.xml";
}
protected ApplicationContext getContext() {
return this.ctx;
}
}

View File

@@ -0,0 +1,83 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jmx;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import junit.framework.TestCase;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public abstract class AbstractMBeanServerTests extends TestCase {
protected MBeanServer server;
public final void setUp() throws Exception {
this.server = MBeanServerFactory.createMBeanServer();
try {
onSetUp();
}
catch (Exception ex) {
releaseServer();
throw ex;
}
}
protected ConfigurableApplicationContext loadContext(String configLocation) {
GenericApplicationContext ctx = new GenericApplicationContext();
new XmlBeanDefinitionReader(ctx).loadBeanDefinitions(configLocation);
ctx.getDefaultListableBeanFactory().registerSingleton("server", this.server);
ctx.refresh();
return ctx;
}
protected void tearDown() throws Exception {
releaseServer();
onTearDown();
}
private void releaseServer() {
MBeanServerFactory.releaseMBeanServer(getServer());
}
protected void onTearDown() throws Exception {
}
protected void onSetUp() throws Exception {
}
public MBeanServer getServer() {
return this.server;
}
protected void assertIsRegistered(String message, ObjectName objectName) {
assertTrue(message, getServer().isRegistered(objectName));
}
protected void assertIsNotRegistered(String message, ObjectName objectName) {
assertFalse(message, getServer().isRegistered(objectName));
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public interface IJmxTestBean {
public int add(int x, int y);
public long myOperation();
public int getAge();
public void setAge(int age);
public void setName(String name) throws Exception;
public String getName();
// used to test invalid methods that exist in the proxy interface
public void dontExposeMe();
}

View File

@@ -0,0 +1,143 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx;
import java.io.IOException;
/**
* @@org.springframework.jmx.export.metadata.ManagedResource
* (description="My Managed Bean", objectName="spring:bean=test",
* log=true, logFile="jmx.log", currencyTimeLimit=15, persistPolicy="OnUpdate",
* persistPeriod=200, persistLocation="./foo", persistName="bar.jmx")
* @@org.springframework.jmx.export.metadata.ManagedNotification
* (name="My Notification", description="A Notification", notificationType="type.foo,type.bar")
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class JmxTestBean implements IJmxTestBean {
private String name;
private String nickName;
private int age;
private boolean isSuperman;
/**
* @@org.springframework.jmx.export.metadata.ManagedAttribute
* (description="The Age Attribute", currencyTimeLimit=15)
*/
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
/**
* @@org.springframework.jmx.export.metadata.ManagedOperation(currencyTimeLimit=30)
*/
public long myOperation() {
return 1L;
}
/**
* @@org.springframework.jmx.export.metadata.ManagedAttribute
* (description="The Name Attribute", currencyTimeLimit=20,
* defaultValue="bar", persistPolicy="OnUpdate")
*/
public void setName(String name) throws Exception {
if ("Juergen".equals(name)) {
throw new IllegalArgumentException("Juergen");
}
if ("Juergen Class".equals(name)) {
throw new ClassNotFoundException("Juergen");
}
if ("Juergen IO".equals(name)) {
throw new IOException("Juergen");
}
this.name = name;
}
/**
* @@org.springframework.jmx.export.metadata.ManagedAttribute
* (defaultValue="foo", persistPeriod=300)
*/
public String getName() {
return name;
}
/**
* @@org.springframework.jmx.export.metadata.ManagedAttribute(description="The Nick
* Name
* Attribute")
*/
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getNickName() {
return this.nickName;
}
public void setSuperman(boolean superman) {
this.isSuperman = superman;
}
/**
* @@org.springframework.jmx.export.metadata.ManagedAttribute(description="The Is
* Superman
* Attribute")
*/
public boolean isSuperman() {
return isSuperman;
}
/**
* @@org.springframework.jmx.export.metadata.ManagedOperation(description="Add Two
* Numbers
* Together")
* @@org.springframework.jmx.export.metadata.ManagedOperationParameter(index=0, name="x", description="Left operand")
* @@org.springframework.jmx.export.metadata.ManagedOperationParameter(index=1, name="y", description="Right operand")
*/
public int add(int x, int y) {
return x + y;
}
/**
* Test method that is not exposed by the MetadataAssembler.
*/
public void dontExposeMe() {
throw new RuntimeException();
}
protected void someProtectedMethod() {
}
private void somePrivateMethod() {
}
protected void getSomething() {
}
private void getSomethingElse() {
}
}

View File

@@ -0,0 +1,316 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.access;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.BindException;
import java.util.HashMap;
import java.util.Map;
import javax.management.Descriptor;
import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
import org.junit.Ignore;
import org.springframework.jmx.AbstractMBeanServerTests;
import org.springframework.jmx.IJmxTestBean;
import org.springframework.jmx.JmxException;
import org.springframework.jmx.JmxTestBean;
import org.springframework.jmx.export.MBeanExporter;
import org.springframework.jmx.export.assembler.AbstractReflectiveMBeanInfoAssembler;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
//@Ignore // see https://issuetracker.springsource.com/browse/BRITS-235
public class MBeanClientInterceptorTests extends AbstractMBeanServerTests {
protected static final String OBJECT_NAME = "spring:test=proxy";
protected JmxTestBean target;
protected boolean runTests = true;
public void onSetUp() throws Exception {
target = new JmxTestBean();
target.setAge(100);
target.setName("Rob Harrop");
MBeanExporter adapter = new MBeanExporter();
Map beans = new HashMap();
beans.put(OBJECT_NAME, target);
adapter.setServer(getServer());
adapter.setBeans(beans);
adapter.setAssembler(new ProxyTestAssembler());
adapter.afterPropertiesSet();
}
protected MBeanServerConnection getServerConnection() throws Exception {
return getServer();
}
protected IJmxTestBean getProxy() throws Exception {
MBeanProxyFactoryBean factory = new MBeanProxyFactoryBean();
factory.setServer(getServerConnection());
factory.setProxyInterface(IJmxTestBean.class);
factory.setObjectName(OBJECT_NAME);
factory.afterPropertiesSet();
return (IJmxTestBean) factory.getObject();
}
public void testProxyClassIsDifferent() throws Exception {
if (!runTests) return;
IJmxTestBean proxy = getProxy();
assertTrue("The proxy class should be different than the base class",
(proxy.getClass() != IJmxTestBean.class));
}
public void testDifferentProxiesSameClass() throws Exception {
if (!runTests) return;
IJmxTestBean proxy1 = getProxy();
IJmxTestBean proxy2 = getProxy();
assertNotSame("The proxies should NOT be the same", proxy1, proxy2);
assertSame("The proxy classes should be the same", proxy1.getClass(), proxy2.getClass());
}
public void testGetAttributeValue() throws Exception {
if (!runTests) return;
IJmxTestBean proxy1 = getProxy();
int age = proxy1.getAge();
assertEquals("The age should be 100", 100, age);
}
public void testSetAttributeValue() throws Exception {
if (!runTests) return;
IJmxTestBean proxy = getProxy();
proxy.setName("Rob Harrop");
assertEquals("The name of the bean should have been updated", "Rob Harrop", target.getName());
}
public void testSetAttributeValueWithRuntimeException() throws Exception {
if (!runTests) return;
IJmxTestBean proxy = getProxy();
try {
proxy.setName("Juergen");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
}
public void testSetAttributeValueWithCheckedException() throws Exception {
if (!runTests) return;
IJmxTestBean proxy = getProxy();
try {
proxy.setName("Juergen Class");
fail("Should have thrown ClassNotFoundException");
}
catch (ClassNotFoundException ex) {
// expected
}
}
public void testSetAttributeValueWithIOException() throws Exception {
if (!runTests) return;
IJmxTestBean proxy = getProxy();
try {
proxy.setName("Juergen IO");
fail("Should have thrown IOException");
}
catch (IOException ex) {
// expected
}
}
public void testSetReadOnlyAttribute() throws Exception {
if (!runTests) return;
IJmxTestBean proxy = getProxy();
try {
proxy.setAge(900);
fail("Should not be able to write to a read only attribute");
}
catch (InvalidInvocationException ex) {
// success
}
}
public void testInvokeNoArgs() throws Exception {
if (!runTests) return;
IJmxTestBean proxy = getProxy();
long result = proxy.myOperation();
assertEquals("The operation should return 1", 1, result);
}
public void testInvokeArgs() throws Exception {
if (!runTests) return;
IJmxTestBean proxy = getProxy();
int result = proxy.add(1, 2);
assertEquals("The operation should return 3", 3, result);
}
public void testInvokeUnexposedMethodWithException() throws Exception {
if (!runTests) return;
IJmxTestBean bean = getProxy();
try {
bean.dontExposeMe();
fail("Method dontExposeMe should throw an exception");
}
catch (InvalidInvocationException desired) {
// success
}
}
@Ignore // see https://issuetracker.springsource.com/browse/BRITS-235
public void ignoreTestLazyConnectionToRemote() throws Exception {
if (!runTests) return;
JMXServiceURL url = new JMXServiceURL("service:jmx:jmxmp://localhost:9876");
JMXConnectorServer connector = JMXConnectorServerFactory.newJMXConnectorServer(url, null, getServer());
MBeanProxyFactoryBean factory = new MBeanProxyFactoryBean();
factory.setServiceUrl(url.toString());
factory.setProxyInterface(IJmxTestBean.class);
factory.setObjectName(OBJECT_NAME);
factory.setConnectOnStartup(false);
factory.setRefreshOnConnectFailure(true);
// should skip connection to the server
factory.afterPropertiesSet();
IJmxTestBean bean = (IJmxTestBean) factory.getObject();
// now start the connector
try {
connector.start();
}
catch (BindException ex) {
// couldn't bind to local port 9876 - let's skip the remainder of this test
System.out.println(
"Skipping JMX LazyConnectionToRemote test because binding to local port 9876 failed: " +
ex.getMessage());
return;
}
// should now be able to access data via the lazy proxy
try {
assertEquals("Rob Harrop", bean.getName());
assertEquals(100, bean.getAge());
}
finally {
connector.stop();
}
try {
bean.getName();
}
catch (JmxException ex) {
// expected
}
connector = JMXConnectorServerFactory.newJMXConnectorServer(url, null, getServer());
connector.start();
// should now be able to access data via the lazy proxy
try {
assertEquals("Rob Harrop", bean.getName());
assertEquals(100, bean.getAge());
}
finally {
connector.stop();
}
}
// Commented out because of a side effect with the the started platform MBeanServer.
/*
public void testMXBeanAttributeAccess() throws Exception {
if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_15) {
return;
}
MBeanClientInterceptor interceptor = new MBeanClientInterceptor();
interceptor.setServer(ManagementFactory.getPlatformMBeanServer());
interceptor.setObjectName("java.lang:type=Memory");
interceptor.setManagementInterface(MemoryMXBean.class);
MemoryMXBean proxy = (MemoryMXBean) ProxyFactory.getProxy(MemoryMXBean.class, interceptor);
assertTrue(proxy.getHeapMemoryUsage().getMax() > 0);
}
public void testMXBeanOperationAccess() throws Exception {
if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_15) {
return;
}
MBeanClientInterceptor interceptor = new MBeanClientInterceptor();
interceptor.setServer(ManagementFactory.getPlatformMBeanServer());
interceptor.setObjectName("java.lang:type=Threading");
ThreadMXBean proxy = (ThreadMXBean) ProxyFactory.getProxy(ThreadMXBean.class, interceptor);
assertTrue(proxy.getThreadInfo(Thread.currentThread().getId()).getStackTrace() != null);
}
*/
private static class ProxyTestAssembler extends AbstractReflectiveMBeanInfoAssembler {
protected boolean includeReadAttribute(Method method, String beanKey) {
return true;
}
protected boolean includeWriteAttribute(Method method, String beanKey) {
if ("setAge".equals(method.getName())) {
return false;
}
return true;
}
protected boolean includeOperation(Method method, String beanKey) {
if ("dontExposeMe".equals(method.getName())) {
return false;
}
return true;
}
protected String getOperationDescription(Method method) {
return method.getName();
}
protected String getAttributeDescription(PropertyDescriptor propertyDescriptor) {
return propertyDescriptor.getDisplayName();
}
protected void populateAttributeDescriptor(Descriptor descriptor, Method getter, Method setter) {
}
protected void populateOperationDescriptor(Descriptor descriptor, Method method) {
}
protected String getDescription(String beanKey, Class beanClass) {
return "";
}
protected void populateMBeanDescriptor(Descriptor mbeanDescriptor, String beanKey, Class beanClass) {
}
}
}

View File

@@ -0,0 +1,72 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.access;
import java.net.BindException;
import java.net.MalformedURLException;
import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
import org.junit.Ignore;
/**
* @author Rob Harrop
*/
@Ignore // see https://issuetracker.springsource.com/browse/BRITS-235
public class RemoteMBeanClientInterceptorTests extends MBeanClientInterceptorTests {
private static final String SERVICE_URL = "service:jmx:jmxmp://localhost:9876";
private JMXConnectorServer connectorServer;
private JMXConnector connector;
public void onSetUp() throws Exception {
super.onSetUp();
this.connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(getServiceUrl(), null, getServer());
try {
this.connectorServer.start();
}
catch (BindException ex) {
// skipping tests, server already running at this port
runTests = false;
}
}
private JMXServiceURL getServiceUrl() throws MalformedURLException {
return new JMXServiceURL(SERVICE_URL);
}
protected MBeanServerConnection getServerConnection() throws Exception {
this.connector = JMXConnectorFactory.connect(getServiceUrl());
return this.connector.getMBeanServerConnection();
}
public void tearDown() throws Exception {
if (this.connector != null) {
this.connector.close();
}
this.connectorServer.stop();
super.tearDown();
}
}

View File

@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="jmxAdapter" class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<map>
<entry key="bean:name=testBean1">
<ref local="testBean"/>
</entry>
</map>
</property>
</bean>
<bean id="testBean" class="org.springframework.jmx.JmxTestBean">
<property name="name">
<value>TEST</value>
</property>
<property name="age">
<value>100</value>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,68 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.management.ObjectName;
import org.junit.Ignore;
import org.springframework.jmx.AbstractJmxTests;
/**
* @author Rob Harrop
*/
@Ignore // changes in CustomEditorConfigurer broke these tests (see diff between r304:305)
public class CustomEditorConfigurerTests extends AbstractJmxTests {
private final SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
protected String getApplicationContextPath() {
return "org/springframework/jmx/export/customConfigurer.xml";
}
public void testDatesInJmx() throws Exception {
System.out.println(getServer().getClass().getName());
ObjectName oname = new ObjectName("bean:name=dateRange");
Date startJmx = (Date) getServer().getAttribute(oname, "StartDate");
Date endJmx = (Date) getServer().getAttribute(oname, "EndDate");
assertEquals("startDate ", getStartDate(), startJmx);
assertEquals("endDate ", getEndDate(), endJmx);
}
public void testGetDates() throws Exception {
DateRange dr = (DateRange) getContext().getBean("dateRange");
assertEquals("startDate ", getStartDate(), dr.getStartDate());
assertEquals("endDate ", getEndDate(), dr.getEndDate());
}
private Date getStartDate() throws ParseException {
Date start = df.parse("2004/10/12");
return start;
}
private Date getEndDate() throws ParseException {
Date end = df.parse("2004/11/13");
return end;
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export;
import java.util.Date;
/**
* @author Rob Harrop
*/
public class DateRange {
private Date startDate;
private Date endDate;
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export;
/**
* @author Rob Harrop
*/
public class ExceptionOnInitBean {
private boolean exceptOnInit = false;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setExceptOnInit(boolean exceptOnInit) {
this.exceptOnInit = exceptOnInit;
}
public ExceptionOnInitBean() {
if (exceptOnInit) {
throw new RuntimeException("I am being init'd!");
}
}
}

View File

@@ -0,0 +1,57 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import junit.framework.TestCase;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jmx.support.ObjectNameManager;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class LazyInitMBeanTests extends TestCase {
public void testLazyInit() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(getApplicationContextPath());
ctx.close();
}
public void testInvokeOnLazyInitBean() throws Exception {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(getApplicationContextPath());
assertFalse(ctx.getBeanFactory().containsSingleton("testBean"));
assertFalse(ctx.getBeanFactory().containsSingleton("testBean2"));
try {
MBeanServer server = (MBeanServer) ctx.getBean("server");
ObjectName oname = ObjectNameManager.getInstance("bean:name=testBean2");
String name = (String) server.getAttribute(oname, "Name");
assertEquals("Invalid name returned", "foo", name);
}
finally {
ctx.close();
}
}
private String getApplicationContextPath() {
return "org/springframework/jmx/export/lazyInit.xml";
}
}

View File

@@ -0,0 +1,119 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jmx.export;
import javax.management.InstanceAlreadyExistsException;
import javax.management.ObjectName;
import javax.management.MBeanInfo;
import javax.management.modelmbean.RequiredModelMBean;
import javax.management.modelmbean.ModelMBeanInfo;
import javax.management.modelmbean.ModelMBeanInfoSupport;
import org.springframework.jmx.AbstractMBeanServerTests;
import org.springframework.jmx.JmxTestBean;
import org.springframework.jmx.export.naming.ObjectNamingStrategy;
import org.springframework.jmx.support.ObjectNameManager;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class MBeanExporterOperationsTests extends AbstractMBeanServerTests {
public void testRegisterManagedResourceWithUserSuppliedObjectName() throws Exception {
ObjectName objectName = ObjectNameManager.getInstance("spring:name=Foo");
JmxTestBean bean = new JmxTestBean();
bean.setName("Rob Harrop");
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(getServer());
exporter.registerManagedResource(bean, objectName);
String name = (String) getServer().getAttribute(objectName, "Name");
assertEquals("Incorrect name on MBean", name, bean.getName());
}
public void testRegisterExistingMBeanWithUserSuppliedObjectName() throws Exception {
ObjectName objectName = ObjectNameManager.getInstance("spring:name=Foo");
ModelMBeanInfo info = new ModelMBeanInfoSupport("myClass", "myDescription", null, null, null, null);
RequiredModelMBean bean = new RequiredModelMBean(info);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(getServer());
exporter.registerManagedResource(bean, objectName);
MBeanInfo infoFromServer = getServer().getMBeanInfo(objectName);
assertEquals(info, infoFromServer);
}
public void testRegisterManagedResourceWithGeneratedObjectName() throws Exception {
final ObjectName objectNameTemplate = ObjectNameManager.getInstance("spring:type=Test");
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(getServer());
exporter.setNamingStrategy(new ObjectNamingStrategy() {
public ObjectName getObjectName(Object managedBean, String beanKey) {
return objectNameTemplate;
}
});
JmxTestBean bean1 = new JmxTestBean();
JmxTestBean bean2 = new JmxTestBean();
ObjectName reg1 = exporter.registerManagedResource(bean1);
ObjectName reg2 = exporter.registerManagedResource(bean2);
assertIsRegistered("Bean 1 not registered with MBeanServer", reg1);
assertIsRegistered("Bean 2 not registered with MBeanServer", reg2);
assertObjectNameMatchesTemplate(objectNameTemplate, reg1);
assertObjectNameMatchesTemplate(objectNameTemplate, reg2);
}
public void testRegisterManagedResourceWithGeneratedObjectNameWithoutUniqueness() throws Exception {
final ObjectName objectNameTemplate = ObjectNameManager.getInstance("spring:type=Test");
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(getServer());
exporter.setEnsureUniqueRuntimeObjectNames(false);
exporter.setNamingStrategy(new ObjectNamingStrategy() {
public ObjectName getObjectName(Object managedBean, String beanKey) {
return objectNameTemplate;
}
});
JmxTestBean bean1 = new JmxTestBean();
JmxTestBean bean2 = new JmxTestBean();
ObjectName reg1 = exporter.registerManagedResource(bean1);
assertIsRegistered("Bean 1 not registered with MBeanServer", reg1);
try {
exporter.registerManagedResource(bean2);
fail("Shouldn't be able to register a runtime MBean with a reused ObjectName.");
}
catch (MBeanExportException e) {
assertEquals("Incorrect root cause", InstanceAlreadyExistsException.class, e.getCause().getClass());
}
}
private void assertObjectNameMatchesTemplate(ObjectName objectNameTemplate, ObjectName registeredName) {
assertEquals("Domain is incorrect", objectNameTemplate.getDomain(), registeredName.getDomain());
}
}

View File

@@ -0,0 +1,762 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jmx.export;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.management.Attribute;
import javax.management.InstanceNotFoundException;
import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.modelmbean.ModelMBeanInfo;
import org.junit.Ignore;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.interceptor.NopInterceptor;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jmx.AbstractMBeanServerTests;
import org.springframework.jmx.IJmxTestBean;
import org.springframework.jmx.JmxTestBean;
import org.springframework.jmx.export.assembler.AutodetectCapableMBeanInfoAssembler;
import org.springframework.jmx.export.assembler.MBeanInfoAssembler;
import org.springframework.jmx.export.assembler.SimpleReflectiveMBeanInfoAssembler;
import org.springframework.jmx.export.naming.SelfNaming;
import org.springframework.jmx.support.ObjectNameManager;
/**
* Integration tests for the MBeanExporter class.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @author Rick Evans
* @author Mark Fisher
*/
public class MBeanExporterTests extends AbstractMBeanServerTests {
private static final String OBJECT_NAME = "spring:test=jmxMBeanAdaptor";
@Ignore // throwing CCE
public void ignoreTestRegisterNonNotificationListenerType() throws Exception {
Map listeners = new HashMap();
// put a non-NotificationListener instance in as a value...
listeners.put("*", this);
MBeanExporter exporter = new MBeanExporter();
try {
exporter.setNotificationListenerMappings(listeners);
fail("Must have thrown an IllegalArgumentException when registering a non-NotificationListener instance as a NotificationListener.");
}
catch (IllegalArgumentException expected) {
}
}
@Ignore // not throwing expected IAE
public void ignoreTestRegisterNullNotificationListenerType() throws Exception {
Map listeners = new HashMap();
// put null in as a value...
listeners.put("*", null);
MBeanExporter exporter = new MBeanExporter();
try {
exporter.setNotificationListenerMappings(listeners);
fail("Must have thrown an IllegalArgumentException when registering a null instance as a NotificationListener.");
}
catch (IllegalArgumentException expected) {
}
}
public void testRegisterNotificationListenerForNonExistentMBean() throws Exception {
Map listeners = new HashMap();
NotificationListener dummyListener = new NotificationListener() {
public void handleNotification(Notification notification, Object handback) {
throw new UnsupportedOperationException();
}
};
// the MBean with the supplied object name does not exist...
listeners.put("spring:type=Test", dummyListener);
MBeanExporter exporter = new MBeanExporter();
exporter.setBeans(getBeanMap());
exporter.setServer(server);
exporter.setNotificationListenerMappings(listeners);
try {
exporter.afterPropertiesSet();
fail("Must have thrown an MBeanExportException when registering a NotificationListener on a non-existent MBean.");
}
catch (MBeanExportException expected) {
assertTrue(expected.contains(InstanceNotFoundException.class));
}
}
public void testWithSuppliedMBeanServer() throws Exception {
MBeanExporter exporter = new MBeanExporter();
exporter.setBeans(getBeanMap());
exporter.setServer(server);
exporter.afterPropertiesSet();
assertIsRegistered("The bean was not registered with the MBeanServer", ObjectNameManager.getInstance(OBJECT_NAME));
}
/** Fails if JVM platform MBean server has been started already
public void testWithLocatedMBeanServer() throws Exception {
MBeanExporter adaptor = new MBeanExporter();
adaptor.setBeans(getBeanMap());
adaptor.afterPropertiesSet();
assertIsRegistered("The bean was not registered with the MBeanServer", ObjectNameManager.getInstance(OBJECT_NAME));
server.unregisterMBean(new ObjectName(OBJECT_NAME));
}
*/
public void testUserCreatedMBeanRegWithDynamicMBean() throws Exception {
Map map = new HashMap();
map.put("spring:name=dynBean", new TestDynamicMBean());
InvokeDetectAssembler asm = new InvokeDetectAssembler();
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(map);
exporter.setAssembler(asm);
exporter.afterPropertiesSet();
Object name = server.getAttribute(ObjectNameManager.getInstance("spring:name=dynBean"), "Name");
assertEquals("The name attribute is incorrect", "Rob Harrop", name);
assertFalse("Assembler should not have been invoked", asm.invoked);
}
public void testAutodetectMBeans() throws Exception {
XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("autodetectMBeans.xml", getClass()));
try {
bf.getBean("exporter");
MBeanServer server = (MBeanServer) bf.getBean("server");
ObjectInstance instance = server.getObjectInstance(ObjectNameManager.getInstance("spring:mbean=true"));
assertNotNull(instance);
instance = server.getObjectInstance(ObjectNameManager.getInstance("spring:mbean2=true"));
assertNotNull(instance);
instance = server.getObjectInstance(ObjectNameManager.getInstance("spring:mbean3=true"));
assertNotNull(instance);
}
finally {
bf.destroySingletons();
}
}
public void testAutodetectWithExclude() throws Exception {
XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("autodetectMBeans.xml", getClass()));
try {
bf.getBean("exporter");
MBeanServer server = (MBeanServer) bf.getBean("server");
ObjectInstance instance = server.getObjectInstance(ObjectNameManager.getInstance("spring:mbean=true"));
assertNotNull(instance);
try {
server.getObjectInstance(ObjectNameManager.getInstance("spring:mbean=false"));
fail("MBean with name spring:mbean=false should have been excluded");
}
catch (InstanceNotFoundException expected) {
}
}
finally {
bf.destroySingletons();
}
}
public void testAutodetectLazyMBeans() throws Exception {
XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("autodetectLazyMBeans.xml", getClass()));
try {
bf.getBean("exporter");
MBeanServer server = (MBeanServer) bf.getBean("server");
ObjectName oname = ObjectNameManager.getInstance("spring:mbean=true");
assertNotNull(server.getObjectInstance(oname));
String name = (String) server.getAttribute(oname, "Name");
assertEquals("Invalid name returned", "Rob Harrop", name);
oname = ObjectNameManager.getInstance("spring:mbean=another");
assertNotNull(server.getObjectInstance(oname));
name = (String) server.getAttribute(oname, "Name");
assertEquals("Invalid name returned", "Juergen Hoeller", name);
}
finally {
bf.destroySingletons();
}
}
public void testAutodetectNoMBeans() throws Exception {
XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("autodetectNoMBeans.xml", getClass()));
try {
bf.getBean("exporter");
}
finally {
bf.destroySingletons();
}
}
public void testWithMBeanExporterListeners() throws Exception {
MockMBeanExporterListener listener1 = new MockMBeanExporterListener();
MockMBeanExporterListener listener2 = new MockMBeanExporterListener();
MBeanExporter exporter = new MBeanExporter();
exporter.setBeans(getBeanMap());
exporter.setServer(server);
exporter.setListeners(new MBeanExporterListener[] {listener1, listener2});
exporter.afterPropertiesSet();
exporter.destroy();
assertListener(listener1);
assertListener(listener2);
}
public void testExportJdkProxy() throws Exception {
JmxTestBean bean = new JmxTestBean();
bean.setName("Rob Harrop");
ProxyFactory factory = new ProxyFactory();
factory.setTarget(bean);
factory.addAdvice(new NopInterceptor());
factory.setInterfaces(new Class[]{IJmxTestBean.class});
IJmxTestBean proxy = (IJmxTestBean) factory.getProxy();
String name = "bean:mmm=whatever";
Map beans = new HashMap();
beans.put(name, proxy);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.registerBeans();
ObjectName oname = ObjectName.getInstance(name);
Object nameValue = server.getAttribute(oname, "Name");
assertEquals("Rob Harrop", nameValue);
}
public void testSelfNaming() throws Exception {
ObjectName objectName = ObjectNameManager.getInstance(OBJECT_NAME);
SelfNamingTestBean testBean = new SelfNamingTestBean();
testBean.setObjectName(objectName);
Map beans = new HashMap();
beans.put("foo", testBean);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.afterPropertiesSet();
ObjectInstance instance = server.getObjectInstance(objectName);
assertNotNull(instance);
}
public void testRegisterIgnoreExisting() throws Exception {
ObjectName objectName = ObjectNameManager.getInstance(OBJECT_NAME);
Person preRegistered = new Person();
preRegistered.setName("Rob Harrop");
server.registerMBean(preRegistered, objectName);
Person springRegistered = new Person();
springRegistered.setName("Sally Greenwood");
String objectName2 = "spring:test=equalBean";
Map beans = new HashMap();
beans.put(objectName.toString(), springRegistered);
beans.put(objectName2, springRegistered);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setRegistrationBehavior(MBeanExporter.REGISTRATION_IGNORE_EXISTING);
exporter.afterPropertiesSet();
ObjectInstance instance = server.getObjectInstance(objectName);
assertNotNull(instance);
ObjectInstance instance2 = server.getObjectInstance(new ObjectName(objectName2));
assertNotNull(instance2);
// should still be the first bean with name Rob Harrop
assertEquals("Rob Harrop", server.getAttribute(objectName, "Name"));
}
public void testRegisterReplaceExisting() throws Exception {
ObjectName objectName = ObjectNameManager.getInstance(OBJECT_NAME);
Person preRegistered = new Person();
preRegistered.setName("Rob Harrop");
server.registerMBean(preRegistered, objectName);
Person springRegistered = new Person();
springRegistered.setName("Sally Greenwood");
Map beans = new HashMap();
beans.put(objectName.toString(), springRegistered);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setRegistrationBehavior(MBeanExporter.REGISTRATION_REPLACE_EXISTING);
exporter.afterPropertiesSet();
ObjectInstance instance = server.getObjectInstance(objectName);
assertNotNull(instance);
// should still be the new bean with name Sally Greenwood
assertEquals("Sally Greenwood", server.getAttribute(objectName, "Name"));
}
public void testWithExposeClassLoader() throws Exception {
String name = "Rob Harrop";
String otherName = "Juergen Hoeller";
JmxTestBean bean = new JmxTestBean();
bean.setName(name);
ObjectName objectName = ObjectNameManager.getInstance("spring:type=Test");
Map beans = new HashMap();
beans.put(objectName.toString(), bean);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(getServer());
exporter.setBeans(beans);
exporter.setExposeManagedResourceClassLoader(true);
exporter.afterPropertiesSet();
assertIsRegistered("Bean instance not registered", objectName);
Object result = server.invoke(objectName, "add",
new Object[]{new Integer(2), new Integer(3)},
new String[]{int.class.getName(), int.class.getName()});
assertEquals("Incorrect result return from add", result, new Integer(5));
assertEquals("Incorrect attribute value", name, server.getAttribute(objectName, "Name"));
server.setAttribute(objectName, new Attribute("Name", otherName));
assertEquals("Incorrect updated name.", otherName, bean.getName());
}
public void testBonaFideMBeanIsNotExportedWhenAutodetectIsTotallyTurnedOff() throws Exception {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Person.class);
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerBeanDefinition("^&_invalidObjectName_(*", builder.getBeanDefinition());
String exportedBeanName = "export.me.please";
factory.registerSingleton(exportedBeanName, new TestBean());
MBeanExporter exporter = new MBeanExporter();
Map beansToExport = new HashMap();
beansToExport.put(OBJECT_NAME, exportedBeanName);
exporter.setBeans(beansToExport);
exporter.setServer(getServer());
exporter.setBeanFactory(factory);
exporter.setAutodetectMode(MBeanExporter.AUTODETECT_NONE);
// MBean has a bad ObjectName, so if said MBean is autodetected, an exception will be thrown...
exporter.afterPropertiesSet();
}
public void testOnlyBonaFideMBeanIsExportedWhenAutodetectIsMBeanOnly() throws Exception {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Person.class);
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerBeanDefinition(OBJECT_NAME, builder.getBeanDefinition());
String exportedBeanName = "spring:type=TestBean";
factory.registerSingleton(exportedBeanName, new TestBean());
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(getServer());
exporter.setAssembler(new NamedBeanAutodetectCapableMBeanInfoAssemblerStub(exportedBeanName));
exporter.setBeanFactory(factory);
exporter.setAutodetectMode(MBeanExporter.AUTODETECT_MBEAN);
exporter.afterPropertiesSet();
assertIsRegistered("Bona fide MBean not autodetected in AUTODETECT_MBEAN mode",
ObjectNameManager.getInstance(OBJECT_NAME));
assertIsNotRegistered("Bean autodetected and (only) AUTODETECT_MBEAN mode is on",
ObjectNameManager.getInstance(exportedBeanName));
}
public void testBonaFideMBeanAndRegularBeanExporterWithAutodetectAll() throws Exception {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Person.class);
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerBeanDefinition(OBJECT_NAME, builder.getBeanDefinition());
String exportedBeanName = "spring:type=TestBean";
factory.registerSingleton(exportedBeanName, new TestBean());
String notToBeExportedBeanName = "spring:type=NotToBeExported";
factory.registerSingleton(notToBeExportedBeanName, new TestBean());
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(getServer());
exporter.setAssembler(new NamedBeanAutodetectCapableMBeanInfoAssemblerStub(exportedBeanName));
exporter.setBeanFactory(factory);
exporter.setAutodetectMode(MBeanExporter.AUTODETECT_ALL);
exporter.afterPropertiesSet();
assertIsRegistered("Bona fide MBean not autodetected in (AUTODETECT_ALL) mode",
ObjectNameManager.getInstance(OBJECT_NAME));
assertIsRegistered("Bean not autodetected in (AUTODETECT_ALL) mode",
ObjectNameManager.getInstance(exportedBeanName));
assertIsNotRegistered("Bean autodetected and did not satisfy the autodetect info assembler",
ObjectNameManager.getInstance(notToBeExportedBeanName));
}
public void testBonaFideMBeanIsNotExportedWithAutodetectAssembler() throws Exception {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Person.class);
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerBeanDefinition(OBJECT_NAME, builder.getBeanDefinition());
String exportedBeanName = "spring:type=TestBean";
factory.registerSingleton(exportedBeanName, new TestBean());
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(getServer());
exporter.setAssembler(new NamedBeanAutodetectCapableMBeanInfoAssemblerStub(exportedBeanName));
exporter.setBeanFactory(factory);
exporter.setAutodetectMode(MBeanExporter.AUTODETECT_ASSEMBLER);
exporter.afterPropertiesSet();
assertIsNotRegistered("Bona fide MBean was autodetected in AUTODETECT_ASSEMBLER mode - must not have been",
ObjectNameManager.getInstance(OBJECT_NAME));
assertIsRegistered("Bean not autodetected in AUTODETECT_ASSEMBLER mode",
ObjectNameManager.getInstance(exportedBeanName));
}
/**
* Want to ensure that said MBean is not exported twice.
*/
public void testBonaFideMBeanExplicitlyExportedAndAutodetectionIsOn() throws Exception {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Person.class);
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerBeanDefinition(OBJECT_NAME, builder.getBeanDefinition());
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(getServer());
Map beansToExport = new HashMap();
beansToExport.put(OBJECT_NAME, OBJECT_NAME);
exporter.setBeans(beansToExport);
exporter.setAssembler(new NamedBeanAutodetectCapableMBeanInfoAssemblerStub(OBJECT_NAME));
exporter.setBeanFactory(factory);
exporter.setAutodetectMode(MBeanExporter.AUTODETECT_ASSEMBLER);
exporter.afterPropertiesSet();
assertIsRegistered("Explicitly exported bona fide MBean obviously not exported.",
ObjectNameManager.getInstance(OBJECT_NAME));
}
public void testSetAutodetectModeToOutOfRangeNegativeValue() throws Exception {
try {
MBeanExporter exporter = new MBeanExporter();
exporter.setAutodetectMode(-1);
fail("Must have failed when supplying an invalid negative out-of-range autodetect mode");
}
catch (IllegalArgumentException expected) {}
}
public void testSetAutodetectModeToOutOfRangePositiveValue() throws Exception {
try {
MBeanExporter exporter = new MBeanExporter();
exporter.setAutodetectMode(5);
fail("Must have failed when supplying an invalid positive out-of-range autodetect mode");
}
catch (IllegalArgumentException expected) {}
}
public void testSetAutodetectModeNameToNull() throws Exception {
try {
MBeanExporter exporter = new MBeanExporter();
exporter.setAutodetectModeName(null);
fail("Must have failed when supplying a null autodetect mode name");
}
catch (IllegalArgumentException expected) {}
}
public void testSetAutodetectModeNameToAnEmptyString() throws Exception {
try {
MBeanExporter exporter = new MBeanExporter();
exporter.setAutodetectModeName("");
fail("Must have failed when supplying an empty autodetect mode name");
}
catch (IllegalArgumentException expected) {}
}
public void testSetAutodetectModeNameToAWhitespacedString() throws Exception {
try {
MBeanExporter exporter = new MBeanExporter();
exporter.setAutodetectModeName(" \t");
fail("Must have failed when supplying a whitespace-only autodetect mode name");
}
catch (IllegalArgumentException expected) {}
}
public void testSetAutodetectModeNameToARubbishValue() throws Exception {
try {
MBeanExporter exporter = new MBeanExporter();
exporter.setAutodetectModeName("That Hansel is... *sssooo* hot right now!");
fail("Must have failed when supplying a whitespace-only autodetect mode name");
}
catch (IllegalArgumentException expected) {}
}
public void testNotRunningInBeanFactoryAndPassedBeanNameToExport() throws Exception {
try {
MBeanExporter exporter = new MBeanExporter();
Map beans = new HashMap();
beans.put(OBJECT_NAME, "beanName");
exporter.setBeans(beans);
exporter.afterPropertiesSet();
fail("Expecting exception because MBeanExporter is not running in a BeanFactory and was passed bean name to (lookup and then) export");
}
catch (MBeanExportException expected) {}
}
public void testNotRunningInBeanFactoryAndAutodetectionIsOn() throws Exception {
try {
MBeanExporter exporter = new MBeanExporter();
exporter.setAutodetectMode(MBeanExporter.AUTODETECT_ALL);
exporter.afterPropertiesSet();
fail("Expecting exception because MBeanExporter is not running in a BeanFactory and was configured to autodetect beans");
}
catch (MBeanExportException expected) {}
}
/**
* SPR-2158
*/
public void testMBeanIsNotUnregisteredSpuriouslyIfSomeExternalProcessHasUnregisteredMBean() throws Exception {
MBeanExporter exporter = new MBeanExporter();
exporter.setBeans(getBeanMap());
exporter.setServer(this.server);
MockMBeanExporterListener listener = new MockMBeanExporterListener();
exporter.setListeners(new MBeanExporterListener[]{listener});
exporter.afterPropertiesSet();
assertIsRegistered("The bean was not registered with the MBeanServer", ObjectNameManager.getInstance(OBJECT_NAME));
this.server.unregisterMBean(new ObjectName(OBJECT_NAME));
exporter.destroy();
assertEquals("Listener should not have been invoked (MBean previously unregistered by external agent)", 0, listener.getUnregistered().size());
}
/**
* SPR-3302
*/
public void testBeanNameCanBeUsedInNotificationListenersMap() throws Exception {
String beanName = "charlesDexterWard";
BeanDefinitionBuilder testBean = BeanDefinitionBuilder.rootBeanDefinition(JmxTestBean.class);
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerBeanDefinition(beanName, testBean.getBeanDefinition());
factory.preInstantiateSingletons();
Object testBeanInstance = factory.getBean(beanName);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(getServer());
Map beansToExport = new HashMap();
beansToExport.put("test:what=ever", testBeanInstance);
exporter.setBeans(beansToExport);
exporter.setBeanFactory(factory);
StubNotificationListener listener = new StubNotificationListener();
exporter.setNotificationListenerMappings(Collections.singletonMap(beanName, listener));
exporter.afterPropertiesSet();
}
public void testWildcardCanBeUsedInNotificationListenersMap() throws Exception {
String beanName = "charlesDexterWard";
BeanDefinitionBuilder testBean = BeanDefinitionBuilder.rootBeanDefinition(JmxTestBean.class);
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerBeanDefinition(beanName, testBean.getBeanDefinition());
factory.preInstantiateSingletons();
Object testBeanInstance = factory.getBean(beanName);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(getServer());
Map beansToExport = new HashMap();
beansToExport.put("test:what=ever", testBeanInstance);
exporter.setBeans(beansToExport);
exporter.setBeanFactory(factory);
StubNotificationListener listener = new StubNotificationListener();
exporter.setNotificationListenerMappings(Collections.singletonMap("*", listener));
exporter.afterPropertiesSet();
}
/*
* SPR-3625
*/
public void testMBeanIsUnregisteredForRuntimeExceptionDuringInitialization() throws Exception {
BeanDefinitionBuilder builder1 = BeanDefinitionBuilder.rootBeanDefinition(Person.class);
BeanDefinitionBuilder builder2 = BeanDefinitionBuilder.rootBeanDefinition(RuntimeExceptionThrowingConstructorBean.class);
String objectName1 = "spring:test=bean1";
String objectName2 = "spring:test=bean2";
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerBeanDefinition(objectName1, builder1.getBeanDefinition());
factory.registerBeanDefinition(objectName2, builder2.getBeanDefinition());
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(getServer());
Map beansToExport = new HashMap();
beansToExport.put(objectName1, objectName1);
beansToExport.put(objectName2, objectName2);
exporter.setBeans(beansToExport);
exporter.setBeanFactory(factory);
try {
exporter.afterPropertiesSet();
fail("Must have failed during creation of RuntimeExceptionThrowingConstructorBean");
}
catch (RuntimeException expected) {
}
assertIsNotRegistered("Must have unregistered all previously registered MBeans due to RuntimeException",
ObjectNameManager.getInstance(objectName1));
assertIsNotRegistered("Must have never registered this MBean due to RuntimeException",
ObjectNameManager.getInstance(objectName2));
}
private Map getBeanMap() {
Map map = new HashMap();
map.put(OBJECT_NAME, new JmxTestBean());
return map;
}
private void assertListener(MockMBeanExporterListener listener) throws MalformedObjectNameException {
ObjectName desired = ObjectNameManager.getInstance(OBJECT_NAME);
assertEquals("Incorrect number of registrations", 1, listener.getRegistered().size());
assertEquals("Incorrect number of unregistrations", 1, listener.getUnregistered().size());
assertEquals("Incorrect ObjectName in register", desired, listener.getRegistered().get(0));
assertEquals("Incorrect ObjectName in unregister", desired, listener.getUnregistered().get(0));
}
private static class InvokeDetectAssembler implements MBeanInfoAssembler {
private boolean invoked = false;
public ModelMBeanInfo getMBeanInfo(Object managedResource, String beanKey) throws JMException {
invoked = true;
return null;
}
}
private static class MockMBeanExporterListener implements MBeanExporterListener {
private List registered = new ArrayList();
private List unregistered = new ArrayList();
public void mbeanRegistered(ObjectName objectName) {
registered.add(objectName);
}
public void mbeanUnregistered(ObjectName objectName) {
unregistered.add(objectName);
}
public List getRegistered() {
return registered;
}
public List getUnregistered() {
return unregistered;
}
}
private static class SelfNamingTestBean implements SelfNaming {
private ObjectName objectName;
public void setObjectName(ObjectName objectName) {
this.objectName = objectName;
}
public ObjectName getObjectName() throws MalformedObjectNameException {
return this.objectName;
}
}
public static interface PersonMBean {
String getName();
}
public static class Person implements PersonMBean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static final class StubNotificationListener implements NotificationListener {
private List notifications = new ArrayList();
public void handleNotification(Notification notification, Object handback) {
this.notifications.add(notification);
}
public List getNotifications() {
return this.notifications;
}
}
private static class RuntimeExceptionThrowingConstructorBean {
public RuntimeExceptionThrowingConstructorBean() {
throw new RuntimeException();
}
}
private static final class NamedBeanAutodetectCapableMBeanInfoAssemblerStub
extends SimpleReflectiveMBeanInfoAssembler
implements AutodetectCapableMBeanInfoAssembler {
private String namedBean;
public NamedBeanAutodetectCapableMBeanInfoAssemblerStub(String namedBean) {
this.namedBean = namedBean;
}
public boolean includeBean(Class beanClass, String beanName) {
return this.namedBean.equals(beanName);
}
}
}

View File

@@ -0,0 +1,484 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jmx.export;
import java.util.HashMap;
import java.util.Map;
import javax.management.Attribute;
import javax.management.AttributeChangeNotification;
import javax.management.MalformedObjectNameException;
import javax.management.Notification;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import org.junit.Ignore;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.jmx.AbstractMBeanServerTests;
import org.springframework.jmx.JmxTestBean;
import org.springframework.jmx.access.NotificationListenerRegistrar;
import org.springframework.jmx.export.naming.SelfNaming;
import org.springframework.jmx.support.ObjectNameManager;
/**
* @author Rob Harrop
* @author Mark Fisher
*/
@Ignore // Getting CCEs regarding ObjectName being cast to String
public class NotificationListenerTests extends AbstractMBeanServerTests {
public void testRegisterNotificationListenerForMBean() throws Exception {
ObjectName objectName = ObjectName.getInstance("spring:name=Test");
JmxTestBean bean = new JmxTestBean();
Map beans = new HashMap();
beans.put(objectName, bean);
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
Map notificationListeners = new HashMap();
notificationListeners.put(objectName, listener);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListenerMappings(notificationListeners);
exporter.afterPropertiesSet();
// update the attribute
String attributeName = "Name";
server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop"));
assertEquals("Listener not notified", 1, listener.getCount(attributeName));
}
public void testRegisterNotificationListenerWithWildcard() throws Exception {
ObjectName objectName = ObjectName.getInstance("spring:name=Test");
JmxTestBean bean = new JmxTestBean();
Map beans = new HashMap();
beans.put(objectName, bean);
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
Map notificationListeners = new HashMap();
notificationListeners.put("*", listener);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListenerMappings(notificationListeners);
exporter.afterPropertiesSet();
// update the attribute
String attributeName = "Name";
server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop"));
assertEquals("Listener not notified", 1, listener.getCount(attributeName));
}
public void testRegisterNotificationListenerWithHandback() throws Exception {
String objectName = "spring:name=Test";
JmxTestBean bean = new JmxTestBean();
Map beans = new HashMap();
beans.put(objectName, bean);
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
Object handback = new Object();
NotificationListenerBean listenerBean = new NotificationListenerBean();
listenerBean.setNotificationListener(listener);
listenerBean.setMappedObjectName("spring:name=Test");
listenerBean.setHandback(handback);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListeners(new NotificationListenerBean[]{listenerBean});
exporter.afterPropertiesSet();
// update the attribute
String attributeName = "Name";
server.setAttribute(ObjectNameManager.getInstance("spring:name=Test"), new Attribute(attributeName, "Rob Harrop"));
assertEquals("Listener not notified", 1, listener.getCount(attributeName));
assertEquals("Handback object not transmitted correctly", handback, listener.getLastHandback(attributeName));
}
public void testRegisterNotificationListenerForAllMBeans() throws Exception {
ObjectName objectName = ObjectName.getInstance("spring:name=Test");
JmxTestBean bean = new JmxTestBean();
Map beans = new HashMap();
beans.put(objectName, bean);
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
NotificationListenerBean listenerBean = new NotificationListenerBean();
listenerBean.setNotificationListener(listener);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListeners(new NotificationListenerBean[]{listenerBean});
exporter.afterPropertiesSet();
// update the attribute
String attributeName = "Name";
server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop"));
assertEquals("Listener not notified", 1, listener.getCount(attributeName));
}
public void testRegisterNotificationListenerWithFilter() throws Exception {
ObjectName objectName = ObjectName.getInstance("spring:name=Test");
JmxTestBean bean = new JmxTestBean();
Map beans = new HashMap();
beans.put(objectName, bean);
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
NotificationListenerBean listenerBean = new NotificationListenerBean();
listenerBean.setNotificationListener(listener);
listenerBean.setNotificationFilter(new NotificationFilter() {
public boolean isNotificationEnabled(Notification notification) {
if (notification instanceof AttributeChangeNotification) {
AttributeChangeNotification changeNotification = (AttributeChangeNotification) notification;
return "Name".equals(changeNotification.getAttributeName());
}
else {
return false;
}
}
});
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListeners(new NotificationListenerBean[]{listenerBean});
exporter.afterPropertiesSet();
// update the attributes
String nameAttribute = "Name";
String ageAttribute = "Age";
server.setAttribute(objectName, new Attribute(nameAttribute, "Rob Harrop"));
server.setAttribute(objectName, new Attribute(ageAttribute, new Integer(90)));
assertEquals("Listener not notified for Name", 1, listener.getCount(nameAttribute));
assertEquals("Listener incorrectly notified for Age", 0, listener.getCount(ageAttribute));
}
public void testCreationWithNoNotificationListenerSet() {
try {
new NotificationListenerBean().afterPropertiesSet();
fail("Must have thrown an IllegalArgumentException (no NotificationListener supplied)");
}
catch (IllegalArgumentException expected) {
}
}
public void testRegisterNotificationListenerWithBeanNameAndBeanNameInBeansMap() throws Exception {
String beanName = "testBean";
ObjectName objectName = ObjectName.getInstance("spring:name=Test");
SelfNamingTestBean testBean = new SelfNamingTestBean();
testBean.setObjectName(objectName);
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerSingleton(beanName, testBean);
Map beans = new HashMap();
beans.put(beanName, beanName);
Map listenerMappings = new HashMap();
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
listenerMappings.put(beanName, listener);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListenerMappings(listenerMappings);
exporter.setBeanFactory(factory);
exporter.afterPropertiesSet();
assertIsRegistered("Should have registered MBean", objectName);
server.setAttribute(objectName, new Attribute("Age", new Integer(77)));
assertEquals("Listener not notified", 1, listener.getCount("Age"));
}
public void testRegisterNotificationListenerWithBeanNameAndBeanInstanceInBeansMap() throws Exception {
String beanName = "testBean";
ObjectName objectName = ObjectName.getInstance("spring:name=Test");
SelfNamingTestBean testBean = new SelfNamingTestBean();
testBean.setObjectName(objectName);
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerSingleton(beanName, testBean);
Map beans = new HashMap();
beans.put(beanName, testBean);
Map listenerMappings = new HashMap();
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
listenerMappings.put(beanName, listener);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListenerMappings(listenerMappings);
exporter.setBeanFactory(factory);
exporter.afterPropertiesSet();
assertIsRegistered("Should have registered MBean", objectName);
server.setAttribute(objectName, new Attribute("Age", new Integer(77)));
assertEquals("Listener not notified", 1, listener.getCount("Age"));
}
public void testRegisterNotificationListenerWithBeanNameBeforeObjectNameMappedToSameBeanInstance() throws Exception {
String beanName = "testBean";
ObjectName objectName = ObjectName.getInstance("spring:name=Test");
SelfNamingTestBean testBean = new SelfNamingTestBean();
testBean.setObjectName(objectName);
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerSingleton(beanName, testBean);
Map beans = new HashMap();
beans.put(beanName, testBean);
Map listenerMappings = new HashMap();
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
listenerMappings.put(beanName, listener);
listenerMappings.put(objectName, listener);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListenerMappings(listenerMappings);
exporter.setBeanFactory(factory);
exporter.afterPropertiesSet();
assertIsRegistered("Should have registered MBean", objectName);
server.setAttribute(objectName, new Attribute("Age", new Integer(77)));
assertEquals("Listener should have been notified exactly once", 1, listener.getCount("Age"));
}
public void testRegisterNotificationListenerWithObjectNameBeforeBeanNameMappedToSameBeanInstance() throws Exception {
String beanName = "testBean";
ObjectName objectName = ObjectName.getInstance("spring:name=Test");
SelfNamingTestBean testBean = new SelfNamingTestBean();
testBean.setObjectName(objectName);
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerSingleton(beanName, testBean);
Map beans = new HashMap();
beans.put(beanName, testBean);
Map listenerMappings = new HashMap();
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
listenerMappings.put(objectName, listener);
listenerMappings.put(beanName, listener);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListenerMappings(listenerMappings);
exporter.setBeanFactory(factory);
exporter.afterPropertiesSet();
assertIsRegistered("Should have registered MBean", objectName);
server.setAttribute(objectName, new Attribute("Age", new Integer(77)));
assertEquals("Listener should have been notified exactly once", 1, listener.getCount("Age"));
}
public void testRegisterNotificationListenerWithTwoBeanNamesMappedToDifferentBeanInstances() throws Exception {
String beanName1 = "testBean1";
String beanName2 = "testBean2";
ObjectName objectName1 = ObjectName.getInstance("spring:name=Test1");
ObjectName objectName2 = ObjectName.getInstance("spring:name=Test2");
SelfNamingTestBean testBean1 = new SelfNamingTestBean();
testBean1.setObjectName(objectName1);
SelfNamingTestBean testBean2 = new SelfNamingTestBean();
testBean2.setObjectName(objectName2);
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerSingleton(beanName1, testBean1);
factory.registerSingleton(beanName2, testBean2);
Map beans = new HashMap();
beans.put(beanName1, testBean1);
beans.put(beanName2, testBean2);
Map listenerMappings = new HashMap();
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
listenerMappings.put(beanName1, listener);
listenerMappings.put(beanName2, listener);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.setNotificationListenerMappings(listenerMappings);
exporter.setBeanFactory(factory);
exporter.afterPropertiesSet();
assertIsRegistered("Should have registered MBean", objectName1);
assertIsRegistered("Should have registered MBean", objectName2);
server.setAttribute(ObjectNameManager.getInstance(objectName1), new Attribute("Age", new Integer(77)));
assertEquals("Listener not notified for testBean1", 1, listener.getCount("Age"));
server.setAttribute(ObjectNameManager.getInstance(objectName2), new Attribute("Age", new Integer(33)));
assertEquals("Listener not notified for testBean2", 2, listener.getCount("Age"));
}
public void testNotificationListenerRegistrar() throws Exception {
ObjectName objectName = ObjectName.getInstance("spring:name=Test");
JmxTestBean bean = new JmxTestBean();
Map beans = new HashMap();
beans.put(objectName, bean);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.afterPropertiesSet();
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
NotificationListenerRegistrar registrar = new NotificationListenerRegistrar();
registrar.setServer(server);
registrar.setNotificationListener(listener);
registrar.setMappedObjectName(objectName);
registrar.afterPropertiesSet();
// update the attribute
String attributeName = "Name";
server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop"));
assertEquals("Listener not notified", 1, listener.getCount(attributeName));
registrar.destroy();
// try to update the attribute again
server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop"));
assertEquals("Listener notified after destruction", 1, listener.getCount(attributeName));
}
public void testNotificationListenerRegistrarWithMultipleNames() throws Exception {
ObjectName objectName = ObjectName.getInstance("spring:name=Test");
ObjectName objectName2 = ObjectName.getInstance("spring:name=Test2");
JmxTestBean bean = new JmxTestBean();
JmxTestBean bean2 = new JmxTestBean();
Map beans = new HashMap();
beans.put(objectName, bean);
beans.put(objectName2, bean2);
MBeanExporter exporter = new MBeanExporter();
exporter.setServer(server);
exporter.setBeans(beans);
exporter.afterPropertiesSet();
CountingAttributeChangeNotificationListener listener = new CountingAttributeChangeNotificationListener();
NotificationListenerRegistrar registrar = new NotificationListenerRegistrar();
registrar.setServer(server);
registrar.setNotificationListener(listener);
//registrar.setMappedObjectNames(new Object[] {objectName, objectName2});
registrar.setMappedObjectNames(new String[] {"spring:name=Test", "spring:name=Test2"});
registrar.afterPropertiesSet();
// update the attribute
String attributeName = "Name";
server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop"));
assertEquals("Listener not notified", 1, listener.getCount(attributeName));
registrar.destroy();
// try to update the attribute again
server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop"));
assertEquals("Listener notified after destruction", 1, listener.getCount(attributeName));
}
private static class CountingAttributeChangeNotificationListener implements NotificationListener {
private Map attributeCounts = new HashMap();
private Map attributeHandbacks = new HashMap();
public void handleNotification(Notification notification, Object handback) {
if (notification instanceof AttributeChangeNotification) {
AttributeChangeNotification attNotification = (AttributeChangeNotification) notification;
String attributeName = attNotification.getAttributeName();
Integer currentCount = (Integer) this.attributeCounts.get(attributeName);
if (currentCount != null) {
int count = currentCount.intValue() + 1;
this.attributeCounts.put(attributeName, new Integer(count));
}
else {
this.attributeCounts.put(attributeName, new Integer(1));
}
this.attributeHandbacks.put(attributeName, handback);
}
}
public int getCount(String attribute) {
Integer count = (Integer) this.attributeCounts.get(attribute);
return (count == null) ? 0 : count.intValue();
}
public Object getLastHandback(String attributeName) {
return this.attributeHandbacks.get(attributeName);
}
}
public static class SelfNamingTestBean implements SelfNaming {
private ObjectName objectName;
private int age;
public void setObjectName(ObjectName objectName) {
this.objectName = objectName;
}
public ObjectName getObjectName() throws MalformedObjectNameException {
return this.objectName;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return this.age;
}
}
}

View File

@@ -0,0 +1,206 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jmx.export;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.DynamicMBean;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanOperationInfo;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationListener;
import javax.management.ReflectionException;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.jmx.AbstractMBeanServerTests;
import org.springframework.jmx.export.notification.NotificationPublisher;
import org.springframework.jmx.export.notification.NotificationPublisherAware;
import org.springframework.jmx.support.ObjectNameManager;
/**
* Integration tests for the Spring JMX {@link NotificationPublisher} functionality.
*
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class NotificationPublisherTests extends AbstractMBeanServerTests {
private CountingNotificationListener listener = new CountingNotificationListener();
public void testSimpleBean() throws Exception {
// start the MBeanExporter
ConfigurableApplicationContext ctx = loadContext("org/springframework/jmx/export/notificationPublisherTests.xml");
this.server.addNotificationListener(ObjectNameManager.getInstance("spring:type=Publisher"), listener, null, null);
MyNotificationPublisher publisher = (MyNotificationPublisher) ctx.getBean("publisher");
assertNotNull("NotificationPublisher should not be null", publisher.getNotificationPublisher());
publisher.sendNotification();
assertEquals("Notification not sent", 1, listener.count);
}
public void testSimpleBeanRegisteredManually() throws Exception {
// start the MBeanExporter
ConfigurableApplicationContext ctx = loadContext("org/springframework/jmx/export/notificationPublisherTests.xml");
MBeanExporter exporter = (MBeanExporter) ctx.getBean("exporter");
MyNotificationPublisher publisher = new MyNotificationPublisher();
exporter.registerManagedResource(publisher, ObjectNameManager.getInstance("spring:type=Publisher2"));
this.server.addNotificationListener(ObjectNameManager.getInstance("spring:type=Publisher2"), listener, null, null);
assertNotNull("NotificationPublisher should not be null", publisher.getNotificationPublisher());
publisher.sendNotification();
assertEquals("Notification not sent", 1, listener.count);
}
public void testMBean() throws Exception {
// start the MBeanExporter
ConfigurableApplicationContext ctx = loadContext("org/springframework/jmx/export/notificationPublisherTests.xml");
this.server.addNotificationListener(ObjectNameManager.getInstance("spring:type=PublisherMBean"), listener, null, null);
MyNotificationPublisherMBean publisher = (MyNotificationPublisherMBean) ctx.getBean("publisherMBean");
publisher.sendNotification();
assertEquals("Notification not sent", 1, listener.count);
}
/*
public void testStandardMBean() throws Exception {
// start the MBeanExporter
ApplicationContext ctx = new ClassPathXmlApplicationContext("org/springframework/jmx/export/notificationPublisherTests.xml");
this.server.addNotificationListener(ObjectNameManager.getInstance("spring:type=PublisherStandardMBean"), listener, null, null);
MyNotificationPublisherStandardMBean publisher = (MyNotificationPublisherStandardMBean) ctx.getBean("publisherStandardMBean");
publisher.sendNotification();
assertEquals("Notification not sent", 1, listener.count);
}
*/
public void testLazyInit() throws Exception {
// start the MBeanExporter
ConfigurableApplicationContext ctx = loadContext("org/springframework/jmx/export/notificationPublisherLazyTests.xml");
assertFalse("Should not have instantiated the bean yet", ctx.getBeanFactory().containsSingleton("publisher"));
// need to touch the MBean proxy
server.getAttribute(ObjectNameManager.getInstance("spring:type=Publisher"), "Name");
this.server.addNotificationListener(ObjectNameManager.getInstance("spring:type=Publisher"), listener, null, null);
MyNotificationPublisher publisher = (MyNotificationPublisher) ctx.getBean("publisher");
assertNotNull("NotificationPublisher should not be null", publisher.getNotificationPublisher());
publisher.sendNotification();
assertEquals("Notification not sent", 1, listener.count);
}
private static class CountingNotificationListener implements NotificationListener {
private int count;
private Notification lastNotification;
public void handleNotification(Notification notification, Object handback) {
this.lastNotification = notification;
this.count++;
}
public int getCount() {
return count;
}
public Notification getLastNotification() {
return lastNotification;
}
}
public static class MyNotificationPublisher implements NotificationPublisherAware {
private NotificationPublisher notificationPublisher;
public void setNotificationPublisher(NotificationPublisher notificationPublisher) {
this.notificationPublisher = notificationPublisher;
}
public NotificationPublisher getNotificationPublisher() {
return notificationPublisher;
}
public void sendNotification() {
this.notificationPublisher.sendNotification(new Notification("test", this, 1));
}
public String getName() {
return "Rob Harrop";
}
}
public static class MyNotificationPublisherMBean extends NotificationBroadcasterSupport implements DynamicMBean {
public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException {
return null;
}
public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
}
public AttributeList getAttributes(String[] attributes) {
return null;
}
public AttributeList setAttributes(AttributeList attributes) {
return null;
}
public Object invoke(String actionName, Object params[], String signature[]) throws MBeanException, ReflectionException {
return null;
}
public MBeanInfo getMBeanInfo() {
return new MBeanInfo(
MyNotificationPublisherMBean.class.getName(), "",
new MBeanAttributeInfo[0],
new MBeanConstructorInfo[0],
new MBeanOperationInfo[0],
new MBeanNotificationInfo[0]);
}
public void sendNotification() {
sendNotification(new Notification("test", this, 1));
}
}
public static class MyNotificationPublisherStandardMBean extends NotificationBroadcasterSupport implements MyMBean {
public void sendNotification() {
sendNotification(new Notification("test", this, 1));
}
}
public interface MyMBean {
void sendNotification();
}
}

View File

@@ -0,0 +1,50 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export;
import javax.management.ObjectName;
import org.springframework.jmx.AbstractJmxTests;
import org.springframework.jmx.IJmxTestBean;
/**
* @author Rob Harrop
*/
public class PropertyPlaceholderConfigurerTests extends AbstractJmxTests {
protected String getApplicationContextPath() {
return "org/springframework/jmx/export/propertyPlaceholderConfigurer.xml";
}
public void testPropertiesReplaced() {
IJmxTestBean bean = (IJmxTestBean) getContext().getBean("testBean");
assertEquals("Name is incorrect", "Rob Harrop", bean.getName());
assertEquals("Age is incorrect", 100, bean.getAge());
}
public void testPropertiesCorrectInJmx() throws Exception {
ObjectName oname = new ObjectName("bean:name=proxyTestBean1");
Object name = getServer().getAttribute(oname, "Name");
Integer age = (Integer) getServer().getAttribute(oname, "Age");
assertEquals("Name is incorrect in JMX", "Rob Harrop", name);
assertEquals("Age is incorrect in JMX", 100, age.intValue());
}
}

View File

@@ -0,0 +1,80 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jmx.export;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.DynamicMBean;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanOperationInfo;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class TestDynamicMBean implements DynamicMBean {
public void setFailOnInit(boolean failOnInit) {
if (failOnInit) {
throw new IllegalArgumentException("Failing on initialization");
}
}
public Object getAttribute(String attribute) {
if ("Name".equals(attribute)) {
return "Rob Harrop";
}
return null;
}
public void setAttribute(Attribute attribute) {
}
public AttributeList getAttributes(String[] attributes) {
return null;
}
public AttributeList setAttributes(AttributeList attributes) {
return null;
}
public Object invoke(String actionName, Object[] params, String[] signature) {
return null;
}
public MBeanInfo getMBeanInfo() {
MBeanAttributeInfo attr = new MBeanAttributeInfo("name", "java.lang.String", "", true, false, false);
return new MBeanInfo(
TestDynamicMBean.class.getName(), "",
new MBeanAttributeInfo[]{attr},
new MBeanConstructorInfo[0],
new MBeanOperationInfo[0],
new MBeanNotificationInfo[0]);
}
public boolean equals(Object obj) {
return (obj instanceof TestDynamicMBean);
}
public int hashCode() {
return TestDynamicMBean.class.hashCode();
}
}

View File

@@ -0,0 +1,90 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export.annotation;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import junit.framework.TestCase;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jmx.support.ObjectNameManager;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class AnnotationLazyInitMBeanTests extends TestCase {
public void testLazyNaming() throws Exception {
ConfigurableApplicationContext ctx =
new ClassPathXmlApplicationContext("org/springframework/jmx/export/annotation/lazyNaming.xml");
try {
MBeanServer server = (MBeanServer) ctx.getBean("server");
ObjectName oname = ObjectNameManager.getInstance("bean:name=testBean4");
assertNotNull(server.getObjectInstance(oname));
String name = (String) server.getAttribute(oname, "Name");
assertEquals("Invalid name returned", "TEST", name);
}
finally {
ctx.close();
}
}
public void testLazyAssembling() throws Exception {
ConfigurableApplicationContext ctx =
new ClassPathXmlApplicationContext("org/springframework/jmx/export/annotation/lazyAssembling.xml");
try {
MBeanServer server = (MBeanServer) ctx.getBean("server");
ObjectName oname = ObjectNameManager.getInstance("bean:name=testBean4");
assertNotNull(server.getObjectInstance(oname));
String name = (String) server.getAttribute(oname, "Name");
assertEquals("Invalid name returned", "TEST", name);
oname = ObjectNameManager.getInstance("spring:mbean=true");
assertNotNull(server.getObjectInstance(oname));
name = (String) server.getAttribute(oname, "Name");
assertEquals("Invalid name returned", "Rob Harrop", name);
oname = ObjectNameManager.getInstance("spring:mbean=another");
assertNotNull(server.getObjectInstance(oname));
name = (String) server.getAttribute(oname, "Name");
assertEquals("Invalid name returned", "Juergen Hoeller", name);
}
finally {
ctx.close();
}
}
public void testComponentScan() throws Exception {
ConfigurableApplicationContext ctx =
new ClassPathXmlApplicationContext("org/springframework/jmx/export/annotation/componentScan.xml");
try {
MBeanServer server = (MBeanServer) ctx.getBean("server");
ObjectName oname = ObjectNameManager.getInstance("bean:name=testBean4");
assertNotNull(server.getObjectInstance(oname));
String name = (String) server.getAttribute(oname, "Name");
assertNull(name);
}
finally {
ctx.close();
}
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export.annotation;
import org.springframework.jmx.IJmxTestBean;
import org.springframework.jmx.export.assembler.AbstractMetadataAssemblerTests;
import org.springframework.jmx.export.metadata.JmxAttributeSource;
/**
* @author Rob Harrop
*/
public class AnnotationMetadataAssemblerTests extends AbstractMetadataAssemblerTests {
private static final String OBJECT_NAME = "bean:name=testBean4";
protected JmxAttributeSource getAttributeSource() {
return new AnnotationJmxAttributeSource();
}
protected String getObjectName() {
return OBJECT_NAME;
}
protected IJmxTestBean createJmxTestBean() {
return new AnnotationTestBean();
}
protected String getApplicationContextPath() {
return "org/springframework/jmx/export/annotation/annotations.xml";
}
}

View File

@@ -0,0 +1,101 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export.annotation;
import org.springframework.jmx.IJmxTestBean;
import org.springframework.stereotype.Service;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
@Service("testBean")
@ManagedResource(objectName = "bean:name=testBean4", description = "My Managed Bean", log = true,
logFile = "jmx.log", currencyTimeLimit = 15, persistPolicy = "OnUpdate", persistPeriod = 200,
persistLocation = "./foo", persistName = "bar.jmx")
@ManagedNotifications({@ManagedNotification(name="My Notification", notificationTypes={"type.foo", "type.bar"})})
public class AnnotationTestBean implements IJmxTestBean {
private String name;
private String nickName;
private int age;
private boolean isSuperman;
@ManagedAttribute(description = "The Age Attribute", currencyTimeLimit = 15)
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@ManagedOperation(currencyTimeLimit = 30)
public long myOperation() {
return 1L;
}
@ManagedAttribute(description = "The Name Attribute",
currencyTimeLimit = 20,
defaultValue = "bar",
persistPolicy = "OnUpdate")
public void setName(String name) {
this.name = name;
}
@ManagedAttribute(defaultValue = "foo", persistPeriod = 300)
public String getName() {
return name;
}
@ManagedAttribute(description = "The Nick Name Attribute")
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getNickName() {
return this.nickName;
}
public void setSuperman(boolean superman) {
this.isSuperman = superman;
}
@ManagedAttribute(description = "The Is Superman Attribute")
public boolean isSuperman() {
return isSuperman;
}
@org.springframework.jmx.export.annotation.ManagedOperation(description = "Add Two Numbers Together")
@ManagedOperationParameters({@ManagedOperationParameter(name="x", description="Left operand"),
@ManagedOperationParameter(name="y", description="Right operand")})
public int add(int x, int y) {
return x + y;
}
/**
* Test method that is not exposed by the MetadataAssembler.
*/
public void dontExposeMe() {
throw new RuntimeException();
}
}

View File

@@ -0,0 +1,77 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export.annotation;
import javax.management.MXBean;
import junit.framework.TestCase;
import org.springframework.core.JdkVersion;
import org.springframework.jmx.support.JmxUtils;
/**
* @author Juergen Hoeller
*/
public class JmxUtilsAnnotationTests extends TestCase {
public void testNotMXBean() throws Exception {
if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_16) {
return;
}
FooNotX foo = new FooNotX();
assertFalse("MXBean annotation not detected correctly", JmxUtils.isMBean(foo.getClass()));
}
public void testAnnotatedMXBean() throws Exception {
if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_16) {
return;
}
FooX foo = new FooX();
assertTrue("MXBean annotation not detected correctly", JmxUtils.isMBean(foo.getClass()));
}
@MXBean(false)
public static interface FooNotMXBean {
String getName();
}
public static class FooNotX implements FooNotMXBean {
public String getName() {
return "Rob Harrop";
}
}
@MXBean(true)
public static interface FooIfc {
String getName();
}
public static class FooX implements FooIfc {
public String getName() {
return "Rob Harrop";
}
}
}

View File

@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="jmxAdapter" class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<map>
<entry key="namingTest">
<ref local="testBean"/>
</entry>
</map>
</property>
<property name="assembler">
<ref local="metadataAssembler"/>
</property>
<property name="namingStrategy">
<ref local="metadataNamingStrategy"/>
</property>
</bean>
<bean id="testBean" class="org.springframework.jmx.export.annotation.AnnotationTestBean">
<property name="name">
<value>TEST</value>
</property>
<property name="age">
<value>100</value>
</property>
</bean>
<bean id="attributeSource" class="org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource"/>
<bean id="metadataNamingStrategy" class="org.springframework.jmx.export.naming.MetadataNamingStrategy">
<property name="attributeSource">
<ref bean="attributeSource"/>
</property>
</bean>
<bean id="metadataAssembler" class="org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler">
<property name="attributeSource">
<ref bean="attributeSource"/>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,14 @@
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:mbean-export server="server"/>
<bean id="server" class="org.springframework.jmx.support.MBeanServerFactoryBean"/>
<context:component-scan base-package="org.springframework.jmx.export.annotation"/>
</beans>

View File

@@ -0,0 +1,25 @@
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:mbean-export server="server" registration="replaceExisting"/>
<context:mbean-export server="server" registration="replaceExisting"/>
<bean id="server" class="org.springframework.jmx.support.MBeanServerFactoryBean"/>
<bean name="bean:name=testBean4" class="org.springframework.jmx.export.annotation.AnnotationTestBean" lazy-init="true">
<property name="name" value="TEST"/>
<property name="age" value="100"/>
</bean>
<bean name="spring:mbean=true" class="org.springframework.jmx.export.TestDynamicMBean" lazy-init="true"/>
<bean name="spring:mbean=another" class="org.springframework.jmx.export.MBeanExporterTests$Person" lazy-init="true">
<property name="name" value="Juergen Hoeller"/>
</bean>
</beans>

View File

@@ -0,0 +1,17 @@
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:mbean-export server="server"/>
<bean id="server" class="org.springframework.jmx.support.MBeanServerFactoryBean"/>
<bean id="testBean" class="org.springframework.jmx.export.annotation.AnnotationTestBean" lazy-init="true">
<property name="name" value="TEST"/>
<property name="age" value="100"/>
</bean>
</beans>

View File

@@ -0,0 +1,37 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export.assembler;
import junit.framework.TestCase;
import org.springframework.jmx.JmxTestBean;
/**
* @author Rob Harrop
*/
public abstract class AbstractAutodetectTests extends TestCase {
public void testAutodetect() throws Exception {
JmxTestBean bean = new JmxTestBean();
AutodetectCapableMBeanInfoAssembler assembler = getAssembler();
assertTrue("The bean should be included", assembler.includeBean(bean.getClass(), "testBean"));
}
protected abstract AutodetectCapableMBeanInfoAssembler getAssembler();
}

View File

@@ -0,0 +1,198 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export.assembler;
import javax.management.Attribute;
import javax.management.Descriptor;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanOperationInfo;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.modelmbean.ModelMBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanInfo;
import javax.management.modelmbean.ModelMBeanOperationInfo;
import org.springframework.jmx.AbstractJmxTests;
import org.springframework.jmx.IJmxTestBean;
import org.springframework.jmx.support.ObjectNameManager;
/**
* @author Rob Harrop
*/
public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests {
protected static final String AGE_ATTRIBUTE = "Age";
protected static final String NAME_ATTRIBUTE = "Name";
protected abstract String getObjectName();
public void testMBeanRegistration() throws Exception {
// beans are registered at this point - just grab them from the server
ObjectInstance instance = getObjectInstance();
assertNotNull("Bean should not be null", instance);
}
public void testRegisterOperations() throws Exception {
IJmxTestBean bean = getBean();
MBeanInfo inf = getMBeanInfo();
assertEquals("Incorrect number of operations registered",
getExpectedOperationCount(), inf.getOperations().length);
}
public void testRegisterAttributes() throws Exception {
IJmxTestBean bean = getBean();
MBeanInfo inf = getMBeanInfo();
assertEquals("Incorrect number of attributes registered",
getExpectedAttributeCount(), inf.getAttributes().length);
}
public void testGetMBeanInfo() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
assertNotNull("MBeanInfo should not be null", info);
}
public void testGetMBeanAttributeInfo() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
MBeanAttributeInfo[] inf = info.getAttributes();
assertEquals("Invalid number of Attributes returned",
getExpectedAttributeCount(), inf.length);
for (int x = 0; x < inf.length; x++) {
assertNotNull("MBeanAttributeInfo should not be null", inf[x]);
assertNotNull(
"Description for MBeanAttributeInfo should not be null",
inf[x].getDescription());
}
}
public void testGetMBeanOperationInfo() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
MBeanOperationInfo[] inf = info.getOperations();
assertEquals("Invalid number of Operations returned",
getExpectedOperationCount(), inf.length);
for (int x = 0; x < inf.length; x++) {
assertNotNull("MBeanOperationInfo should not be null", inf[x]);
assertNotNull(
"Description for MBeanOperationInfo should not be null",
inf[x].getDescription());
}
}
public void testDescriptionNotNull() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
assertNotNull("The MBean description should not be null",
info.getDescription());
}
public void testSetAttribute() throws Exception {
ObjectName objectName = ObjectNameManager.getInstance(getObjectName());
getServer().setAttribute(objectName, new Attribute(NAME_ATTRIBUTE, "Rob Harrop"));
IJmxTestBean bean = (IJmxTestBean) getContext().getBean("testBean");
assertEquals("Rob Harrop", bean.getName());
}
public void testGetAttribute() throws Exception {
ObjectName objectName = ObjectNameManager.getInstance(getObjectName());
getBean().setName("John Smith");
Object val = getServer().getAttribute(objectName, NAME_ATTRIBUTE);
assertEquals("Incorrect result", "John Smith", val);
}
public void testOperationInvocation() throws Exception{
ObjectName objectName = ObjectNameManager.getInstance(getObjectName());
Object result = getServer().invoke(objectName, "add",
new Object[] {new Integer(20), new Integer(30)}, new String[] {"int", "int"});
assertEquals("Incorrect result", new Integer(50), result);
}
public void testAttributeInfoHasDescriptors() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
ModelMBeanAttributeInfo attr = info.getAttribute(NAME_ATTRIBUTE);
Descriptor desc = attr.getDescriptor();
assertNotNull("getMethod field should not be null",
desc.getFieldValue("getMethod"));
assertNotNull("setMethod field should not be null",
desc.getFieldValue("setMethod"));
assertEquals("getMethod field has incorrect value", "getName",
desc.getFieldValue("getMethod"));
assertEquals("setMethod field has incorrect value", "setName",
desc.getFieldValue("setMethod"));
}
public void testAttributeHasCorrespondingOperations() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
ModelMBeanOperationInfo get = info.getOperation("getName");
assertNotNull("get operation should not be null", get);
assertEquals("get operation should have visibility of four",
(Integer) get.getDescriptor().getFieldValue("visibility"),
new Integer(4));
assertEquals("get operation should have role \"getter\"", "getter", get.getDescriptor().getFieldValue("role"));
ModelMBeanOperationInfo set = info.getOperation("setName");
assertNotNull("set operation should not be null", set);
assertEquals("set operation should have visibility of four",
(Integer) set.getDescriptor().getFieldValue("visibility"),
new Integer(4));
assertEquals("set operation should have role \"setter\"", "setter", set.getDescriptor().getFieldValue("role"));
}
public void testNotificationMetadata() throws Exception {
ModelMBeanInfo info = (ModelMBeanInfo) getMBeanInfo();
MBeanNotificationInfo[] notifications = info.getNotifications();
assertEquals("Incorrect number of notifications", 1, notifications.length);
assertEquals("Incorrect notification name", "My Notification", notifications[0].getName());
String[] notifTypes = notifications[0].getNotifTypes();
assertEquals("Incorrect number of notification types", 2, notifTypes.length);
assertEquals("Notification type.foo not found", "type.foo", notifTypes[0]);
assertEquals("Notification type.bar not found", "type.bar", notifTypes[1]);
}
protected ModelMBeanInfo getMBeanInfoFromAssembler() throws Exception {
IJmxTestBean bean = getBean();
ModelMBeanInfo info = getAssembler().getMBeanInfo(bean, getObjectName());
return info;
}
protected IJmxTestBean getBean() {
Object bean = getContext().getBean("testBean");
return (IJmxTestBean) bean;
}
protected MBeanInfo getMBeanInfo() throws Exception {
return getServer().getMBeanInfo(ObjectNameManager.getInstance(getObjectName()));
}
protected ObjectInstance getObjectInstance() throws Exception {
return getServer().getObjectInstance(ObjectNameManager.getInstance(getObjectName()));
}
protected abstract int getExpectedOperationCount();
protected abstract int getExpectedAttributeCount();
protected abstract MBeanInfoAssembler getAssembler() throws Exception;
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export.assembler;
import org.springframework.jmx.export.metadata.JmxAttributeSource;
/**
* @author Rob Harrop
*/
public abstract class AbstractMetadataAssemblerAutodetectTests extends AbstractAutodetectTests {
protected AutodetectCapableMBeanInfoAssembler getAssembler() {
MetadataMBeanInfoAssembler assembler = new MetadataMBeanInfoAssembler();
assembler.setAttributeSource(getAttributeSource());
return assembler;
}
protected abstract JmxAttributeSource getAttributeSource();
}

View File

@@ -0,0 +1,189 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export.assembler;
import java.util.HashMap;
import java.util.Map;
import javax.management.Descriptor;
import javax.management.MBeanInfo;
import javax.management.MBeanParameterInfo;
import javax.management.modelmbean.ModelMBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanInfo;
import javax.management.modelmbean.ModelMBeanOperationInfo;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.interceptor.NopInterceptor;
import org.springframework.jmx.IJmxTestBean;
import org.springframework.jmx.JmxTestBean;
import org.springframework.jmx.export.MBeanExporter;
import org.springframework.jmx.export.metadata.JmxAttributeSource;
import org.springframework.jmx.support.ObjectNameManager;
/**
* @author Rob Harrop
*/
public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemblerTests {
public void testDescription() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
assertEquals("The descriptions are not the same", "My Managed Bean",
info.getDescription());
}
public void testAttributeDescriptionOnSetter() throws Exception {
ModelMBeanInfo inf = getMBeanInfoFromAssembler();
ModelMBeanAttributeInfo attr = inf.getAttribute(AGE_ATTRIBUTE);
assertEquals("The description for the age attribute is incorrect",
"The Age Attribute", attr.getDescription());
}
public void testAttributeDescriptionOnGetter() throws Exception {
ModelMBeanInfo inf = getMBeanInfoFromAssembler();
ModelMBeanAttributeInfo attr = inf.getAttribute(NAME_ATTRIBUTE);
assertEquals("The description for the name attribute is incorrect",
"The Name Attribute", attr.getDescription());
}
/**
* Tests the situation where the attribute is only defined on the getter.
*/
public void testReadOnlyAttribute() throws Exception {
ModelMBeanInfo inf = getMBeanInfoFromAssembler();
ModelMBeanAttributeInfo attr = inf.getAttribute(AGE_ATTRIBUTE);
assertFalse("The age attribute should not be writable", attr.isWritable());
}
public void testReadWriteAttribute() throws Exception {
ModelMBeanInfo inf = getMBeanInfoFromAssembler();
ModelMBeanAttributeInfo attr = inf.getAttribute(NAME_ATTRIBUTE);
assertTrue("The name attribute should be writable", attr.isWritable());
assertTrue("The name attribute should be readable", attr.isReadable());
}
/**
* Tests the situation where the property only has a getter.
*/
public void testWithOnlySetter() throws Exception {
ModelMBeanInfo inf = getMBeanInfoFromAssembler();
ModelMBeanAttributeInfo attr = inf.getAttribute("NickName");
assertNotNull("Attribute should not be null", attr);
}
/**
* Tests the situation where the property only has a setter.
*/
public void testWithOnlyGetter() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
ModelMBeanAttributeInfo attr = info.getAttribute("Superman");
assertNotNull("Attribute should not be null", attr);
}
public void testManagedResourceDescriptor() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
Descriptor desc = info.getMBeanDescriptor();
assertEquals("Logging should be set to true", "true", desc.getFieldValue("log"));
assertEquals("Log file should be jmx.log", "jmx.log", desc.getFieldValue("logFile"));
assertEquals("Currency Time Limit should be 15", "15", desc.getFieldValue("currencyTimeLimit"));
assertEquals("Persist Policy should be OnUpdate", "OnUpdate", desc.getFieldValue("persistPolicy"));
assertEquals("Persist Period should be 200", "200", desc.getFieldValue("persistPeriod"));
assertEquals("Persist Location should be foo", "./foo", desc.getFieldValue("persistLocation"));
assertEquals("Persist Name should be bar", "bar.jmx", desc.getFieldValue("persistName"));
}
public void testAttributeDescriptor() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
Descriptor desc = info.getAttribute(NAME_ATTRIBUTE).getDescriptor();
assertEquals("Default value should be foo", "foo", desc.getFieldValue("default"));
assertEquals("Currency Time Limit should be 20", "20", desc.getFieldValue("currencyTimeLimit"));
assertEquals("Persist Policy should be OnUpdate", "OnUpdate", desc.getFieldValue("persistPolicy"));
assertEquals("Persist Period should be 300", "300", desc.getFieldValue("persistPeriod"));
}
public void testOperationDescriptor() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
Descriptor desc = info.getOperation("myOperation").getDescriptor();
assertEquals("Currency Time Limit should be 30", "30", desc.getFieldValue("currencyTimeLimit"));
assertEquals("Role should be \"operation\"", "operation", desc.getFieldValue("role"));
}
public void testOperationParameterMetadata() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
ModelMBeanOperationInfo oper = info.getOperation("add");
MBeanParameterInfo[] params = oper.getSignature();
assertEquals("Invalid number of params", 2, params.length);
assertEquals("Incorrect name for x param", "x", params[0].getName());
assertEquals("Incorrect type for x param", int.class.getName(), params[0].getType());
assertEquals("Incorrect name for y param", "y", params[1].getName());
assertEquals("Incorrect type for y param", int.class.getName(), params[1].getType());
}
public void testWithCglibProxy() throws Exception {
IJmxTestBean tb = createJmxTestBean();
ProxyFactory pf = new ProxyFactory();
pf.setTarget(tb);
pf.addAdvice(new NopInterceptor());
Object proxy = pf.getProxy();
MetadataMBeanInfoAssembler assembler = (MetadataMBeanInfoAssembler) getAssembler();
MBeanExporter exporter = new MBeanExporter();
exporter.setBeanFactory(getContext());
exporter.setAssembler(assembler);
String objectName = "spring:bean=test,proxy=true";
Map beans = new HashMap();
beans.put(objectName, proxy);
exporter.setBeans(beans);
exporter.afterPropertiesSet();
MBeanInfo inf = getServer().getMBeanInfo(ObjectNameManager.getInstance(objectName));
assertEquals("Incorrect number of operations", getExpectedOperationCount(), inf.getOperations().length);
assertEquals("Incorrect number of attributes", getExpectedAttributeCount(), inf.getAttributes().length);
assertTrue("Not included in autodetection", assembler.includeBean(proxy.getClass(), "some bean name"));
}
protected abstract String getObjectName();
protected int getExpectedAttributeCount() {
return 4;
}
protected int getExpectedOperationCount() {
return 7;
}
protected IJmxTestBean createJmxTestBean() {
return new JmxTestBean();
}
protected MBeanInfoAssembler getAssembler() {
MetadataMBeanInfoAssembler assembler = new MetadataMBeanInfoAssembler();
assembler.setAttributeSource(getAttributeSource());
return assembler;
}
protected abstract JmxAttributeSource getAttributeSource();
}

View File

@@ -0,0 +1,13 @@
package org.springframework.jmx.export.assembler;
/**
* @author Rob Harrop
*/
public interface IAdditionalTestMethods {
String getNickName();
void setNickName(String nickName);
}

View File

@@ -0,0 +1,28 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export.assembler;
/**
* @author Juergen Hoeller
*/
public interface ICustomBase {
int add(int x, int y);
long myOperation();
}

View File

@@ -0,0 +1,30 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export.assembler;
/**
* @author Rob Harrop
*/
public interface ICustomJmxBean extends ICustomBase {
String getName();
void setName(String name);
int getAge();
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export.assembler;
import javax.management.modelmbean.ModelMBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanInfo;
import org.junit.Ignore;
/**
* @author Rob Harrop
*/
@Ignore
public class InterfaceBasedMBeanInfoAssemblerCustomTests extends AbstractJmxAssemblerTests {
protected static final String OBJECT_NAME = "bean:name=testBean5";
protected String getObjectName() {
return OBJECT_NAME;
}
protected int getExpectedOperationCount() {
return 5;
}
protected int getExpectedAttributeCount() {
return 2;
}
protected MBeanInfoAssembler getAssembler() {
InterfaceBasedMBeanInfoAssembler assembler = new InterfaceBasedMBeanInfoAssembler();
assembler.setManagedInterfaces(new Class[] {ICustomJmxBean.class});
return assembler;
}
public void testGetAgeIsReadOnly() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE);
assertTrue(attr.isReadable());
assertFalse(attr.isWritable());
}
protected String getApplicationContextPath() {
return "org/springframework/jmx/export/assembler/interfaceAssemblerCustom.xml";
}
}

View File

@@ -0,0 +1,122 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jmx.export.assembler;
import java.util.Properties;
import javax.management.MBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanInfo;
import org.junit.Ignore;
/**
* @author Rob Harrop
*/
public class InterfaceBasedMBeanInfoAssemblerMappedTests extends AbstractJmxAssemblerTests {
protected static final String OBJECT_NAME = "bean:name=testBean4";
public void testGetAgeIsReadOnly() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE);
assertTrue("Age is not readable", attr.isReadable());
assertFalse("Age is not writable", attr.isWritable());
}
public void testWithUnknownClass() throws Exception {
try {
InterfaceBasedMBeanInfoAssembler assembler = getWithMapping("com.foo.bar.Unknown");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
}
public void testWithNonInterface() throws Exception {
try {
InterfaceBasedMBeanInfoAssembler assembler = getWithMapping("JmxTestBean");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
}
@Ignore
public void ignoreTestWithFallThrough() throws Exception {
InterfaceBasedMBeanInfoAssembler assembler =
getWithMapping("foobar", "org.springframework.jmx.export.assembler.ICustomJmxBean");
assembler.setManagedInterfaces(new Class[] {IAdditionalTestMethods.class});
ModelMBeanInfo inf = assembler.getMBeanInfo(getBean(), getObjectName());
MBeanAttributeInfo attr = inf.getAttribute("NickName");
assertNickName(attr);
}
public void testNickNameIsExposed() throws Exception {
ModelMBeanInfo inf = (ModelMBeanInfo) getMBeanInfo();
MBeanAttributeInfo attr = inf.getAttribute("NickName");
assertNickName(attr);
}
protected String getObjectName() {
return OBJECT_NAME;
}
protected int getExpectedOperationCount() {
return 7;
}
protected int getExpectedAttributeCount() {
return 3;
}
protected MBeanInfoAssembler getAssembler() throws Exception {
return getWithMapping(
"org.springframework.jmx.export.assembler.IAdditionalTestMethods, " +
"org.springframework.jmx.export.assembler.ICustomJmxBean");
}
protected String getApplicationContextPath() {
return "org/springframework/jmx/export/assembler/interfaceAssemblerMapped.xml";
}
private InterfaceBasedMBeanInfoAssembler getWithMapping(String mapping) {
return getWithMapping(OBJECT_NAME, mapping);
}
private InterfaceBasedMBeanInfoAssembler getWithMapping(String name, String mapping) {
InterfaceBasedMBeanInfoAssembler assembler = new InterfaceBasedMBeanInfoAssembler();
Properties props = new Properties();
props.setProperty(name, mapping);
assembler.setInterfaceMappings(props);
assembler.afterPropertiesSet();
return assembler;
}
private void assertNickName(MBeanAttributeInfo attr) {
assertNotNull("Nick Name should not be null", attr);
assertTrue("Nick Name should be writable", attr.isWritable());
assertTrue("Nick Name should be readab;e", attr.isReadable());
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export.assembler;
/**
* @author Rob Harrop
*/
public class InterfaceBasedMBeanInfoAssemblerTests extends AbstractJmxAssemblerTests {
protected String getObjectName() {
return "bean:name=testBean4";
}
protected int getExpectedOperationCount() {
return 7;
}
protected int getExpectedAttributeCount() {
return 2;
}
protected MBeanInfoAssembler getAssembler() {
return new InterfaceBasedMBeanInfoAssembler();
}
protected String getApplicationContextPath() {
return "org/springframework/jmx/export/assembler/interfaceAssembler.xml";
}
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jmx.export.assembler;
import java.util.Properties;
import javax.management.MBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanInfo;
/**
* @author Juergen Hoeller
* @author Rob Harrop
*/
public class MethodExclusionMBeanInfoAssemblerComboTests extends AbstractJmxAssemblerTests {
protected static final String OBJECT_NAME = "bean:name=testBean4";
public void testGetAgeIsReadOnly() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE);
assertTrue("Age is not readable", attr.isReadable());
assertFalse("Age is not writable", attr.isWritable());
}
public void testNickNameIsExposed() throws Exception {
ModelMBeanInfo inf = (ModelMBeanInfo) getMBeanInfo();
MBeanAttributeInfo attr = inf.getAttribute("NickName");
assertNotNull("Nick Name should not be null", attr);
assertTrue("Nick Name should be writable", attr.isWritable());
assertTrue("Nick Name should be readable", attr.isReadable());
}
protected String getObjectName() {
return OBJECT_NAME;
}
protected int getExpectedOperationCount() {
return 7;
}
protected int getExpectedAttributeCount() {
return 3;
}
protected String getApplicationContextPath() {
return "org/springframework/jmx/export/assembler/methodExclusionAssemblerCombo.xml";
}
protected MBeanInfoAssembler getAssembler() throws Exception {
MethodExclusionMBeanInfoAssembler assembler = new MethodExclusionMBeanInfoAssembler();
Properties props = new Properties();
props.setProperty(OBJECT_NAME, "setAge,isSuperman,setSuperman,dontExposeMe");
assembler.setIgnoredMethodMappings(props);
assembler.setIgnoredMethods(new String[] {"someMethod"});
return assembler;
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jmx.export.assembler;
import java.util.Properties;
import javax.management.MBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanInfo;
/**
* @author Rob Harrop
*/
public class MethodExclusionMBeanInfoAssemblerMappedTests extends AbstractJmxAssemblerTests {
protected static final String OBJECT_NAME = "bean:name=testBean4";
public void testGetAgeIsReadOnly() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE);
assertTrue("Age is not readable", attr.isReadable());
assertFalse("Age is not writable", attr.isWritable());
}
public void testNickNameIsExposed() throws Exception {
ModelMBeanInfo inf = (ModelMBeanInfo) getMBeanInfo();
MBeanAttributeInfo attr = inf.getAttribute("NickName");
assertNotNull("Nick Name should not be null", attr);
assertTrue("Nick Name should be writable", attr.isWritable());
assertTrue("Nick Name should be readable", attr.isReadable());
}
protected String getObjectName() {
return OBJECT_NAME;
}
protected int getExpectedOperationCount() {
return 7;
}
protected int getExpectedAttributeCount() {
return 3;
}
protected String getApplicationContextPath() {
return "org/springframework/jmx/export/assembler/methodExclusionAssemblerMapped.xml";
}
protected MBeanInfoAssembler getAssembler() throws Exception {
MethodExclusionMBeanInfoAssembler assembler = new MethodExclusionMBeanInfoAssembler();
Properties props = new Properties();
props.setProperty(OBJECT_NAME, "setAge,isSuperman,setSuperman,dontExposeMe");
assembler.setIgnoredMethodMappings(props);
return assembler;
}
}

View File

@@ -0,0 +1,72 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jmx.export.assembler;
import java.util.Properties;
import javax.management.MBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanInfo;
/**
* @author Juergen Hoeller
* @author Rob Harrop
*/
public class MethodExclusionMBeanInfoAssemblerNotMappedTests extends AbstractJmxAssemblerTests {
protected static final String OBJECT_NAME = "bean:name=testBean4";
public void testGetAgeIsReadOnly() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE);
assertTrue("Age is not readable", attr.isReadable());
assertTrue("Age is not writable", attr.isWritable());
}
public void testNickNameIsExposed() throws Exception {
ModelMBeanInfo inf = (ModelMBeanInfo) getMBeanInfo();
MBeanAttributeInfo attr = inf.getAttribute("NickName");
assertNotNull("Nick Name should not be null", attr);
assertTrue("Nick Name should be writable", attr.isWritable());
assertTrue("Nick Name should be readable", attr.isReadable());
}
protected String getObjectName() {
return OBJECT_NAME;
}
protected int getExpectedOperationCount() {
return 11;
}
protected int getExpectedAttributeCount() {
return 4;
}
protected String getApplicationContextPath() {
return "org/springframework/jmx/export/assembler/methodExclusionAssemblerNotMapped.xml";
}
protected MBeanInfoAssembler getAssembler() throws Exception {
MethodExclusionMBeanInfoAssembler assembler = new MethodExclusionMBeanInfoAssembler();
Properties props = new Properties();
props.setProperty("bean:name=testBean5", "setAge,isSuperman,setSuperman,dontExposeMe");
assembler.setIgnoredMethodMappings(props);
return assembler;
}
}

View File

@@ -0,0 +1,81 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jmx.export.assembler;
import java.lang.reflect.Method;
import java.util.Properties;
import javax.management.modelmbean.ModelMBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanInfo;
import org.springframework.jmx.JmxTestBean;
/**
* @author Rob Harrop
* @author Rick Evans
*/
public class MethodExclusionMBeanInfoAssemblerTests extends AbstractJmxAssemblerTests {
private static final String OBJECT_NAME = "bean:name=testBean5";
protected String getObjectName() {
return OBJECT_NAME;
}
protected int getExpectedOperationCount() {
return 9;
}
protected int getExpectedAttributeCount() {
return 4;
}
protected String getApplicationContextPath() {
return "org/springframework/jmx/export/assembler/methodExclusionAssembler.xml";
}
protected MBeanInfoAssembler getAssembler() {
MethodExclusionMBeanInfoAssembler assembler = new MethodExclusionMBeanInfoAssembler();
assembler.setIgnoredMethods(new String[] {"dontExposeMe", "setSuperman"});
return assembler;
}
public void testSupermanIsReadOnly() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
ModelMBeanAttributeInfo attr = info.getAttribute("Superman");
assertTrue(attr.isReadable());
assertFalse(attr.isWritable());
}
/*
* http://opensource.atlassian.com/projects/spring/browse/SPR-2754
*/
public void testIsNotIgnoredDoesntIgnoreUnspecifiedBeanMethods() throws Exception {
final String beanKey = "myTestBean";
MethodExclusionMBeanInfoAssembler assembler = new MethodExclusionMBeanInfoAssembler();
Properties ignored = new Properties();
ignored.setProperty(beanKey, "dontExposeMe,setSuperman");
assembler.setIgnoredMethodMappings(ignored);
Method method = JmxTestBean.class.getMethod("dontExposeMe", null);
assertFalse(assembler.isNotIgnored(method, beanKey));
// this bean does not have any ignored methods on it, so must obviously not be ignored...
assertTrue(assembler.isNotIgnored(method, "someOtherBeanKey"));
}
}

View File

@@ -0,0 +1,95 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export.assembler;
import javax.management.MBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanInfo;
import java.util.Properties;
/**
* @author Rob Harrop
*/
public class MethodNameBasedMBeanInfoAssemblerMappedTests extends AbstractJmxAssemblerTests {
protected static final String OBJECT_NAME = "bean:name=testBean4";
public void testGetAgeIsReadOnly() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE);
assertTrue("Age is not readable", attr.isReadable());
assertFalse("Age is not writable", attr.isWritable());
}
public void testWithFallThrough() throws Exception {
MethodNameBasedMBeanInfoAssembler assembler =
getWithMapping("foobar", "add,myOperation,getName,setName,getAge");
assembler.setManagedMethods(new String[]{"getNickName", "setNickName"});
ModelMBeanInfo inf = assembler.getMBeanInfo(getBean(), getObjectName());
MBeanAttributeInfo attr = inf.getAttribute("NickName");
assertNickName(attr);
}
public void testNickNameIsExposed() throws Exception {
ModelMBeanInfo inf = (ModelMBeanInfo) getMBeanInfo();
MBeanAttributeInfo attr = inf.getAttribute("NickName");
assertNickName(attr);
}
protected String getObjectName() {
return OBJECT_NAME;
}
protected int getExpectedOperationCount() {
return 7;
}
protected int getExpectedAttributeCount() {
return 3;
}
protected MBeanInfoAssembler getAssembler() throws Exception {
return getWithMapping("getNickName,setNickName,add,myOperation,getName,setName,getAge");
}
protected String getApplicationContextPath() {
return "org/springframework/jmx/export/assembler/methodNameAssemblerMapped.xml";
}
private MethodNameBasedMBeanInfoAssembler getWithMapping(String mapping) {
return getWithMapping(OBJECT_NAME, mapping);
}
private MethodNameBasedMBeanInfoAssembler getWithMapping(String name, String mapping) {
MethodNameBasedMBeanInfoAssembler assembler = new MethodNameBasedMBeanInfoAssembler();
Properties props = new Properties();
props.setProperty(name, mapping);
assembler.setMethodMappings(props);
return assembler;
}
private void assertNickName(MBeanAttributeInfo attr) {
assertNotNull("Nick Name should not be null", attr);
assertTrue("Nick Name should be writable", attr.isWritable());
assertTrue("Nick Name should be readable", attr.isReadable());
}
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export.assembler;
import javax.management.modelmbean.ModelMBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanInfo;
/**
* @author Rob Harrop
*/
public class MethodNameBasedMBeanInfoAssemblerTests extends AbstractJmxAssemblerTests {
protected static final String OBJECT_NAME = "bean:name=testBean5";
protected String getObjectName() {
return OBJECT_NAME;
}
protected int getExpectedOperationCount() {
return 5;
}
protected int getExpectedAttributeCount() {
return 2;
}
protected MBeanInfoAssembler getAssembler() {
MethodNameBasedMBeanInfoAssembler assembler = new MethodNameBasedMBeanInfoAssembler();
assembler.setManagedMethods(new String[] {"add", "myOperation", "getName", "setName", "getAge"});
return assembler;
}
public void testGetAgeIsReadOnly() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE);
assertTrue(attr.isReadable());
assertFalse(attr.isWritable());
}
protected String getApplicationContextPath() {
return "org/springframework/jmx/export/assembler/methodNameAssembler.xml";
}
}

View File

@@ -0,0 +1,49 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export.assembler;
/**
* @author Rob Harrop
*/
public class ReflectiveAssemblerTests extends AbstractJmxAssemblerTests {
protected static final String OBJECT_NAME = "bean:name=testBean1";
protected String getObjectName() {
return OBJECT_NAME;
}
protected int getExpectedOperationCount() {
return 11;
}
protected int getExpectedAttributeCount() {
return 4;
}
protected MBeanInfoAssembler getAssembler() {
return new SimpleReflectiveMBeanInfoAssembler();
}
protected String getApplicationContextPath() {
return "org/springframework/jmx/export/assembler/reflectiveAssembler.xml";
}
}

View File

@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="org.springframework.jmx.export.MBeanExporter" autowire="byName">
<property name="beans">
<map>
<entry key="bean:name=testBean4">
<ref local="testBean"/>
</entry>
</map>
</property>
<property name="assembler">
<bean class="org.springframework.jmx.export.assembler.InterfaceBasedMBeanInfoAssembler">
<property name="notificationInfoMappings">
<map>
<entry key="bean:name=testBean4">
<list>
<bean class="org.springframework.jmx.export.metadata.ManagedNotification">
<property name="name" value="My Notification"/>
<property name="description" value="A Notification"/>
<property name="notificationTypes" value="type.foo,type.bar"/>
</bean>
</list>
</entry>
</map>
</property>
</bean>
</property>
</bean>
<bean id="testBean" class="org.springframework.jmx.JmxTestBean">
<property name="name">
<value>TEST</value>
</property>
<property name="age">
<value>100</value>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="org.springframework.jmx.export.MBeanExporter" autowire="byName">
<property name="beans">
<map>
<entry key="bean:name=testBean5">
<ref local="testBean"/>
</entry>
</map>
</property>
<property name="assembler">
<bean class="org.springframework.jmx.export.assembler.InterfaceBasedMBeanInfoAssembler">
<property name="managedInterfaces">
<value>org.springframework.jmx.export.assembler.ICustomJmxBean</value>
</property>
<property name="notificationInfos">
<bean class="org.springframework.jmx.export.metadata.ManagedNotification">
<property name="name" value="My Notification"/>
<property name="description" value="A Notification"/>
<property name="notificationTypes" value="type.foo,type.bar"/>
</bean>
</property>
</bean>
</property>
</bean>
<bean id="testBean" class="org.springframework.jmx.JmxTestBean">
<property name="name">
<value>TEST</value>
</property>
<property name="age">
<value>100</value>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="org.springframework.jmx.export.MBeanExporter" autowire="byName">
<property name="beans">
<map>
<entry key="bean:name=testBean4">
<ref local="testBean"/>
</entry>
</map>
</property>
<property name="assembler">
<bean class="org.springframework.jmx.export.assembler.InterfaceBasedMBeanInfoAssembler">
<property name="interfaceMappings">
<props>
<prop key="bean:name=testBean4">
org.springframework.jmx.export.assembler.IAdditionalTestMethods,
org.springframework.jmx.export.assembler.ICustomJmxBean
</prop>
</props>
</property>
<property name="notificationInfos">
<bean class="org.springframework.jmx.export.metadata.ManagedNotification">
<property name="name" value="My Notification"/>
<property name="description" value="A Notification"/>
<property name="notificationTypes" value="type.foo,type.bar"/>
</bean>
</property>
</bean>
</property>
</bean>
<bean id="testBean" class="org.springframework.jmx.JmxTestBean">
<property name="name">
<value>TEST</value>
</property>
<property name="age">
<value>100</value>
</property>
</bean>
</beans
>

View File

@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="jmxAdapter" class="org.springframework.jmx.export.MBeanExporter">
<property name="assembler">
<ref local="metadataAssembler"/>
</property>
<property name="namingStrategy">
<ref local="namingStrategy"/>
</property>
</bean>
<bean id="testBean" class="org.springframework.jmx.JmxTestBean">
<property name="name">
<value>TEST</value>
</property>
<property name="age">
<value>100</value>
</property>
</bean>
<bean id="metadataAssembler" class="org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler">
<property name="attributeSource">
<ref local="attributeSource"/>
</property>
</bean>
<bean id="namingStrategy" class="org.springframework.jmx.export.naming.MetadataNamingStrategy">
<property name="attributeSource">
<ref local="attributeSource"/>
</property>
</bean>
<bean id="attributeSource" class="org.springframework.jmx.export.metadata.AttributesJmxAttributeSource">
<property name="attributes">
<bean class="org.springframework.metadata.commons.CommonsAttributes"/>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="org.springframework.jmx.export.MBeanExporter" autowire="byName">
<property name="beans">
<map>
<entry key="bean:name=testBean3">
<ref local="testBean"/>
</entry>
</map>
</property>
<property name="assembler">
<ref local="metadataAssembler"/>
</property>
</bean>
<bean id="testBean" class="org.springframework.jmx.JmxTestBean">
<property name="name">
<value>TEST</value>
</property>
<property name="age">
<value>100</value>
</property>
</bean>
<bean id="metadataAssembler" class="org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler">
<property name="attributeSource">
<bean class="org.springframework.jmx.export.metadata.AttributesJmxAttributeSource">
<property name="attributes">
<bean class="org.springframework.metadata.commons.CommonsAttributes"/>
</property>
</bean>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="org.springframework.jmx.export.MBeanExporter" autowire="byName">
<property name="beans">
<map>
<entry key="bean:name=testBean5" value-ref="testBean"/>
</map>
</property>
<property name="assembler">
<bean class="org.springframework.jmx.export.assembler.MethodExclusionMBeanInfoAssembler">
<property name="ignoredMethods" value="dontExposeMe,setSuperman"/>
<property name="notificationInfos">
<bean class="org.springframework.jmx.export.metadata.ManagedNotification">
<property name="name" value="My Notification"/>
<property name="description" value="A Notification"/>
<property name="notificationTypes" value="type.foo,type.bar"/>
</bean>
</property>
</bean>
</property>
</bean>
<bean id="testBean" class="org.springframework.jmx.JmxTestBean">
<property name="name" value="TEST"/>
<property name="age" value="100"/>
</bean>
</beans>

View File

@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="org.springframework.jmx.export.MBeanExporter" autowire="byName">
<property name="beans">
<map>
<entry key="bean:name=testBean4" value-ref="testBean"/>
</map>
</property>
<property name="assembler">
<bean class="org.springframework.jmx.export.assembler.MethodExclusionMBeanInfoAssembler">
<property name="ignoredMethods" value="setAge,isSuperman,setSuperman,dontExposeMe"/>
<property name="ignoredMethodMappings">
<props>
<prop key="bean:name=testBean5">setAge,isSuperman,setSuperman,dontExposeMe</prop>
</props>
</property>
<property name="notificationInfos">
<bean class="org.springframework.jmx.export.metadata.ManagedNotification">
<property name="name" value="My Notification"/>
<property name="description" value="A Notification"/>
<property name="notificationTypes" value="type.foo,type.bar"/>
</bean>
</property>
</bean>
</property>
</bean>
<bean id="testBean" class="org.springframework.jmx.JmxTestBean">
<property name="name" value="TEST"/>
<property name="age" value="100"/>
</bean>
</beans
>

View File

@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="org.springframework.jmx.export.MBeanExporter" autowire="byName">
<property name="beans">
<map>
<entry key="bean:name=testBean4" value-ref="testBean"/>
</map>
</property>
<property name="assembler">
<bean class="org.springframework.jmx.export.assembler.MethodExclusionMBeanInfoAssembler">
<property name="ignoredMethodMappings">
<props>
<prop key="bean:name=testBean4">setAge,isSuperman,setSuperman,dontExposeMe</prop>
</props>
</property>
<property name="notificationInfos">
<bean class="org.springframework.jmx.export.metadata.ManagedNotification">
<property name="name" value="My Notification"/>
<property name="description" value="A Notification"/>
<property name="notificationTypes" value="type.foo,type.bar"/>
</bean>
</property>
</bean>
</property>
</bean>
<bean id="testBean" class="org.springframework.jmx.JmxTestBean">
<property name="name" value="TEST"/>
<property name="age" value="100"/>
</bean>
</beans
>

View File

@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="org.springframework.jmx.export.MBeanExporter" autowire="byName">
<property name="beans">
<map>
<entry key="bean:name=testBean4" value-ref="testBean"/>
</map>
</property>
<property name="assembler">
<bean class="org.springframework.jmx.export.assembler.MethodExclusionMBeanInfoAssembler">
<property name="ignoredMethodMappings">
<props>
<prop key="bean:name=testBean5">setAge,isSuperman,setSuperman,dontExposeMe</prop>
</props>
</property>
<property name="notificationInfos">
<bean class="org.springframework.jmx.export.metadata.ManagedNotification">
<property name="name" value="My Notification"/>
<property name="description" value="A Notification"/>
<property name="notificationTypes" value="type.foo,type.bar"/>
</bean>
</property>
</bean>
</property>
</bean>
<bean id="testBean" class="org.springframework.jmx.JmxTestBean">
<property name="name" value="TEST"/>
<property name="age" value="100"/>
</bean>
</beans
>

View File

@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="org.springframework.jmx.export.MBeanExporter" autowire="byName">
<property name="beans">
<map>
<entry key="bean:name=testBean5">
<ref local="testBean"/>
</entry>
</map>
</property>
<property name="assembler">
<bean class="org.springframework.jmx.export.assembler.MethodNameBasedMBeanInfoAssembler">
<property name="managedMethods">
<value>add,myOperation,getName,setName,getAge</value>
</property>
<property name="notificationInfos">
<bean class="org.springframework.jmx.export.metadata.ManagedNotification">
<property name="name" value="My Notification"/>
<property name="description" value="A Notification"/>
<property name="notificationTypes" value="type.foo,type.bar"/>
</bean>
</property>
</bean>
</property>
</bean>
<bean id="testBean" class="org.springframework.jmx.JmxTestBean">
<property name="name">
<value>TEST</value>
</property>
<property name="age">
<value>100</value>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="org.springframework.jmx.export.MBeanExporter" autowire="byName">
<property name="beans">
<map>
<entry key="bean:name=testBean4">
<ref local="testBean"/>
</entry>
</map>
</property>
<property name="assembler">
<bean class="org.springframework.jmx.export.assembler.MethodNameBasedMBeanInfoAssembler">
<property name="methodMappings">
<props>
<prop key="bean:name=testBean4">
getNickName,setNickName,add,myOperation,getName,setName,getAge</prop>
</props>
</property>
<property name="notificationInfoMappings">
<map>
<entry key="bean:name=testBean4">
<bean class="org.springframework.jmx.export.metadata.ManagedNotification">
<property name="name" value="My Notification"/>
<property name="description" value="A Notification"/>
<property name="notificationTypes" value="type.foo,type.bar"/>
</bean>
</entry>
</map>
</property>
</bean>
</property>
</bean>
<bean id="testBean" class="org.springframework.jmx.JmxTestBean">
<property name="name">
<value>TEST</value>
</property>
<property name="age">
<value>100</value>
</property>
</bean>
</beans
>

View File

@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="org.springframework.jmx.export.MBeanExporter" autowire="byName">
<property name="beans">
<map>
<entry key="bean:name=testBean1">
<ref local="testBean"/>
</entry>
</map>
</property>
<property name="assembler">
<bean class="org.springframework.jmx.export.assembler.SimpleReflectiveMBeanInfoAssembler">
<property name="notificationInfos">
<bean class="org.springframework.jmx.export.metadata.ManagedNotification">
<property name="name" value="My Notification"/>
<property name="description" value="A Notification"/>
<property name="notificationTypes" value="type.foo,type.bar"/>
</bean>
</property>
</bean>
</property>
</bean>
<bean id="testBean" class="org.springframework.jmx.JmxTestBean">
<property name="name">
<value>TEST</value>
</property>
<property name="age">
<value>100</value>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="server" class="org.springframework.jmx.support.MBeanServerFactoryBean"/>
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
<property name="server" ref="server"/>
<property name="autodetect" value="true"/>
<property name="excludedBeans" value="connector"/>
</bean>
<bean name="spring:mbean=true" class="org.springframework.jmx.export.TestDynamicMBean" lazy-init="true"/>
<bean name="spring:mbean=another" class="org.springframework.jmx.export.MBeanExporterTests$Person" lazy-init="true">
<property name="name" value="Juergen Hoeller"/>
</bean>
<bean id="connector" class="org.springframework.jmx.support.ConnectorServerFactoryBean">
<property name="server">
<ref local="server"/>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="server" class="org.springframework.jmx.support.MBeanServerFactoryBean"/>
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
<property name="server" ref="server"/>
<property name="autodetect" value="true"/>
<property name="excludedBeans" value="connector"/>
</bean>
<bean name="spring:mbean=true" class="org.springframework.jmx.export.TestDynamicMBean"/>
<bean name="spring:mbean2=true" class="org.springframework.jmx.export.TestDynamicMBean"/>
<bean name="spring:mbean3=true" class="org.springframework.jmx.export.TestDynamicMBean"/>
<bean id="connector" class="org.springframework.jmx.support.ConnectorServerFactoryBean">
<property name="server">
<ref local="server"/>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="server" class="org.springframework.jmx.support.MBeanServerFactoryBean"/>
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
<property name="server" ref="server"/>
<property name="autodetect" value="true"/>
</bean>
</beans>

View File

@@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date">
<bean class="org.springframework.beans.propertyeditors.CustomDateEditor">
<constructor-arg index="0">
<bean class="java.text.SimpleDateFormat">
<constructor-arg>
<value>yyyy/MM/dd</value>
</constructor-arg>
</bean>
</constructor-arg>
<constructor-arg index="1">
<value>true</value>
</constructor-arg>
</bean>
</entry>
</map>
</property>
</bean>
<bean id="dateRange" class="org.springframework.jmx.export.DateRange">
<property name="startDate">
<value>2004/10/12</value>
</property>
<property name="endDate">
<value>2004/11/13</value>
</property>
</bean>
<bean class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<map>
<entry key="bean:name=dateRange">
<ref bean="dateRange"/>
</entry>
</map>
</property>
<property name="server" ref="server"/>
</bean>
</beans>

View File

@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="server" class="org.springframework.jmx.support.MBeanServerFactoryBean"/>
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
<property name="server">
<ref local="server"/>
</property>
<property name="autodetect">
<value>true</value>
</property>
<property name="excludedBeans" value="spring:mbean=false"/>
</bean>
<bean name="spring:mbean=true" class="org.springframework.jmx.export.TestDynamicMBean"/>
<bean name="spring:mbean=false" class="org.springframework.jmx.export.TestDynamicMBean"/>
<bean id="connector" class="org.springframework.jmx.support.ConnectorServerFactoryBean">
<property name="server">
<ref local="server"/>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<map>
<entry key="bean:name=testBean1" value="testBean"/>
<entry key="bean:name=testBean2" value="testBean2"/>
</map>
</property>
<property name="server" ref="server"/>
<property name="autodetect" value="true"/>
</bean>
<bean id="testBean" class="org.springframework.jmx.export.ExceptionOnInitBean" lazy-init="true">
<property name="exceptOnInit" value="true"/>
<property name="name" value="foo"/>
</bean>
<bean id="testBean2" class="org.springframework.jmx.export.ExceptionOnInitBean" lazy-init="true">
<property name="exceptOnInit" value="false"/>
<property name="name" value="foo"/>
</bean>
<bean id="testBean3" class="org.springframework.jmx.export.ExceptionOnInitBea" lazy-init="true"/>
<bean id="server" class="org.springframework.jmx.support.MBeanServerFactoryBean"/>
</beans>

View File

@@ -0,0 +1,42 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export.naming;
import javax.management.ObjectName;
import junit.framework.TestCase;
/**
* @author Rob Harrop
*/
public abstract class AbstractNamingStrategyTests extends TestCase {
public void testNaming() throws Exception {
ObjectNamingStrategy strat = getStrategy();
ObjectName objectName = strat.getObjectName(getManagedResource(), getKey());
assertEquals(objectName.getCanonicalName(), getCorrectObjectName());
}
protected abstract ObjectNamingStrategy getStrategy() throws Exception;
protected abstract Object getManagedResource() throws Exception;
protected abstract String getKey();
protected abstract String getCorrectObjectName();
}

View File

@@ -0,0 +1,45 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jmx.export.naming;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import junit.framework.TestCase;
import org.springframework.jmx.JmxTestBean;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
/**
* @author Rob Harrop
*/
public class IdentityNamingStrategyTests extends TestCase {
public void testNaming() throws MalformedObjectNameException {
JmxTestBean bean = new JmxTestBean();
IdentityNamingStrategy strategy = new IdentityNamingStrategy();
ObjectName objectName = strategy.getObjectName(bean, "null");
assertEquals("Domain is incorrect", bean.getClass().getPackage().getName(),
objectName.getDomain());
assertEquals("Type property is incorrect", ClassUtils.getShortName(bean.getClass()),
objectName.getKeyProperty(IdentityNamingStrategy.TYPE_KEY));
assertEquals("HashCode property is incorrect", ObjectUtils.getIdentityHexString(bean),
objectName.getKeyProperty(IdentityNamingStrategy.HASH_CODE_KEY));
}
}

View File

@@ -0,0 +1,42 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export.naming;
/**
* @author Rob Harrop
*/
public class KeyNamingStrategyTests extends AbstractNamingStrategyTests {
private static final String OBJECT_NAME = "spring:name=test";
protected ObjectNamingStrategy getStrategy() throws Exception {
return new KeyNamingStrategy();
}
protected Object getManagedResource() {
return new Object();
}
protected String getKey() {
return OBJECT_NAME;
}
protected String getCorrectObjectName() {
return OBJECT_NAME;
}
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export.naming;
import org.springframework.core.io.ClassPathResource;
/**
* @author Juergen Hoeller
*/
public class PropertiesFileNamingStrategyTests extends PropertiesNamingStrategyTests {
protected ObjectNamingStrategy getStrategy() throws Exception {
KeyNamingStrategy strat = new KeyNamingStrategy();
strat.setMappingLocation(new ClassPathResource("jmx-names.properties", getClass()));
strat.afterPropertiesSet();
return strat;
}
}

View File

@@ -0,0 +1,50 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.export.naming;
import java.util.Properties;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class PropertiesNamingStrategyTests extends AbstractNamingStrategyTests {
private static final String OBJECT_NAME = "bean:name=namingTest";
protected ObjectNamingStrategy getStrategy() throws Exception {
KeyNamingStrategy strat = new KeyNamingStrategy();
Properties mappings = new Properties();
mappings.setProperty("namingTest", "bean:name=namingTest");
strat.setMappings(mappings);
strat.afterPropertiesSet();
return strat;
}
protected Object getManagedResource() {
return new Object();
}
protected String getKey() {
return "namingTest";
}
protected String getCorrectObjectName() {
return OBJECT_NAME;
}
}

View File

@@ -0,0 +1 @@
namingTest = bean:name=namingTest

View File

@@ -0,0 +1,125 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jmx.export.notification;
import static org.junit.Assert.*;
import javax.management.AttributeChangeNotification;
import javax.management.MBeanException;
import javax.management.MalformedObjectNameException;
import javax.management.Notification;
import javax.management.ObjectName;
import javax.management.RuntimeOperationsException;
import org.junit.Test;
import org.springframework.jmx.export.SpringModelMBean;
/**
* @author Rick Evans
* @author Chris Beams
*/
public final class ModelMBeanNotificationPublisherTests {
@Test(expected=IllegalArgumentException.class)
public void testCtorWithNullMBean() throws Exception {
new ModelMBeanNotificationPublisher(null, createObjectName(), this);
}
@Test(expected=IllegalArgumentException.class)
public void testCtorWithNullObjectName() throws Exception {
new ModelMBeanNotificationPublisher(new SpringModelMBean(), null, this);
}
@Test(expected=IllegalArgumentException.class)
public void testCtorWithNullManagedResource() throws Exception {
new ModelMBeanNotificationPublisher(new SpringModelMBean(), createObjectName(), null);
}
@Test(expected=IllegalArgumentException.class)
public void testSendNullNotification() throws Exception {
NotificationPublisher publisher
= new ModelMBeanNotificationPublisher(new SpringModelMBean(), createObjectName(), this);
publisher.sendNotification(null);
}
public void testSendVanillaNotification() throws Exception {
StubSpringModelMBean mbean = new StubSpringModelMBean();
Notification notification = new Notification("network.alarm.router", mbean, 1872);
ObjectName objectName = createObjectName();
NotificationPublisher publisher = new ModelMBeanNotificationPublisher(mbean, objectName, mbean);
publisher.sendNotification(notification);
assertNotNull(mbean.getActualNotification());
assertSame("The exact same Notification is not being passed through from the publisher to the mbean.", notification, mbean.getActualNotification());
assertSame("The 'source' property of the Notification is not being set to the ObjectName of the associated MBean.", objectName, mbean.getActualNotification().getSource());
}
public void testSendAttributeChangeNotification() throws Exception {
StubSpringModelMBean mbean = new StubSpringModelMBean();
Notification notification = new AttributeChangeNotification(mbean, 1872, System.currentTimeMillis(), "Shall we break for some tea?", "agree", "java.lang.Boolean", Boolean.FALSE, Boolean.TRUE);
ObjectName objectName = createObjectName();
NotificationPublisher publisher = new ModelMBeanNotificationPublisher(mbean, objectName, mbean);
publisher.sendNotification(notification);
assertNotNull(mbean.getActualNotification());
assertTrue(mbean.getActualNotification() instanceof AttributeChangeNotification);
assertSame("The exact same Notification is not being passed through from the publisher to the mbean.", notification, mbean.getActualNotification());
assertSame("The 'source' property of the Notification is not being set to the ObjectName of the associated MBean.", objectName, mbean.getActualNotification().getSource());
}
public void testSendAttributeChangeNotificationWhereSourceIsNotTheManagedResource() throws Exception {
StubSpringModelMBean mbean = new StubSpringModelMBean();
Notification notification = new AttributeChangeNotification(this, 1872, System.currentTimeMillis(), "Shall we break for some tea?", "agree", "java.lang.Boolean", Boolean.FALSE, Boolean.TRUE);
ObjectName objectName = createObjectName();
NotificationPublisher publisher = new ModelMBeanNotificationPublisher(mbean, objectName, mbean);
publisher.sendNotification(notification);
assertNotNull(mbean.getActualNotification());
assertTrue(mbean.getActualNotification() instanceof AttributeChangeNotification);
assertSame("The exact same Notification is not being passed through from the publisher to the mbean.", notification, mbean.getActualNotification());
assertSame("The 'source' property of the Notification is *wrongly* being set to the ObjectName of the associated MBean.", this, mbean.getActualNotification().getSource());
}
private static ObjectName createObjectName() throws MalformedObjectNameException {
return ObjectName.getInstance("foo:type=bar");
}
private static class StubSpringModelMBean extends SpringModelMBean {
private Notification actualNotification;
public StubSpringModelMBean() throws MBeanException, RuntimeOperationsException {
}
public Notification getActualNotification() {
return this.actualNotification;
}
public void sendNotification(Notification notification) throws RuntimeOperationsException {
this.actualNotification = notification;
}
public void sendAttributeChangeNotification(AttributeChangeNotification notification) throws RuntimeOperationsException {
this.actualNotification = notification;
}
}
}

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="publisher" class="org.springframework.jmx.export.NotificationPublisherTests$MyNotificationPublisher" lazy-init="true"/>
<bean class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<map>
<entry key="spring:type=Publisher" value="publisher"/>
</map>
</property>
<property name="server" ref="server"/>
</bean>
</beans>

View File

@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="publisher" class="org.springframework.jmx.export.NotificationPublisherTests$MyNotificationPublisher"/>
<bean id="publisherMBean" class="org.springframework.jmx.export.NotificationPublisherTests$MyNotificationPublisherMBean"/>
<bean id="publisherStandardMBean" class="org.springframework.jmx.export.NotificationPublisherTests$MyNotificationPublisherStandardMBean"/>
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<map>
<entry key="spring:type=Publisher" value-ref="publisher"/>
<entry key="spring:type=PublisherMBean" value-ref="publisherMBean"/>
<entry key="spring:type=PublisherStandardMBean" value-ref="publisherStandardMBean"/>
</map>
</property>
<property name="server" ref="server"/>
</bean>
</beans>

View File

@@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="properties">
<props>
<prop key="testBean.name">Rob Harrop</prop>
<prop key="testBean.age">100</prop>
<prop key="scopeName">myScope</prop>
</props>
</property>
</bean>
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="${scopeName}">
<bean class="org.springframework.beans.factory.config.SimpleMapScope"/>
</entry>
</map>
</property>
</bean>
<bean class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<map>
<entry key="bean:name=proxyTestBean1">
<ref local="testBean"/>
</entry>
</map>
</property>
<property name="server" ref="server"/>
</bean>
<bean id="testBean" class="org.springframework.jmx.JmxTestBean" scope="myScope">
<property name="name">
<value>${testBean.name}</value>
</property>
<property name="age">
<value>${testBean.age}</value>
</property>
<property name="nickName">
<null/>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,122 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.support;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import org.junit.Ignore;
import org.springframework.jmx.AbstractMBeanServerTests;
/**
* @author Rob Harrop
*/
@Ignore // see https://issuetracker.springsource.com/browse/BRITS-235
public class ConnectorServerFactoryBeanTests extends AbstractMBeanServerTests {
private static final String OBJECT_NAME = "spring:type=connector,name=test";
public void testStartupWithLocatedServer() throws Exception {
ConnectorServerFactoryBean bean = new ConnectorServerFactoryBean();
bean.afterPropertiesSet();
try {
checkServerConnection(getServer());
}
finally {
bean.destroy();
}
}
public void testStartupWithSuppliedServer() throws Exception {
//Added a brief snooze here - seems to fix occasional
//java.net.BindException: Address already in use errors
Thread.sleep(1);
ConnectorServerFactoryBean bean = new ConnectorServerFactoryBean();
bean.setServer(getServer());
bean.afterPropertiesSet();
try {
checkServerConnection(getServer());
}
finally {
bean.destroy();
}
}
public void testRegisterWithMBeanServer() throws Exception {
//Added a brief snooze here - seems to fix occasional
//java.net.BindException: Address already in use errors
Thread.sleep(1);
ConnectorServerFactoryBean bean = new ConnectorServerFactoryBean();
bean.setObjectName(OBJECT_NAME);
bean.afterPropertiesSet();
try {
// Try to get the connector bean.
ObjectInstance instance = getServer().getObjectInstance(ObjectName.getInstance(OBJECT_NAME));
assertNotNull("ObjectInstance should not be null", instance);
}
finally {
bean.destroy();
}
}
public void testNoRegisterWithMBeanServer() throws Exception {
ConnectorServerFactoryBean bean = new ConnectorServerFactoryBean();
bean.afterPropertiesSet();
try {
// Try to get the connector bean.
getServer().getObjectInstance(ObjectName.getInstance(OBJECT_NAME));
fail("Instance should not be found");
}
catch (InstanceNotFoundException ex) {
// expected
}
finally {
bean.destroy();
}
}
private void checkServerConnection(MBeanServer hostedServer) throws IOException, MalformedURLException {
// Try to connect using client.
JMXServiceURL serviceURL = new JMXServiceURL(ConnectorServerFactoryBean.DEFAULT_SERVICE_URL);
JMXConnector connector = JMXConnectorFactory.connect(serviceURL);
assertNotNull("Client Connector should not be null", connector);
// Get the MBean server connection.
MBeanServerConnection connection = connector.getMBeanServerConnection();
assertNotNull("MBeanServerConnection should not be null", connection);
// Test for MBean server equality.
assertEquals("Registered MBean count should be the same",
hostedServer.getMBeanCount(), connection.getMBeanCount());
}
}

View File

@@ -0,0 +1,243 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.support;
import java.beans.PropertyDescriptor;
import javax.management.DynamicMBean;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.management.StandardMBean;
import junit.framework.TestCase;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.core.JdkVersion;
import org.springframework.jmx.IJmxTestBean;
import org.springframework.jmx.JmxTestBean;
import org.springframework.jmx.export.TestDynamicMBean;
import org.springframework.util.ObjectUtils;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class JmxUtilsTests extends TestCase {
public void testIsMBeanWithDynamicMBean() throws Exception {
DynamicMBean mbean = new TestDynamicMBean();
assertTrue("Dynamic MBean not detected correctly", JmxUtils.isMBean(mbean.getClass()));
}
public void testIsMBeanWithStandardMBeanWrapper() throws Exception {
StandardMBean mbean = new StandardMBean(new JmxTestBean(), IJmxTestBean.class);
assertTrue("Standard MBean not detected correctly", JmxUtils.isMBean(mbean.getClass()));
}
public void testIsMBeanWithStandardMBeanInherited() throws Exception {
StandardMBean mbean = new StandardMBeanImpl();
assertTrue("Standard MBean not detected correctly", JmxUtils.isMBean(mbean.getClass()));
}
public void testNotAnMBean() throws Exception {
assertFalse("Object incorrectly identified as an MBean", JmxUtils.isMBean(Object.class));
}
public void testSimpleMBean() throws Exception {
Foo foo = new Foo();
assertTrue("Simple MBean not detected correctly", JmxUtils.isMBean(foo.getClass()));
}
public void testSimpleMXBean() throws Exception {
FooX foo = new FooX();
assertTrue("Simple MXBean not detected correctly", JmxUtils.isMBean(foo.getClass()));
}
public void testSimpleMBeanThroughInheritance() throws Exception {
Bar bar = new Bar();
Abc abc = new Abc();
assertTrue("Simple MBean (through inheritance) not detected correctly",
JmxUtils.isMBean(bar.getClass()));
assertTrue("Simple MBean (through 2 levels of inheritance) not detected correctly",
JmxUtils.isMBean(abc.getClass()));
}
public void testGetAttributeNameWithStrictCasing() {
PropertyDescriptor pd = new BeanWrapperImpl(AttributeTestBean.class).getPropertyDescriptor("name");
String attributeName = JmxUtils.getAttributeName(pd, true);
assertEquals("Incorrect casing on attribute name", "Name", attributeName);
}
public void testGetAttributeNameWithoutStrictCasing() {
PropertyDescriptor pd = new BeanWrapperImpl(AttributeTestBean.class).getPropertyDescriptor("name");
String attributeName = JmxUtils.getAttributeName(pd, false);
assertEquals("Incorrect casing on attribute name", "name", attributeName);
}
public void testAppendIdentityToObjectName() throws MalformedObjectNameException {
ObjectName objectName = ObjectNameManager.getInstance("spring:type=Test");
Object managedResource = new Object();
ObjectName uniqueName = JmxUtils.appendIdentityToObjectName(objectName, managedResource);
String typeProperty = "type";
assertEquals("Domain of transformed name is incorrect", objectName.getDomain(), uniqueName.getDomain());
assertEquals("Type key is incorrect", objectName.getKeyProperty(typeProperty), uniqueName.getKeyProperty("type"));
assertEquals("Identity key is incorrect", ObjectUtils.getIdentityHexString(managedResource), uniqueName.getKeyProperty(JmxUtils.IDENTITY_OBJECT_NAME_KEY));
}
public void testLocatePlatformMBeanServer() {
if(JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_15) {
return;
}
MBeanServer server = null;
try {
server = JmxUtils.locateMBeanServer();
}
finally {
if (server != null) {
MBeanServerFactory.releaseMBeanServer(server);
}
}
}
public void testIsMBean() {
// Correctly returns true for a class
assertTrue(JmxUtils.isMBean(JmxClass.class));
// Correctly returns false since JmxUtils won't navigate to the extended interface
assertFalse(JmxUtils.isMBean(SpecializedJmxInterface.class));
// Incorrectly returns true since it doesn't detect that this is an interface
assertFalse(JmxUtils.isMBean(JmxInterface.class));
}
public static class AttributeTestBean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static class StandardMBeanImpl extends StandardMBean implements IJmxTestBean {
public StandardMBeanImpl() throws NotCompliantMBeanException {
super(IJmxTestBean.class);
}
public int add(int x, int y) {
return 0;
}
public long myOperation() {
return 0;
}
public int getAge() {
return 0;
}
public void setAge(int age) {
}
public void setName(String name) {
}
public String getName() {
return null;
}
public void dontExposeMe() {
}
}
public static interface FooMBean {
String getName();
}
public static class Foo implements FooMBean {
public String getName() {
return "Rob Harrop";
}
}
public static interface FooMXBean {
String getName();
}
public static class FooX implements FooMXBean {
public String getName() {
return "Rob Harrop";
}
}
public static class Bar extends Foo {
}
public static class Abc extends Bar {
}
private static interface JmxInterfaceMBean {
}
private static interface JmxInterface extends JmxInterfaceMBean {
}
private static interface SpecializedJmxInterface extends JmxInterface {
}
private static interface JmxClassMBean {
}
private static class JmxClass implements JmxClassMBean {
}
}

View File

@@ -0,0 +1,118 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jmx.support;
import java.net.MalformedURLException;
import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
import org.junit.Ignore;
import org.springframework.aop.support.AopUtils;
import org.springframework.jmx.AbstractMBeanServerTests;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class MBeanServerConnectionFactoryBeanTests extends AbstractMBeanServerTests {
private static final String SERVICE_URL = "service:jmx:jmxmp://localhost:9876";
private JMXServiceURL getServiceUrl() throws MalformedURLException {
return new JMXServiceURL(SERVICE_URL);
}
private JMXConnectorServer getConnectorServer() throws Exception {
return JMXConnectorServerFactory.newJMXConnectorServer(getServiceUrl(), null, getServer());
}
@Ignore // see https://issuetracker.springsource.com/browse/BRITS-235
public void ignoreTestValidConnection() throws Exception {
JMXConnectorServer connectorServer = getConnectorServer();
connectorServer.start();
try {
MBeanServerConnectionFactoryBean bean = new MBeanServerConnectionFactoryBean();
bean.setServiceUrl(SERVICE_URL);
bean.afterPropertiesSet();
try {
MBeanServerConnection connection = (MBeanServerConnection) bean.getObject();
assertNotNull("Connection should not be null", connection);
// perform simple MBean count test
assertEquals("MBean count should be the same", getServer().getMBeanCount(), connection.getMBeanCount());
}
finally {
bean.destroy();
}
}
finally {
connectorServer.stop();
}
}
public void testWithNoServiceUrl() throws Exception {
MBeanServerConnectionFactoryBean bean = new MBeanServerConnectionFactoryBean();
try {
bean.afterPropertiesSet();
fail("IllegalArgumentException should be raised when no service url is provided");
}
catch (IllegalArgumentException ex) {
// expected
}
}
@Ignore // see https://issuetracker.springsource.com/browse/BRITS-235
public void ignoreTestWithLazyConnection() throws Exception {
MBeanServerConnectionFactoryBean bean = new MBeanServerConnectionFactoryBean();
bean.setServiceUrl(SERVICE_URL);
bean.setConnectOnStartup(false);
bean.afterPropertiesSet();
MBeanServerConnection connection = (MBeanServerConnection) bean.getObject();
assertTrue(AopUtils.isAopProxy(connection));
JMXConnectorServer connector = null;
try {
connector = getConnectorServer();
connector.start();
assertEquals("Incorrect MBean count", getServer().getMBeanCount(), connection.getMBeanCount());
}
finally {
bean.destroy();
if (connector != null) {
connector.stop();
}
}
}
public void testWithLazyConnectionAndNoAccess() throws Exception {
MBeanServerConnectionFactoryBean bean = new MBeanServerConnectionFactoryBean();
bean.setServiceUrl(SERVICE_URL);
bean.setConnectOnStartup(false);
bean.afterPropertiesSet();
MBeanServerConnection connection = (MBeanServerConnection) bean.getObject();
assertTrue(AopUtils.isAopProxy(connection));
bean.destroy();
}
}

View File

@@ -0,0 +1,121 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.springframework.jmx.support;
import java.util.List;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import junit.framework.TestCase;
/**
* @author Rob Harrop
*/
public class MBeanServerFactoryBeanTests extends TestCase {
public void testGetObject() throws Exception {
MBeanServerFactoryBean bean = new MBeanServerFactoryBean();
bean.afterPropertiesSet();
try {
MBeanServer server = (MBeanServer) bean.getObject();
assertNotNull("The MBeanServer should not be null", server);
}
finally {
bean.destroy();
}
}
public void testDefaultDomain() throws Exception {
MBeanServerFactoryBean bean = new MBeanServerFactoryBean();
bean.setDefaultDomain("foo");
bean.afterPropertiesSet();
try {
MBeanServer server = (MBeanServer) bean.getObject();
assertEquals("The default domain should be foo", "foo", server.getDefaultDomain());
}
finally {
bean.destroy();
}
}
public void testWithLocateExistingAndExistingServer() {
MBeanServer server = MBeanServerFactory.createMBeanServer();
try {
MBeanServerFactoryBean bean = new MBeanServerFactoryBean();
bean.setLocateExistingServerIfPossible(true);
bean.afterPropertiesSet();
try {
MBeanServer otherServer = (MBeanServer) bean.getObject();
assertSame("Existing MBeanServer not located", server, otherServer);
}
finally {
bean.destroy();
}
}
finally {
MBeanServerFactory.releaseMBeanServer(server);
}
}
public void testWithLocateExistingAndNoExistingServer() {
MBeanServerFactoryBean bean = new MBeanServerFactoryBean();
bean.setLocateExistingServerIfPossible(true);
bean.afterPropertiesSet();
try {
assertNotNull("MBeanServer not created", bean.getObject());
}
finally {
bean.destroy();
}
}
public void testCreateMBeanServer() throws Exception {
testCreation(true, "The server should be available in the list");
}
public void testNewMBeanServer() throws Exception {
testCreation(false, "The server should not be available in the list");
}
private void testCreation(boolean referenceShouldExist, String failMsg) throws Exception {
MBeanServerFactoryBean bean = new MBeanServerFactoryBean();
bean.setRegisterWithFactory(referenceShouldExist);
bean.afterPropertiesSet();
try {
MBeanServer server = (MBeanServer) bean.getObject();
List servers = MBeanServerFactory.findMBeanServer(null);
boolean found = false;
for (int x = 0; x < servers.size(); x++) {
if (servers.get(x) == server) {
found = true;
break;
}
}
if (!(found == referenceShouldExist)) {
fail(failMsg);
}
}
finally {
bean.destroy();
}
}
}