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.jmx.JMXNotifierConfigRegistry;
45 import org.opendaylight.controller.config.manager.impl.osgi.mapping.BindingContextProvider;
46 import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolImpl;
47 import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPool;
48 import org.opendaylight.controller.config.spi.Module;
49 import org.opendaylight.controller.config.util.ConfigRegistryJMXClient;
50 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
51 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
52 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
53 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
54 import org.osgi.framework.BundleContext;
55 import org.osgi.framework.ServiceRegistration;
58 * Each test that relies on
59 * {@link org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl}
60 * needs to subclass this test.
61 * {@link org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl} is
62 * registered to platform MBean Server using
63 * {@link #initConfigTransactionManagerImpl(org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver)}
64 * typically during setting up the each test.
66 public abstract class AbstractConfigTest extends
67 AbstractLockedPlatformMBeanServerTest {
68 protected ConfigRegistryJMXRegistrator configRegistryJMXRegistrator;
69 protected ConfigRegistryImpl configRegistry;
70 private JMXNotifierConfigRegistry notifyingConfigRegistry;
71 protected ConfigRegistryJMXClient configRegistryClient;
72 protected BaseJMXRegistrator baseJmxRegistrator;
73 protected InternalJMXRegistrator internalJmxRegistrator;
75 protected BundleContext mockedContext;
77 protected ServiceRegistration<?> mockedServiceRegistration;
80 public void setUpMocks() {
81 MockitoAnnotations.initMocks(this);
85 // Default handler for OSGi service registration
86 protected static class RecordingBundleContextServiceRegistrationHandler implements BundleContextServiceRegistrationHandler {
87 private final List<RegistrationHolder> registrations = new LinkedList<>();
89 public void handleServiceRegistration(Class<?> clazz, Object serviceInstance, Dictionary<String, ?> props) {
91 registrations.add(new RegistrationHolder(clazz, serviceInstance, props));
94 public List<RegistrationHolder> getRegistrations() {
98 protected static class RegistrationHolder {
99 protected final Class<?> clazz;
100 protected final Object instance;
101 protected final Dictionary<String, ?> props;
103 public RegistrationHolder(Class<?> clazz, Object instance, Dictionary<String, ?> props) {
105 this.instance = instance;
112 protected BundleContextServiceRegistrationHandler currentBundleContextServiceRegistrationHandler;
114 protected BundleContextServiceRegistrationHandler getBundleContextServiceRegistrationHandler(Class<?> serviceType) {
115 return currentBundleContextServiceRegistrationHandler;
118 // this method should be called in @Before
119 protected void initConfigTransactionManagerImpl(
120 ModuleFactoriesResolver resolver) {
122 final MBeanServer platformMBeanServer = ManagementFactory
123 .getPlatformMBeanServer();
125 configRegistryJMXRegistrator = new ConfigRegistryJMXRegistrator(platformMBeanServer);
128 internalJmxRegistrator = new InternalJMXRegistrator(platformMBeanServer);
129 baseJmxRegistrator = new BaseJMXRegistrator(internalJmxRegistrator);
131 configRegistry = new ConfigRegistryImpl(resolver, platformMBeanServer, baseJmxRegistrator, new BindingContextProvider() {
133 public synchronized void update(final ClassLoadingStrategy classLoadingStrategy, final SchemaContextProvider ctxProvider) {
138 public synchronized BindingRuntimeContext getBindingContext() {
139 return getBindingRuntimeContext();
142 notifyingConfigRegistry = new JMXNotifierConfigRegistry(this.configRegistry, platformMBeanServer);
145 configRegistryJMXRegistrator.registerToJMXNoNotifications(configRegistry);
146 configRegistryJMXRegistrator.registerToJMX(notifyingConfigRegistry);
147 } catch (InstanceAlreadyExistsException e) {
148 throw new RuntimeException(e);
150 configRegistryClient = new ConfigRegistryJMXClient(platformMBeanServer);
151 currentBundleContextServiceRegistrationHandler = new RecordingBundleContextServiceRegistrationHandler();
154 private void initBundleContext() {
155 doNothing().when(mockedServiceRegistration).unregister();
156 RegisterServiceAnswer answer = new RegisterServiceAnswer();
157 doAnswer(answer).when(mockedContext).registerService(Matchers.<String>any(), any(), Matchers.<Dictionary<String, ?>>any());
158 doAnswer(answer).when(mockedContext).registerService(Matchers.<Class>any(), any(), Matchers.<Dictionary<String, ?>>any());
162 public final void cleanUpConfigTransactionManagerImpl() {
163 configRegistryJMXRegistrator.close();
164 notifyingConfigRegistry.close();
165 configRegistry.close();
166 TestingFixedThreadPool.cleanUp();
167 TestingScheduledThreadPoolImpl.cleanUp();
171 * Can be called in @After of tests if some other cleanup is needed that
172 * would be discarded by closing config beans in this method
174 protected void destroyAllConfigBeans() throws Exception {
175 ConfigTransactionJMXClient transaction = configRegistryClient
176 .createTransaction();
177 Set<ObjectName> all = transaction.lookupConfigBeans();
178 // workaround for getting same Module more times
179 while (all.size() > 0) {
180 transaction.destroyModule(all.iterator().next());
181 all = transaction.lookupConfigBeans();
183 transaction.commit();
186 protected void assertStatus(CommitStatus status, int expectedNewInstances,
187 int expectedRecreatedInstances, int expectedReusedInstances) {
188 assertEquals("New instances mismatch in " + status, expectedNewInstances, status.getNewInstances().size());
189 assertEquals("Recreated instances mismatch in " + status, expectedRecreatedInstances, status.getRecreatedInstances()
191 assertEquals("Reused instances mismatch in " + status, expectedReusedInstances, status.getReusedInstances()
196 protected void assertBeanCount(int i, String configMXBeanName) {
197 assertEquals(i, configRegistry.lookupConfigBeans(configMXBeanName)
203 * @param configBeanClass
204 * Empty constructor class of config bean to be instantiated
206 * @param implementationName
209 protected ClassBasedModuleFactory createClassBasedCBF(
210 Class<? extends Module> configBeanClass, String implementationName) {
211 return new ClassBasedModuleFactory(implementationName, configBeanClass);
214 protected BindingRuntimeContext getBindingRuntimeContext() {
215 return mock(BindingRuntimeContext.class);
218 public static interface BundleContextServiceRegistrationHandler {
220 void handleServiceRegistration(Class<?> clazz, Object serviceInstance, Dictionary<String, ?> props);
224 private class RegisterServiceAnswer implements Answer<ServiceRegistration<?>> {
227 public ServiceRegistration<?> answer(InvocationOnMock invocation) throws Throwable {
228 Object[] args = invocation.getArguments();
230 Preconditions.checkArgument(args.length == 3, "Unexpected arguments size (expected 3 was %s)", args.length);
232 Object serviceTypeRaw = args[0];
233 Object serviceInstance = args[1];
234 Dictionary<String, ?> props = (Dictionary<String, ?>) args[2];
236 if (serviceTypeRaw instanceof Class) {
237 Class<?> serviceType = (Class<?>) serviceTypeRaw;
238 invokeServiceHandler(serviceInstance, serviceType, props);
240 } else if(serviceTypeRaw instanceof String[]) {
241 for (String className : (String[]) serviceTypeRaw) {
242 invokeServiceHandler(serviceInstance, className, props);
244 } else if (serviceTypeRaw instanceof String) {
245 invokeServiceHandler(serviceInstance, (String) serviceTypeRaw, props);
247 throw new IllegalStateException("Not handling service registration of type, Unknown type" + serviceTypeRaw);
251 return mockedServiceRegistration;
254 public void invokeServiceHandler(Object serviceInstance, String className, Dictionary<String, ?> props) {
256 Class<?> serviceType = Class.forName(className);
257 invokeServiceHandler(serviceInstance, serviceType, props);
258 } catch (ClassNotFoundException e) {
259 throw new IllegalStateException("Not handling service registration of type " + className, e);
263 private void invokeServiceHandler(Object serviceInstance, Class<?> serviceType, Dictionary<String, ?> props) {
264 BundleContextServiceRegistrationHandler serviceRegistrationHandler = getBundleContextServiceRegistrationHandler(serviceType);
266 if (serviceRegistrationHandler != null) {
267 serviceRegistrationHandler.handleServiceRegistration(serviceType, serviceInstance, props);
273 * Expand inner exception wrapped by JMX
275 * @param innerObject jmx proxy which will be wrapped and returned
277 protected <T> T rethrowCause(final T innerObject) {
279 Object proxy = Proxy.newProxyInstance(innerObject.getClass().getClassLoader(),
280 innerObject.getClass().getInterfaces(), new InvocationHandler() {
282 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
284 return method.invoke(innerObject, args);
285 } catch (InvocationTargetException e) {
287 throw e.getTargetException();
288 } catch (RuntimeMBeanException e2) {
289 throw e2.getTargetException();
299 * removes contents of the directory
300 * @param dir to be cleaned
301 * @throws IOException
303 protected void cleanDirectory(File dir) throws IOException {
304 if (!dir.isDirectory()) {
305 throw new IllegalStateException("dir must be a directory");
308 final File[] files = dir.listFiles();
310 throw new IOException("Failed to list contents of " + dir);
313 for (File file : files) {
314 if (file.isDirectory()) {