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;
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.config.manager.impl.factoriesresolver.ModuleFactoriesResolver)}
61 * typically during setting up the each test.
63 public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServerTest {
64 protected ConfigRegistryJMXRegistrator configRegistryJMXRegistrator;
65 protected ConfigRegistryImpl configRegistry;
66 private JMXNotifierConfigRegistry notifyingConfigRegistry;
67 protected ConfigRegistryJMXClient configRegistryClient;
68 protected BaseJMXRegistrator baseJmxRegistrator;
70 protected BundleContext mockedContext;
72 protected ServiceRegistration<?> mockedServiceRegistration;
73 protected BundleContextServiceRegistrationHandler currentBundleContextServiceRegistrationHandler;
76 public void setUpMocks() {
77 MockitoAnnotations.initMocks(this);
80 // Default handler for OSGi service registration
81 protected static class RecordingBundleContextServiceRegistrationHandler implements BundleContextServiceRegistrationHandler {
82 private final List<RegistrationHolder> registrations = new LinkedList<>();
84 public void handleServiceRegistration(final Class<?> clazz, final Object serviceInstance, final Dictionary<String, ?> props) {
85 this.registrations.add(new RegistrationHolder(clazz, serviceInstance, props));
88 public List<RegistrationHolder> getRegistrations() {
89 return this.registrations;
92 protected static class RegistrationHolder {
93 protected final Class<?> clazz;
94 protected final Object instance;
95 protected final Dictionary<String, ?> props;
97 public RegistrationHolder(final Class<?> clazz, final Object instance, final Dictionary<String, ?> props) {
99 this.instance = instance;
105 protected BundleContextServiceRegistrationHandler getBundleContextServiceRegistrationHandler(final Class<?> serviceType) {
106 return this.currentBundleContextServiceRegistrationHandler;
109 // this method should be called in @Before
110 protected void initConfigTransactionManagerImpl(final ModuleFactoriesResolver resolver) {
112 final MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
114 this.configRegistryJMXRegistrator = new ConfigRegistryJMXRegistrator(platformMBeanServer);
117 this.baseJmxRegistrator = new BaseJMXRegistrator(platformMBeanServer);
119 this.configRegistry = new ConfigRegistryImpl(resolver, platformMBeanServer, this.baseJmxRegistrator, new BindingContextProvider() {
121 public synchronized void update(final ClassLoadingStrategy classLoadingStrategy, final SchemaContextProvider ctxProvider) {
126 public synchronized BindingRuntimeContext getBindingContext() {
127 return getBindingRuntimeContext();
130 this.notifyingConfigRegistry = new JMXNotifierConfigRegistry(this.configRegistry, platformMBeanServer);
133 this.configRegistryJMXRegistrator.registerToJMXNoNotifications(this.configRegistry);
134 this.configRegistryJMXRegistrator.registerToJMX(this.notifyingConfigRegistry);
135 } catch (final InstanceAlreadyExistsException e) {
136 throw new RuntimeException(e);
138 this.configRegistryClient = new ConfigRegistryJMXClient(platformMBeanServer);
139 this.currentBundleContextServiceRegistrationHandler = new RecordingBundleContextServiceRegistrationHandler();
142 private void initBundleContext() {
143 doNothing().when(this.mockedServiceRegistration).unregister();
144 final RegisterServiceAnswer answer = new RegisterServiceAnswer();
145 doAnswer(answer).when(this.mockedContext).registerService(Matchers.<String>any(), any(), Matchers.<Dictionary<String, ?>>any());
146 doAnswer(answer).when(this.mockedContext).registerService(Matchers.<Class<?>>any(), any(), Matchers.<Dictionary<String, ?>>any());
150 public final void cleanUpConfigTransactionManagerImpl() {
151 this.configRegistryJMXRegistrator.close();
152 this.notifyingConfigRegistry.close();
153 this.configRegistry.close();
154 TestingFixedThreadPool.cleanUp();
155 TestingScheduledThreadPoolImpl.cleanUp();
159 * Can be called in @After of tests if some other cleanup is needed that
160 * would be discarded by closing config beans in this method
162 protected void destroyAllConfigBeans() throws Exception {
163 final ConfigTransactionJMXClient transaction = this.configRegistryClient
164 .createTransaction();
165 Set<ObjectName> all = transaction.lookupConfigBeans();
166 // workaround for getting same Module more times
167 while (all.size() > 0) {
168 transaction.destroyModule(all.iterator().next());
169 all = transaction.lookupConfigBeans();
171 transaction.commit();
174 protected void assertStatus(final CommitStatus status, final int expectedNewInstances,
175 final int expectedRecreatedInstances, final int expectedReusedInstances) {
176 assertEquals("New instances mismatch in " + status, expectedNewInstances, status.getNewInstances().size());
177 assertEquals("Recreated instances mismatch in " + status, expectedRecreatedInstances,
178 status.getRecreatedInstances().size());
179 assertEquals("Reused instances mismatch in " + status, expectedReusedInstances,
180 status.getReusedInstances().size());
184 protected void assertBeanCount(final int i, final String configMXBeanName) {
185 assertEquals(i, this.configRegistry.lookupConfigBeans(configMXBeanName).size());
190 * @param configBeanClass
191 * Empty constructor class of config bean to be instantiated
193 * @param implementationName
196 protected ClassBasedModuleFactory createClassBasedCBF(final Class<? extends Module> configBeanClass,
197 final String implementationName) {
198 return new ClassBasedModuleFactory(implementationName, configBeanClass);
201 protected BindingRuntimeContext getBindingRuntimeContext() {
202 return mock(BindingRuntimeContext.class);
205 public interface BundleContextServiceRegistrationHandler {
206 void handleServiceRegistration(Class<?> clazz, Object serviceInstance, Dictionary<String, ?> props);
209 private class RegisterServiceAnswer implements Answer<ServiceRegistration<?>> {
211 public ServiceRegistration<?> answer(final InvocationOnMock invocation) throws Throwable {
212 final Object[] args = invocation.getArguments();
214 Preconditions.checkArgument(args.length == 3, "Unexpected arguments size (expected 3 was %s)", args.length);
216 final Object serviceTypeRaw = args[0];
217 final Object serviceInstance = args[1];
218 @SuppressWarnings("unchecked")
220 Dictionary<String, ?> props = (Dictionary<String, ?>) args[2];
222 if (serviceTypeRaw instanceof Class) {
223 final Class<?> serviceType = (Class<?>) serviceTypeRaw;
224 invokeServiceHandler(serviceInstance, serviceType, props);
225 } else if (serviceTypeRaw instanceof String[]) {
226 for (final String className : (String[]) serviceTypeRaw) {
227 invokeServiceHandler(serviceInstance, className, props);
229 } else if (serviceTypeRaw instanceof String) {
230 invokeServiceHandler(serviceInstance, (String) serviceTypeRaw, props);
232 throw new IllegalStateException("Not handling service registration of type, Unknown type" + serviceTypeRaw);
235 return AbstractConfigTest.this.mockedServiceRegistration;
238 public void invokeServiceHandler(final Object serviceInstance, final String className, final Dictionary<String, ?> props) {
240 final Class<?> serviceType = Class.forName(className);
241 invokeServiceHandler(serviceInstance, serviceType, props);
242 } catch (final ClassNotFoundException e) {
243 throw new IllegalStateException("Not handling service registration of type " + className, e);
247 private void invokeServiceHandler(final Object serviceInstance, final Class<?> serviceType, final Dictionary<String, ?> props) {
248 final BundleContextServiceRegistrationHandler serviceRegistrationHandler = getBundleContextServiceRegistrationHandler(serviceType);
250 if (serviceRegistrationHandler != null) {
251 serviceRegistrationHandler.handleServiceRegistration(serviceType, serviceInstance, props);
257 * Expand inner exception wrapped by JMX
259 * @param innerObject jmx proxy which will be wrapped and returned
261 protected <T> T rethrowCause(final T innerObject) {
262 @SuppressWarnings("unchecked")
263 final T proxy = (T)Proxy.newProxyInstance(innerObject.getClass().getClassLoader(),
264 innerObject.getClass().getInterfaces(), (proxy1, method, args) -> {
266 return method.invoke(innerObject, args);
267 } catch (final InvocationTargetException e) {
269 throw e.getTargetException();
270 } catch (final RuntimeMBeanException e2) {
271 throw e2.getTargetException();
280 * removes contents of the directory
281 * @param dir to be cleaned
282 * @throws IOException
284 protected void cleanDirectory(final File dir) throws IOException {
285 if (!dir.isDirectory()) {
286 throw new IllegalStateException("dir must be a directory");
289 final File[] files = dir.listFiles();
291 throw new IOException("Failed to list contents of " + dir);
294 for (final File file : files) {
295 if (file.isDirectory()) {