2 * Copyright (c) 2013, 2017 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;
18 import java.io.IOException;
19 import java.lang.management.ManagementFactory;
20 import java.lang.reflect.InvocationTargetException;
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.JMXNotifierConfigRegistry;
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.mdsal.binding.generator.api.ClassLoadingStrategy;
49 import org.opendaylight.mdsal.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
61 * .config.manager.impl.factoriesresolver.ModuleFactoriesResolver)}
62 * typically during setting up the each test.
64 public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServerTest {
65 protected ConfigRegistryJMXRegistrator configRegistryJMXRegistrator;
66 protected ConfigRegistryImpl configRegistry;
67 private JMXNotifierConfigRegistry notifyingConfigRegistry;
68 protected ConfigRegistryJMXClient configRegistryClient;
69 protected BaseJMXRegistrator baseJmxRegistrator;
71 protected BundleContext mockedContext;
73 protected ServiceRegistration<?> mockedServiceRegistration;
74 protected BundleContextServiceRegistrationHandler currentBundleContextServiceRegistrationHandler;
77 public void setUpMocks() {
78 MockitoAnnotations.initMocks(this);
81 // Default handler for OSGi service registration
82 protected static class RecordingBundleContextServiceRegistrationHandler
83 implements BundleContextServiceRegistrationHandler {
84 private final List<RegistrationHolder> registrations = new LinkedList<>();
87 public void handleServiceRegistration(final Class<?> clazz, final Object serviceInstance,
88 final Dictionary<String, ?> props) {
89 this.registrations.add(new RegistrationHolder(clazz, serviceInstance, props));
92 public List<RegistrationHolder> getRegistrations() {
93 return this.registrations;
96 protected static class RegistrationHolder {
97 protected final Class<?> clazz;
98 protected final Object instance;
99 protected final Dictionary<String, ?> props;
101 public RegistrationHolder(final Class<?> clazz, final Object instance, final Dictionary<String, ?> props) {
103 this.instance = instance;
109 protected BundleContextServiceRegistrationHandler getBundleContextServiceRegistrationHandler(
110 final Class<?> serviceType) {
111 return this.currentBundleContextServiceRegistrationHandler;
114 // this method should be called in @Before
115 protected void initConfigTransactionManagerImpl(final ModuleFactoriesResolver resolver) {
117 final MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
119 this.configRegistryJMXRegistrator = new ConfigRegistryJMXRegistrator(platformMBeanServer);
122 this.baseJmxRegistrator = new BaseJMXRegistrator(platformMBeanServer);
124 this.configRegistry = new ConfigRegistryImpl(resolver, platformMBeanServer, this.baseJmxRegistrator,
125 new BindingContextProvider() {
127 public synchronized void update(final ClassLoadingStrategy classLoadingStrategy,
128 final SchemaContextProvider ctxProvider) {
133 public synchronized BindingRuntimeContext getBindingContext() {
134 return getBindingRuntimeContext();
137 this.notifyingConfigRegistry = new JMXNotifierConfigRegistry(this.configRegistry, platformMBeanServer);
140 this.configRegistryJMXRegistrator.registerToJMXNoNotifications(this.configRegistry);
141 this.configRegistryJMXRegistrator.registerToJMX(this.notifyingConfigRegistry);
142 } catch (final InstanceAlreadyExistsException e) {
143 throw new RuntimeException(e);
145 this.configRegistryClient = new ConfigRegistryJMXClient(platformMBeanServer);
146 this.currentBundleContextServiceRegistrationHandler = new RecordingBundleContextServiceRegistrationHandler();
149 private void initBundleContext() {
150 doNothing().when(this.mockedServiceRegistration).unregister();
151 final RegisterServiceAnswer answer = new RegisterServiceAnswer();
152 doAnswer(answer).when(this.mockedContext).registerService(Matchers.<String>any(), any(),
153 Matchers.<Dictionary<String, ?>>any());
154 doAnswer(answer).when(this.mockedContext).registerService(Matchers.<Class<?>>any(), any(),
155 Matchers.<Dictionary<String, ?>>any());
159 public final void cleanUpConfigTransactionManagerImpl() {
160 this.configRegistryJMXRegistrator.close();
161 this.notifyingConfigRegistry.close();
162 this.configRegistry.close();
163 TestingFixedThreadPool.cleanUp();
164 TestingScheduledThreadPoolImpl.cleanUp();
168 * Can be called in @After of tests if some other cleanup is needed that would
169 * be discarded by closing config beans in this method.
171 protected void destroyAllConfigBeans() throws Exception {
172 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
173 Set<ObjectName> all = transaction.lookupConfigBeans();
174 // workaround for getting same Module more times
175 while (all.size() > 0) {
176 transaction.destroyModule(all.iterator().next());
177 all = transaction.lookupConfigBeans();
179 transaction.commit();
182 protected void assertStatus(final CommitStatus status, final int expectedNewInstances,
183 final int expectedRecreatedInstances, final int expectedReusedInstances) {
184 assertEquals("New instances mismatch in " + status, expectedNewInstances, status.getNewInstances().size());
185 assertEquals("Recreated instances mismatch in " + status, expectedRecreatedInstances,
186 status.getRecreatedInstances().size());
187 assertEquals("Reused instances mismatch in " + status, expectedReusedInstances,
188 status.getReusedInstances().size());
191 protected void assertBeanCount(final int index, final String configMXBeanName) {
192 assertEquals(index, this.configRegistry.lookupConfigBeans(configMXBeanName).size());
198 * @param configBeanClass
199 * Empty constructor class of config bean to be instantiated whenever
201 * @param implementationName name
204 protected ClassBasedModuleFactory createClassBasedCBF(final Class<? extends Module> configBeanClass,
205 final String implementationName) {
206 return new ClassBasedModuleFactory(implementationName, configBeanClass);
209 protected BindingRuntimeContext getBindingRuntimeContext() {
210 return mock(BindingRuntimeContext.class);
213 public interface BundleContextServiceRegistrationHandler {
214 void handleServiceRegistration(Class<?> clazz, Object serviceInstance, Dictionary<String, ?> props);
217 private class RegisterServiceAnswer implements Answer<ServiceRegistration<?>> {
219 public ServiceRegistration<?> answer(final InvocationOnMock invocation) throws Throwable {
220 final Object[] args = invocation.getArguments();
222 Preconditions.checkArgument(args.length == 3, "Unexpected arguments size (expected 3 was %s)", args.length);
224 final Object serviceTypeRaw = args[0];
225 final Object serviceInstance = args[1];
226 @SuppressWarnings("unchecked")
227 final Dictionary<String, ?> props = (Dictionary<String, ?>) args[2];
229 if (serviceTypeRaw instanceof Class) {
230 final Class<?> serviceType = (Class<?>) serviceTypeRaw;
231 invokeServiceHandler(serviceInstance, serviceType, props);
232 } else if (serviceTypeRaw instanceof String[]) {
233 for (final String className : (String[]) serviceTypeRaw) {
234 invokeServiceHandler(serviceInstance, className, props);
236 } else if (serviceTypeRaw instanceof String) {
237 invokeServiceHandler(serviceInstance, (String) serviceTypeRaw, props);
239 throw new IllegalStateException(
240 "Not handling service registration of type, Unknown type" + serviceTypeRaw);
243 return AbstractConfigTest.this.mockedServiceRegistration;
246 public void invokeServiceHandler(final Object serviceInstance, final String className,
247 final Dictionary<String, ?> props) {
249 final Class<?> serviceType = Class.forName(className);
250 invokeServiceHandler(serviceInstance, serviceType, props);
251 } catch (final ClassNotFoundException e) {
252 throw new IllegalStateException("Not handling service registration of type " + className, e);
256 private void invokeServiceHandler(final Object serviceInstance, final Class<?> serviceType,
257 final Dictionary<String, ?> props) {
258 final BundleContextServiceRegistrationHandler serviceRegistrationHandler =
259 getBundleContextServiceRegistrationHandler(serviceType);
261 if (serviceRegistrationHandler != null) {
262 serviceRegistrationHandler.handleServiceRegistration(serviceType, serviceInstance, props);
268 * Expand inner exception wrapped by JMX.
271 * jmx proxy which will be wrapped and returned
273 protected <T> T rethrowCause(final T innerObject) {
274 @SuppressWarnings({ "unchecked", "checkstyle:avoidHidingCauseException" })
275 final T proxy = (T) Proxy.newProxyInstance(innerObject.getClass().getClassLoader(),
276 innerObject.getClass().getInterfaces(), (proxy1, method, args) -> {
278 return method.invoke(innerObject, args);
279 } catch (final InvocationTargetException e) {
281 throw e.getTargetException();
282 } catch (final RuntimeMBeanException e2) {
283 throw e2.getTargetException();
291 * removes contents of the directory.
295 * @throws IOException IO exception
297 protected void cleanDirectory(final File dir) throws IOException {
298 if (!dir.isDirectory()) {
299 throw new IllegalStateException("dir must be a directory");
302 final File[] files = dir.listFiles();
304 throw new IOException("Failed to list contents of " + dir);
307 for (final File file : files) {
308 if (file.isDirectory()) {