2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.config.manager.impl;
10 import static org.junit.Assert.assertEquals;
11 import static org.mockito.Matchers.any;
12 import static org.mockito.Mockito.doAnswer;
13 import static org.mockito.Mockito.doNothing;
14 import static org.mockito.Mockito.mock;
16 import com.google.common.base.Preconditions;
17 import java.lang.management.ManagementFactory;
18 import java.lang.reflect.InvocationHandler;
19 import java.lang.reflect.InvocationTargetException;
20 import java.lang.reflect.Method;
21 import java.lang.reflect.Proxy;
22 import java.util.Dictionary;
23 import java.util.LinkedList;
24 import java.util.List;
26 import javax.management.InstanceAlreadyExistsException;
27 import javax.management.MBeanServer;
28 import javax.management.ObjectName;
29 import javax.management.RuntimeMBeanException;
30 import org.junit.After;
31 import org.junit.Before;
32 import org.mockito.Matchers;
33 import org.mockito.Mock;
34 import org.mockito.MockitoAnnotations;
35 import org.mockito.invocation.InvocationOnMock;
36 import org.mockito.stubbing.Answer;
37 import org.opendaylight.controller.config.api.jmx.CommitStatus;
38 import org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver;
39 import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
40 import org.opendaylight.controller.config.manager.impl.jmx.ConfigRegistryJMXRegistrator;
41 import org.opendaylight.controller.config.manager.impl.jmx.InternalJMXRegistrator;
42 import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolImpl;
43 import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPool;
44 import org.opendaylight.controller.config.spi.Module;
45 import org.opendaylight.controller.config.util.ConfigRegistryJMXClient;
46 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
47 import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
48 import org.osgi.framework.BundleContext;
49 import org.osgi.framework.ServiceRegistration;
52 * Each test that relies on
53 * {@link org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl}
54 * needs to subclass this test.
55 * {@link org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl} is
56 * registered to platform MBean Server using
57 * {@link #initConfigTransactionManagerImpl(org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver)}
58 * typically during setting up the each test.
60 public abstract class AbstractConfigTest extends
61 AbstractLockedPlatformMBeanServerTest {
62 protected ConfigRegistryJMXRegistrator configRegistryJMXRegistrator;
63 protected ConfigRegistryImpl configRegistry;
64 protected ConfigRegistryJMXClient configRegistryClient;
65 protected BaseJMXRegistrator baseJmxRegistrator;
66 protected InternalJMXRegistrator internalJmxRegistrator;
68 protected BundleContext mockedContext;
70 protected ServiceRegistration<?> mockedServiceRegistration;
73 public void setUpMocks() {
74 MockitoAnnotations.initMocks(this);
78 // Default handler for OSGi service registration
79 protected static class RecordingBundleContextServiceRegistrationHandler implements BundleContextServiceRegistrationHandler {
80 private final List<RegistrationHolder> registrations = new LinkedList<>();
82 public void handleServiceRegistration(Class<?> clazz, Object serviceInstance, Dictionary<String, ?> props) {
84 registrations.add(new RegistrationHolder(clazz, serviceInstance, props));
87 public List<RegistrationHolder> getRegistrations() {
91 protected static class RegistrationHolder {
92 protected final Class<?> clazz;
93 protected final Object instance;
94 protected final Dictionary<String, ?> props;
96 public RegistrationHolder(Class<?> clazz, Object instance, Dictionary<String, ?> props) {
98 this.instance = instance;
105 protected BundleContextServiceRegistrationHandler currentBundleContextServiceRegistrationHandler;
107 protected BundleContextServiceRegistrationHandler getBundleContextServiceRegistrationHandler(Class<?> serviceType) {
108 return currentBundleContextServiceRegistrationHandler;
111 // this method should be called in @Before
112 protected void initConfigTransactionManagerImpl(
113 ModuleFactoriesResolver resolver) {
115 final MBeanServer platformMBeanServer = ManagementFactory
116 .getPlatformMBeanServer();
118 configRegistryJMXRegistrator = new ConfigRegistryJMXRegistrator(platformMBeanServer);
121 internalJmxRegistrator = new InternalJMXRegistrator(platformMBeanServer);
122 baseJmxRegistrator = new BaseJMXRegistrator(internalJmxRegistrator);
124 configRegistry = new ConfigRegistryImpl(resolver,
125 platformMBeanServer, baseJmxRegistrator, getCodecRegistry());
128 configRegistryJMXRegistrator.registerToJMX(configRegistry);
129 } catch (InstanceAlreadyExistsException e) {
130 throw new RuntimeException(e);
132 configRegistryClient = new ConfigRegistryJMXClient(platformMBeanServer);
133 currentBundleContextServiceRegistrationHandler = new RecordingBundleContextServiceRegistrationHandler();
136 private void initBundleContext() {
137 doNothing().when(mockedServiceRegistration).unregister();
138 RegisterServiceAnswer answer = new RegisterServiceAnswer();
139 doAnswer(answer).when(mockedContext).registerService(Matchers.<String>any(), any(), Matchers.<Dictionary<String, ?>>any());
140 doAnswer(answer).when(mockedContext).registerService(Matchers.<Class>any(), any(), Matchers.<Dictionary<String, ?>>any());
144 public final void cleanUpConfigTransactionManagerImpl() {
145 configRegistryJMXRegistrator.close();
146 configRegistry.close();
147 TestingFixedThreadPool.cleanUp();
148 TestingScheduledThreadPoolImpl.cleanUp();
152 * Can be called in @After of tests if some other cleanup is needed that
153 * would be discarded by closing config beans in this method
155 protected void destroyAllConfigBeans() throws Exception {
156 ConfigTransactionJMXClient transaction = configRegistryClient
157 .createTransaction();
158 Set<ObjectName> all = transaction.lookupConfigBeans();
159 // workaround for getting same Module more times
160 while (all.size() > 0) {
161 transaction.destroyModule(all.iterator().next());
162 all = transaction.lookupConfigBeans();
164 transaction.commit();
167 protected void assertStatus(CommitStatus status, int expectedNewInstances,
168 int expectedRecreatedInstances, int expectedReusedInstances) {
169 assertEquals("New instances mismatch in " + status, expectedNewInstances, status.getNewInstances().size());
170 assertEquals("Recreated instances mismatch in " + status, expectedRecreatedInstances, status.getRecreatedInstances()
172 assertEquals("Reused instances mismatch in " + status, expectedReusedInstances, status.getReusedInstances()
177 protected void assertBeanCount(int i, String configMXBeanName) {
178 assertEquals(i, configRegistry.lookupConfigBeans(configMXBeanName)
184 * @param configBeanClass
185 * Empty constructor class of config bean to be instantiated
187 * @param implementationName
190 protected ClassBasedModuleFactory createClassBasedCBF(
191 Class<? extends Module> configBeanClass, String implementationName) {
192 return new ClassBasedModuleFactory(implementationName, configBeanClass);
195 protected CodecRegistry getCodecRegistry() {
196 return mock(CodecRegistry.class);
199 public static interface BundleContextServiceRegistrationHandler {
201 void handleServiceRegistration(Class<?> clazz, Object serviceInstance, Dictionary<String, ?> props);
205 private class RegisterServiceAnswer implements Answer<ServiceRegistration<?>> {
208 public ServiceRegistration<?> answer(InvocationOnMock invocation) throws Throwable {
209 Object[] args = invocation.getArguments();
211 Preconditions.checkArgument(args.length == 3, "Unexpected arguments size (expected 3 was %s)", args.length);
213 Object serviceTypeRaw = args[0];
214 Object serviceInstance = args[1];
215 Dictionary<String, ?> props = (Dictionary<String, ?>) args[2];
217 if (serviceTypeRaw instanceof Class) {
218 Class<?> serviceType = (Class<?>) serviceTypeRaw;
219 invokeServiceHandler(serviceInstance, serviceType, props);
221 } else if(serviceTypeRaw instanceof String[]) {
222 for (String className : (String[]) serviceTypeRaw) {
223 invokeServiceHandler(serviceInstance, className, props);
225 } else if (serviceTypeRaw instanceof String) {
226 invokeServiceHandler(serviceInstance, (String) serviceTypeRaw, props);
228 throw new IllegalStateException("Not handling service registration of type, Unknown type" + serviceTypeRaw);
232 return mockedServiceRegistration;
235 public void invokeServiceHandler(Object serviceInstance, String className, Dictionary<String, ?> props) {
237 Class<?> serviceType = Class.forName(className);
238 invokeServiceHandler(serviceInstance, serviceType, props);
239 } catch (ClassNotFoundException e) {
240 throw new IllegalStateException("Not handling service registration of type " + className, e);
244 private void invokeServiceHandler(Object serviceInstance, Class<?> serviceType, Dictionary<String, ?> props) {
245 BundleContextServiceRegistrationHandler serviceRegistrationHandler = getBundleContextServiceRegistrationHandler(serviceType);
247 if (serviceRegistrationHandler != null) {
248 serviceRegistrationHandler.handleServiceRegistration(serviceType, serviceInstance, props);
254 * Expand inner exception wrapped by JMX
256 * @param innerObject jmx proxy which will be wrapped and returned
258 protected <T> T rethrowCause(final T innerObject) {
260 Object proxy = Proxy.newProxyInstance(innerObject.getClass().getClassLoader(),
261 innerObject.getClass().getInterfaces(), new InvocationHandler() {
263 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
265 return method.invoke(innerObject, args);
266 } catch (InvocationTargetException e) {
268 throw e.getTargetException();
269 } catch (RuntimeMBeanException e2) {
270 throw e2.getTargetException();