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.impl.osgi.mapping.BindingContextProvider;
43 import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolImpl;
44 import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPool;
45 import org.opendaylight.controller.config.spi.Module;
46 import org.opendaylight.controller.config.util.ConfigRegistryJMXClient;
47 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
48 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
49 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
50 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
51 import org.osgi.framework.BundleContext;
52 import org.osgi.framework.ServiceRegistration;
55 * Each test that relies on
56 * {@link org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl}
57 * needs to subclass this test.
58 * {@link org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl} is
59 * registered to platform MBean Server using
60 * {@link #initConfigTransactionManagerImpl(org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver)}
61 * typically during setting up the each test.
63 public abstract class AbstractConfigTest extends
64 AbstractLockedPlatformMBeanServerTest {
65 protected ConfigRegistryJMXRegistrator configRegistryJMXRegistrator;
66 protected ConfigRegistryImpl configRegistry;
67 protected ConfigRegistryJMXClient configRegistryClient;
68 protected BaseJMXRegistrator baseJmxRegistrator;
69 protected InternalJMXRegistrator internalJmxRegistrator;
71 protected BundleContext mockedContext;
73 protected ServiceRegistration<?> mockedServiceRegistration;
76 public void setUpMocks() {
77 MockitoAnnotations.initMocks(this);
81 // Default handler for OSGi service registration
82 protected static class RecordingBundleContextServiceRegistrationHandler implements BundleContextServiceRegistrationHandler {
83 private final List<RegistrationHolder> registrations = new LinkedList<>();
85 public void handleServiceRegistration(Class<?> clazz, Object serviceInstance, Dictionary<String, ?> props) {
87 registrations.add(new RegistrationHolder(clazz, serviceInstance, props));
90 public List<RegistrationHolder> getRegistrations() {
94 protected static class RegistrationHolder {
95 protected final Class<?> clazz;
96 protected final Object instance;
97 protected final Dictionary<String, ?> props;
99 public RegistrationHolder(Class<?> clazz, Object instance, Dictionary<String, ?> props) {
101 this.instance = instance;
108 protected BundleContextServiceRegistrationHandler currentBundleContextServiceRegistrationHandler;
110 protected BundleContextServiceRegistrationHandler getBundleContextServiceRegistrationHandler(Class<?> serviceType) {
111 return currentBundleContextServiceRegistrationHandler;
114 // this method should be called in @Before
115 protected void initConfigTransactionManagerImpl(
116 ModuleFactoriesResolver resolver) {
118 final MBeanServer platformMBeanServer = ManagementFactory
119 .getPlatformMBeanServer();
121 configRegistryJMXRegistrator = new ConfigRegistryJMXRegistrator(platformMBeanServer);
124 internalJmxRegistrator = new InternalJMXRegistrator(platformMBeanServer);
125 baseJmxRegistrator = new BaseJMXRegistrator(internalJmxRegistrator);
127 configRegistry = new ConfigRegistryImpl(resolver, platformMBeanServer, baseJmxRegistrator, new BindingContextProvider() {
129 public synchronized void update(final ClassLoadingStrategy classLoadingStrategy, final SchemaContextProvider ctxProvider) {
134 public synchronized BindingRuntimeContext getBindingContext() {
135 return getBindingRuntimeContext();
140 configRegistryJMXRegistrator.registerToJMX(configRegistry);
141 } catch (InstanceAlreadyExistsException e) {
142 throw new RuntimeException(e);
144 configRegistryClient = new ConfigRegistryJMXClient(platformMBeanServer);
145 currentBundleContextServiceRegistrationHandler = new RecordingBundleContextServiceRegistrationHandler();
148 private void initBundleContext() {
149 doNothing().when(mockedServiceRegistration).unregister();
150 RegisterServiceAnswer answer = new RegisterServiceAnswer();
151 doAnswer(answer).when(mockedContext).registerService(Matchers.<String>any(), any(), Matchers.<Dictionary<String, ?>>any());
152 doAnswer(answer).when(mockedContext).registerService(Matchers.<Class>any(), any(), Matchers.<Dictionary<String, ?>>any());
156 public final void cleanUpConfigTransactionManagerImpl() {
157 configRegistryJMXRegistrator.close();
158 configRegistry.close();
159 TestingFixedThreadPool.cleanUp();
160 TestingScheduledThreadPoolImpl.cleanUp();
164 * Can be called in @After of tests if some other cleanup is needed that
165 * would be discarded by closing config beans in this method
167 protected void destroyAllConfigBeans() throws Exception {
168 ConfigTransactionJMXClient transaction = configRegistryClient
169 .createTransaction();
170 Set<ObjectName> all = transaction.lookupConfigBeans();
171 // workaround for getting same Module more times
172 while (all.size() > 0) {
173 transaction.destroyModule(all.iterator().next());
174 all = transaction.lookupConfigBeans();
176 transaction.commit();
179 protected void assertStatus(CommitStatus status, int expectedNewInstances,
180 int expectedRecreatedInstances, int expectedReusedInstances) {
181 assertEquals("New instances mismatch in " + status, expectedNewInstances, status.getNewInstances().size());
182 assertEquals("Recreated instances mismatch in " + status, expectedRecreatedInstances, status.getRecreatedInstances()
184 assertEquals("Reused instances mismatch in " + status, expectedReusedInstances, status.getReusedInstances()
189 protected void assertBeanCount(int i, String configMXBeanName) {
190 assertEquals(i, configRegistry.lookupConfigBeans(configMXBeanName)
196 * @param configBeanClass
197 * Empty constructor class of config bean to be instantiated
199 * @param implementationName
202 protected ClassBasedModuleFactory createClassBasedCBF(
203 Class<? extends Module> configBeanClass, String implementationName) {
204 return new ClassBasedModuleFactory(implementationName, configBeanClass);
207 protected BindingRuntimeContext getBindingRuntimeContext() {
208 return mock(BindingRuntimeContext.class);
211 public static interface BundleContextServiceRegistrationHandler {
213 void handleServiceRegistration(Class<?> clazz, Object serviceInstance, Dictionary<String, ?> props);
217 private class RegisterServiceAnswer implements Answer<ServiceRegistration<?>> {
220 public ServiceRegistration<?> answer(InvocationOnMock invocation) throws Throwable {
221 Object[] args = invocation.getArguments();
223 Preconditions.checkArgument(args.length == 3, "Unexpected arguments size (expected 3 was %s)", args.length);
225 Object serviceTypeRaw = args[0];
226 Object serviceInstance = args[1];
227 Dictionary<String, ?> props = (Dictionary<String, ?>) args[2];
229 if (serviceTypeRaw instanceof Class) {
230 Class<?> serviceType = (Class<?>) serviceTypeRaw;
231 invokeServiceHandler(serviceInstance, serviceType, props);
233 } else if(serviceTypeRaw instanceof String[]) {
234 for (String className : (String[]) serviceTypeRaw) {
235 invokeServiceHandler(serviceInstance, className, props);
237 } else if (serviceTypeRaw instanceof String) {
238 invokeServiceHandler(serviceInstance, (String) serviceTypeRaw, props);
240 throw new IllegalStateException("Not handling service registration of type, Unknown type" + serviceTypeRaw);
244 return mockedServiceRegistration;
247 public void invokeServiceHandler(Object serviceInstance, String className, Dictionary<String, ?> props) {
249 Class<?> serviceType = Class.forName(className);
250 invokeServiceHandler(serviceInstance, serviceType, props);
251 } catch (ClassNotFoundException e) {
252 throw new IllegalStateException("Not handling service registration of type " + className, e);
256 private void invokeServiceHandler(Object serviceInstance, Class<?> serviceType, Dictionary<String, ?> props) {
257 BundleContextServiceRegistrationHandler serviceRegistrationHandler = getBundleContextServiceRegistrationHandler(serviceType);
259 if (serviceRegistrationHandler != null) {
260 serviceRegistrationHandler.handleServiceRegistration(serviceType, serviceInstance, props);
266 * Expand inner exception wrapped by JMX
268 * @param innerObject jmx proxy which will be wrapped and returned
270 protected <T> T rethrowCause(final T innerObject) {
272 Object proxy = Proxy.newProxyInstance(innerObject.getClass().getClassLoader(),
273 innerObject.getClass().getInterfaces(), new InvocationHandler() {
275 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
277 return method.invoke(innerObject, args);
278 } catch (InvocationTargetException e) {
280 throw e.getTargetException();
281 } catch (RuntimeMBeanException e2) {
282 throw e2.getTargetException();