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.InvocationHandler;
21 import java.lang.reflect.InvocationTargetException;
22 import java.lang.reflect.Method;
23 import java.lang.reflect.Proxy;
24 import java.util.Dictionary;
25 import java.util.LinkedList;
26 import java.util.List;
28 import javax.management.InstanceAlreadyExistsException;
29 import javax.management.MBeanServer;
30 import javax.management.ObjectName;
31 import javax.management.RuntimeMBeanException;
32 import org.junit.After;
33 import org.junit.Before;
34 import org.mockito.Matchers;
35 import org.mockito.Mock;
36 import org.mockito.MockitoAnnotations;
37 import org.mockito.invocation.InvocationOnMock;
38 import org.mockito.stubbing.Answer;
39 import org.opendaylight.controller.config.api.jmx.CommitStatus;
40 import org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver;
41 import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
42 import org.opendaylight.controller.config.manager.impl.jmx.ConfigRegistryJMXRegistrator;
43 import org.opendaylight.controller.config.manager.impl.jmx.InternalJMXRegistrator;
44 import org.opendaylight.controller.config.manager.impl.osgi.mapping.BindingContextProvider;
45 import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolImpl;
46 import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPool;
47 import org.opendaylight.controller.config.spi.Module;
48 import org.opendaylight.controller.config.util.ConfigRegistryJMXClient;
49 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
50 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
51 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
52 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
53 import org.osgi.framework.BundleContext;
54 import org.osgi.framework.ServiceRegistration;
57 * Each test that relies on
58 * {@link org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl}
59 * needs to subclass this test.
60 * {@link org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl} is
61 * registered to platform MBean Server using
62 * {@link #initConfigTransactionManagerImpl(org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver)}
63 * typically during setting up the each test.
65 public abstract class AbstractConfigTest extends
66 AbstractLockedPlatformMBeanServerTest {
67 protected ConfigRegistryJMXRegistrator configRegistryJMXRegistrator;
68 protected ConfigRegistryImpl configRegistry;
69 protected ConfigRegistryJMXClient configRegistryClient;
70 protected BaseJMXRegistrator baseJmxRegistrator;
71 protected InternalJMXRegistrator internalJmxRegistrator;
73 protected BundleContext mockedContext;
75 protected ServiceRegistration<?> mockedServiceRegistration;
78 public void setUpMocks() {
79 MockitoAnnotations.initMocks(this);
83 // Default handler for OSGi service registration
84 protected static class RecordingBundleContextServiceRegistrationHandler implements BundleContextServiceRegistrationHandler {
85 private final List<RegistrationHolder> registrations = new LinkedList<>();
87 public void handleServiceRegistration(Class<?> clazz, Object serviceInstance, Dictionary<String, ?> props) {
89 registrations.add(new RegistrationHolder(clazz, serviceInstance, props));
92 public List<RegistrationHolder> getRegistrations() {
96 protected static class RegistrationHolder {
97 protected final Class<?> clazz;
98 protected final Object instance;
99 protected final Dictionary<String, ?> props;
101 public RegistrationHolder(Class<?> clazz, Object instance, Dictionary<String, ?> props) {
103 this.instance = instance;
110 protected BundleContextServiceRegistrationHandler currentBundleContextServiceRegistrationHandler;
112 protected BundleContextServiceRegistrationHandler getBundleContextServiceRegistrationHandler(Class<?> serviceType) {
113 return currentBundleContextServiceRegistrationHandler;
116 // this method should be called in @Before
117 protected void initConfigTransactionManagerImpl(
118 ModuleFactoriesResolver resolver) {
120 final MBeanServer platformMBeanServer = ManagementFactory
121 .getPlatformMBeanServer();
123 configRegistryJMXRegistrator = new ConfigRegistryJMXRegistrator(platformMBeanServer);
126 internalJmxRegistrator = new InternalJMXRegistrator(platformMBeanServer);
127 baseJmxRegistrator = new BaseJMXRegistrator(internalJmxRegistrator);
129 configRegistry = new ConfigRegistryImpl(resolver, platformMBeanServer, baseJmxRegistrator, new BindingContextProvider() {
131 public synchronized void update(final ClassLoadingStrategy classLoadingStrategy, final SchemaContextProvider ctxProvider) {
136 public synchronized BindingRuntimeContext getBindingContext() {
137 return getBindingRuntimeContext();
142 configRegistryJMXRegistrator.registerToJMX(configRegistry);
143 } catch (InstanceAlreadyExistsException e) {
144 throw new RuntimeException(e);
146 configRegistryClient = new ConfigRegistryJMXClient(platformMBeanServer);
147 currentBundleContextServiceRegistrationHandler = new RecordingBundleContextServiceRegistrationHandler();
150 private void initBundleContext() {
151 doNothing().when(mockedServiceRegistration).unregister();
152 RegisterServiceAnswer answer = new RegisterServiceAnswer();
153 doAnswer(answer).when(mockedContext).registerService(Matchers.<String>any(), any(), Matchers.<Dictionary<String, ?>>any());
154 doAnswer(answer).when(mockedContext).registerService(Matchers.<Class>any(), any(), Matchers.<Dictionary<String, ?>>any());
158 public final void cleanUpConfigTransactionManagerImpl() {
159 configRegistryJMXRegistrator.close();
160 configRegistry.close();
161 TestingFixedThreadPool.cleanUp();
162 TestingScheduledThreadPoolImpl.cleanUp();
166 * Can be called in @After of tests if some other cleanup is needed that
167 * would be discarded by closing config beans in this method
169 protected void destroyAllConfigBeans() throws Exception {
170 ConfigTransactionJMXClient transaction = configRegistryClient
171 .createTransaction();
172 Set<ObjectName> all = transaction.lookupConfigBeans();
173 // workaround for getting same Module more times
174 while (all.size() > 0) {
175 transaction.destroyModule(all.iterator().next());
176 all = transaction.lookupConfigBeans();
178 transaction.commit();
181 protected void assertStatus(CommitStatus status, int expectedNewInstances,
182 int expectedRecreatedInstances, int expectedReusedInstances) {
183 assertEquals("New instances mismatch in " + status, expectedNewInstances, status.getNewInstances().size());
184 assertEquals("Recreated instances mismatch in " + status, expectedRecreatedInstances, status.getRecreatedInstances()
186 assertEquals("Reused instances mismatch in " + status, expectedReusedInstances, status.getReusedInstances()
191 protected void assertBeanCount(int i, String configMXBeanName) {
192 assertEquals(i, configRegistry.lookupConfigBeans(configMXBeanName)
198 * @param configBeanClass
199 * Empty constructor class of config bean to be instantiated
201 * @param implementationName
204 protected ClassBasedModuleFactory createClassBasedCBF(
205 Class<? extends Module> configBeanClass, String implementationName) {
206 return new ClassBasedModuleFactory(implementationName, configBeanClass);
209 protected BindingRuntimeContext getBindingRuntimeContext() {
210 return mock(BindingRuntimeContext.class);
213 public static interface BundleContextServiceRegistrationHandler {
215 void handleServiceRegistration(Class<?> clazz, Object serviceInstance, Dictionary<String, ?> props);
219 private class RegisterServiceAnswer implements Answer<ServiceRegistration<?>> {
222 public ServiceRegistration<?> answer(InvocationOnMock invocation) throws Throwable {
223 Object[] args = invocation.getArguments();
225 Preconditions.checkArgument(args.length == 3, "Unexpected arguments size (expected 3 was %s)", args.length);
227 Object serviceTypeRaw = args[0];
228 Object serviceInstance = args[1];
229 Dictionary<String, ?> props = (Dictionary<String, ?>) args[2];
231 if (serviceTypeRaw instanceof Class) {
232 Class<?> serviceType = (Class<?>) serviceTypeRaw;
233 invokeServiceHandler(serviceInstance, serviceType, props);
235 } else if(serviceTypeRaw instanceof String[]) {
236 for (String className : (String[]) serviceTypeRaw) {
237 invokeServiceHandler(serviceInstance, className, props);
239 } else if (serviceTypeRaw instanceof String) {
240 invokeServiceHandler(serviceInstance, (String) serviceTypeRaw, props);
242 throw new IllegalStateException("Not handling service registration of type, Unknown type" + serviceTypeRaw);
246 return mockedServiceRegistration;
249 public void invokeServiceHandler(Object serviceInstance, String className, Dictionary<String, ?> props) {
251 Class<?> serviceType = Class.forName(className);
252 invokeServiceHandler(serviceInstance, serviceType, props);
253 } catch (ClassNotFoundException e) {
254 throw new IllegalStateException("Not handling service registration of type " + className, e);
258 private void invokeServiceHandler(Object serviceInstance, Class<?> serviceType, Dictionary<String, ?> props) {
259 BundleContextServiceRegistrationHandler serviceRegistrationHandler = getBundleContextServiceRegistrationHandler(serviceType);
261 if (serviceRegistrationHandler != null) {
262 serviceRegistrationHandler.handleServiceRegistration(serviceType, serviceInstance, props);
268 * Expand inner exception wrapped by JMX
270 * @param innerObject jmx proxy which will be wrapped and returned
272 protected <T> T rethrowCause(final T innerObject) {
274 Object proxy = Proxy.newProxyInstance(innerObject.getClass().getClassLoader(),
275 innerObject.getClass().getInterfaces(), new InvocationHandler() {
277 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
279 return method.invoke(innerObject, args);
280 } catch (InvocationTargetException e) {
282 throw e.getTargetException();
283 } catch (RuntimeMBeanException e2) {
284 throw e2.getTargetException();
294 * removes contents of the directory
295 * @param dir to be cleaned
296 * @throws IOException
298 protected void cleanDirectory(File dir) throws IOException {
299 if (!dir.isDirectory()) {
300 throw new IllegalStateException("dir must be a directory");
303 final File[] files = dir.listFiles();
305 throw new IOException("Failed to list contents of " + dir);
308 for (File file : files) {
309 if (file.isDirectory()) {