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;
15 import com.google.common.base.Preconditions;
17 import java.io.IOException;
18 import java.lang.management.ManagementFactory;
19 import java.lang.reflect.InvocationHandler;
20 import java.lang.reflect.InvocationTargetException;
21 import java.lang.reflect.Method;
22 import java.lang.reflect.Proxy;
23 import java.util.Dictionary;
24 import java.util.LinkedList;
25 import java.util.List;
27 import javax.management.InstanceAlreadyExistsException;
28 import javax.management.MBeanServer;
29 import javax.management.ObjectName;
30 import javax.management.RuntimeMBeanException;
31 import org.junit.After;
32 import org.junit.Before;
33 import org.mockito.Matchers;
34 import org.mockito.Mock;
35 import org.mockito.MockitoAnnotations;
36 import org.mockito.invocation.InvocationOnMock;
37 import org.mockito.stubbing.Answer;
38 import org.opendaylight.controller.config.api.jmx.CommitStatus;
39 import org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver;
40 import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
41 import org.opendaylight.controller.config.manager.impl.jmx.ConfigRegistryJMXRegistrator;
42 import org.opendaylight.controller.config.manager.impl.jmx.JMXNotifierConfigRegistry;
43 import org.opendaylight.controller.config.manager.impl.osgi.mapping.BindingContextProvider;
44 import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolImpl;
45 import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPool;
46 import org.opendaylight.controller.config.spi.Module;
47 import org.opendaylight.controller.config.util.ConfigRegistryJMXClient;
48 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
49 import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
50 import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
51 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
52 import org.osgi.framework.BundleContext;
53 import org.osgi.framework.ServiceRegistration;
56 * Each test that relies on
57 * {@link org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl}
58 * needs to subclass this test.
59 * {@link org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl} is
60 * registered to platform MBean Server using
61 * {@link #initConfigTransactionManagerImpl(org.opendaylight.controller.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 implements BundleContextServiceRegistrationHandler {
83 private final List<RegistrationHolder> registrations = new LinkedList<>();
85 public void handleServiceRegistration(final Class<?> clazz, final Object serviceInstance, final Dictionary<String, ?> props) {
86 this.registrations.add(new RegistrationHolder(clazz, serviceInstance, props));
89 public List<RegistrationHolder> getRegistrations() {
90 return this.registrations;
93 protected static class RegistrationHolder {
94 protected final Class<?> clazz;
95 protected final Object instance;
96 protected final Dictionary<String, ?> props;
98 public RegistrationHolder(final Class<?> clazz, final Object instance, final Dictionary<String, ?> props) {
100 this.instance = instance;
106 protected BundleContextServiceRegistrationHandler getBundleContextServiceRegistrationHandler(final Class<?> serviceType) {
107 return this.currentBundleContextServiceRegistrationHandler;
110 // this method should be called in @Before
111 protected void initConfigTransactionManagerImpl(final ModuleFactoriesResolver resolver) {
113 final MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
115 this.configRegistryJMXRegistrator = new ConfigRegistryJMXRegistrator(platformMBeanServer);
118 this.baseJmxRegistrator = new BaseJMXRegistrator(platformMBeanServer);
120 this.configRegistry = new ConfigRegistryImpl(resolver, platformMBeanServer, this.baseJmxRegistrator, new BindingContextProvider() {
122 public synchronized void update(final ClassLoadingStrategy classLoadingStrategy, final SchemaContextProvider ctxProvider) {
127 public synchronized BindingRuntimeContext getBindingContext() {
128 return getBindingRuntimeContext();
131 this.notifyingConfigRegistry = new JMXNotifierConfigRegistry(this.configRegistry, platformMBeanServer);
134 this.configRegistryJMXRegistrator.registerToJMXNoNotifications(this.configRegistry);
135 this.configRegistryJMXRegistrator.registerToJMX(this.notifyingConfigRegistry);
136 } catch (final InstanceAlreadyExistsException e) {
137 throw new RuntimeException(e);
139 this.configRegistryClient = new ConfigRegistryJMXClient(platformMBeanServer);
140 this.currentBundleContextServiceRegistrationHandler = new RecordingBundleContextServiceRegistrationHandler();
143 private void initBundleContext() {
144 doNothing().when(this.mockedServiceRegistration).unregister();
145 final RegisterServiceAnswer answer = new RegisterServiceAnswer();
146 doAnswer(answer).when(this.mockedContext).registerService(Matchers.<String>any(), any(), Matchers.<Dictionary<String, ?>>any());
147 doAnswer(answer).when(this.mockedContext).registerService(Matchers.<Class>any(), any(), Matchers.<Dictionary<String, ?>>any());
151 public final void cleanUpConfigTransactionManagerImpl() {
152 this.configRegistryJMXRegistrator.close();
153 this.notifyingConfigRegistry.close();
154 this.configRegistry.close();
155 TestingFixedThreadPool.cleanUp();
156 TestingScheduledThreadPoolImpl.cleanUp();
160 * Can be called in @After of tests if some other cleanup is needed that
161 * would be discarded by closing config beans in this method
163 protected void destroyAllConfigBeans() throws Exception {
164 final ConfigTransactionJMXClient transaction = this.configRegistryClient
165 .createTransaction();
166 Set<ObjectName> all = transaction.lookupConfigBeans();
167 // workaround for getting same Module more times
168 while (all.size() > 0) {
169 transaction.destroyModule(all.iterator().next());
170 all = transaction.lookupConfigBeans();
172 transaction.commit();
175 protected void assertStatus(final CommitStatus status, final int expectedNewInstances,
176 final int expectedRecreatedInstances, final int expectedReusedInstances) {
177 assertEquals("New instances mismatch in " + status, expectedNewInstances, status.getNewInstances().size());
178 assertEquals("Recreated instances mismatch in " + status, expectedRecreatedInstances,
179 status.getRecreatedInstances().size());
180 assertEquals("Reused instances mismatch in " + status, expectedReusedInstances,
181 status.getReusedInstances().size());
185 protected void assertBeanCount(final int i, final String configMXBeanName) {
186 assertEquals(i, this.configRegistry.lookupConfigBeans(configMXBeanName).size());
191 * @param configBeanClass
192 * Empty constructor class of config bean to be instantiated
194 * @param implementationName
197 protected ClassBasedModuleFactory createClassBasedCBF(final Class<? extends Module> configBeanClass,
198 final String implementationName) {
199 return new ClassBasedModuleFactory(implementationName, configBeanClass);
202 protected BindingRuntimeContext getBindingRuntimeContext() {
203 return mock(BindingRuntimeContext.class);
206 public interface BundleContextServiceRegistrationHandler {
207 void handleServiceRegistration(Class<?> clazz, Object serviceInstance, Dictionary<String, ?> props);
210 private class RegisterServiceAnswer implements Answer<ServiceRegistration<?>> {
212 public ServiceRegistration<?> answer(final InvocationOnMock invocation) throws Throwable {
213 final Object[] args = invocation.getArguments();
215 Preconditions.checkArgument(args.length == 3, "Unexpected arguments size (expected 3 was %s)", args.length);
217 final Object serviceTypeRaw = args[0];
218 final Object serviceInstance = args[1];
219 @SuppressWarnings("unchecked")
221 Dictionary<String, ?> props = (Dictionary<String, ?>) args[2];
223 if (serviceTypeRaw instanceof Class) {
224 final Class<?> serviceType = (Class<?>) serviceTypeRaw;
225 invokeServiceHandler(serviceInstance, serviceType, props);
226 } else if (serviceTypeRaw instanceof String[]) {
227 for (final String className : (String[]) serviceTypeRaw) {
228 invokeServiceHandler(serviceInstance, className, props);
230 } else if (serviceTypeRaw instanceof String) {
231 invokeServiceHandler(serviceInstance, (String) serviceTypeRaw, props);
233 throw new IllegalStateException("Not handling service registration of type, Unknown type" + serviceTypeRaw);
236 return AbstractConfigTest.this.mockedServiceRegistration;
239 public void invokeServiceHandler(final Object serviceInstance, final String className, final Dictionary<String, ?> props) {
241 final Class<?> serviceType = Class.forName(className);
242 invokeServiceHandler(serviceInstance, serviceType, props);
243 } catch (final ClassNotFoundException e) {
244 throw new IllegalStateException("Not handling service registration of type " + className, e);
248 private void invokeServiceHandler(final Object serviceInstance, final Class<?> serviceType, final Dictionary<String, ?> props) {
249 final BundleContextServiceRegistrationHandler serviceRegistrationHandler = getBundleContextServiceRegistrationHandler(serviceType);
251 if (serviceRegistrationHandler != null) {
252 serviceRegistrationHandler.handleServiceRegistration(serviceType, serviceInstance, props);
258 * Expand inner exception wrapped by JMX
260 * @param innerObject jmx proxy which will be wrapped and returned
262 protected <T> T rethrowCause(final T innerObject) {
263 @SuppressWarnings("unchecked")
264 final T proxy = (T)Proxy.newProxyInstance(innerObject.getClass().getClassLoader(),
265 innerObject.getClass().getInterfaces(), new InvocationHandler() {
267 public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
269 return method.invoke(innerObject, args);
270 } catch (final InvocationTargetException e) {
272 throw e.getTargetException();
273 } catch (final RuntimeMBeanException e2) {
274 throw e2.getTargetException();
284 * removes contents of the directory
285 * @param dir to be cleaned
286 * @throws IOException
288 protected void cleanDirectory(final File dir) throws IOException {
289 if (!dir.isDirectory()) {
290 throw new IllegalStateException("dir must be a directory");
293 final File[] files = dir.listFiles();
295 throw new IOException("Failed to list contents of " + dir);
298 for (final File file : files) {
299 if (file.isDirectory()) {