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 com.google.common.base.Preconditions;
11 import junit.framework.Assert;
12 import org.junit.After;
13 import org.mockito.Matchers;
14 import org.mockito.invocation.InvocationOnMock;
15 import org.mockito.stubbing.Answer;
16 import org.opendaylight.controller.config.api.jmx.CommitStatus;
17 import org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver;
18 import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
19 import org.opendaylight.controller.config.manager.impl.jmx.ConfigRegistryJMXRegistrator;
20 import org.opendaylight.controller.config.manager.impl.jmx.InternalJMXRegistrator;
21 import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolImpl;
22 import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPool;
23 import org.opendaylight.controller.config.spi.Module;
24 import org.opendaylight.controller.config.util.ConfigRegistryJMXClient;
25 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
26 import org.osgi.framework.BundleContext;
27 import org.osgi.framework.ServiceRegistration;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
31 import javax.management.InstanceAlreadyExistsException;
32 import javax.management.MBeanServer;
33 import javax.management.ObjectName;
34 import javax.management.RuntimeMBeanException;
35 import java.io.Closeable;
36 import java.io.InputStream;
37 import java.lang.management.ManagementFactory;
38 import java.util.ArrayList;
39 import java.util.Collection;
40 import java.util.Collections;
41 import java.lang.reflect.InvocationHandler;
42 import java.lang.reflect.InvocationTargetException;
43 import java.lang.reflect.Method;
44 import java.lang.reflect.Proxy;
45 import java.util.Dictionary;
46 import java.util.List;
49 import static org.junit.Assert.assertEquals;
50 import static org.mockito.Matchers.any;
51 import static org.mockito.Mockito.doAnswer;
52 import static org.mockito.Mockito.doNothing;
53 import static org.mockito.Mockito.mock;
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
65 AbstractLockedPlatformMBeanServerTest {
66 protected ConfigRegistryJMXRegistrator configRegistryJMXRegistrator;
67 protected ConfigRegistryImpl configRegistry;
68 protected ConfigRegistryJMXClient configRegistryClient;
69 protected BaseJMXRegistrator baseJmxRegistrator;
70 protected InternalJMXRegistrator internalJmxRegistrator;
71 protected BundleContext mockedContext = mock(BundleContext.class);
72 protected ServiceRegistration<?> mockedServiceRegistration;
74 private static final Logger logger = LoggerFactory.getLogger(AbstractConfigTest.class);
76 // Default handler for OSGi service registration
77 private static final BundleContextServiceRegistrationHandler noopServiceRegHandler = new BundleContextServiceRegistrationHandler() {
79 public void handleServiceRegistration(Object serviceInstance) {}
82 protected BundleContextServiceRegistrationHandler getBundleContextServiceRegistrationHandler(Class<?> serviceType) {
83 return noopServiceRegHandler;
86 // this method should be called in @Before
87 protected void initConfigTransactionManagerImpl(
88 ModuleFactoriesResolver resolver) {
89 final MBeanServer platformMBeanServer = ManagementFactory
90 .getPlatformMBeanServer();
92 configRegistryJMXRegistrator = new ConfigRegistryJMXRegistrator(
96 internalJmxRegistrator = new InternalJMXRegistrator(platformMBeanServer);
97 baseJmxRegistrator = new BaseJMXRegistrator(internalJmxRegistrator);
99 configRegistry = new ConfigRegistryImpl(resolver,
100 platformMBeanServer, baseJmxRegistrator);
103 configRegistryJMXRegistrator.registerToJMX(configRegistry);
104 } catch (InstanceAlreadyExistsException e) {
105 throw new RuntimeException(e);
107 configRegistryClient = new ConfigRegistryJMXClient(platformMBeanServer);
110 private void initBundleContext() {
111 this.mockedServiceRegistration = mock(ServiceRegistration.class);
112 doNothing().when(mockedServiceRegistration).unregister();
114 RegisterServiceAnswer answer = new RegisterServiceAnswer();
116 doAnswer(answer).when(mockedContext).registerService(Matchers.any(String[].class),
117 any(Closeable.class), Matchers.<Dictionary<String, ?>>any());
118 doAnswer(answer).when(mockedContext).registerService(Matchers.<Class<Closeable>>any(), any(Closeable.class),
119 Matchers.<Dictionary<String, ?>>any());
123 public Collection<InputStream> getFilesAsInputStreams(List<String> paths) {
124 final Collection<InputStream> resources = new ArrayList<>();
125 List<String> failedToFind = new ArrayList<>();
126 for (String path : paths) {
127 InputStream resourceAsStream = getClass().getResourceAsStream(path);
128 if (resourceAsStream == null) {
129 failedToFind.add(path);
131 resources.add(resourceAsStream);
134 Assert.assertEquals("Some files were not found", Collections.<String>emptyList(), failedToFind);
140 public final void cleanUpConfigTransactionManagerImpl() {
141 configRegistryJMXRegistrator.close();
142 configRegistry.close();
143 TestingFixedThreadPool.cleanUp();
144 TestingScheduledThreadPoolImpl.cleanUp();
148 * Can be called in @After of tests if some other cleanup is needed that
149 * would be discarded by closing config beans in this method
151 protected void destroyAllConfigBeans() throws Exception {
152 ConfigTransactionJMXClient transaction = configRegistryClient
153 .createTransaction();
154 Set<ObjectName> all = transaction.lookupConfigBeans();
155 // workaround for getting same Module more times
156 while (all.size() > 0) {
157 transaction.destroyModule(all.iterator().next());
158 all = transaction.lookupConfigBeans();
160 transaction.commit();
163 protected void assertSame(ObjectName oN1, ObjectName oN2) {
164 assertEquals(oN1.getKeyProperty("instanceName"),
165 oN2.getKeyProperty("instanceName"));
166 assertEquals(oN1.getKeyProperty("interfaceName"),
167 oN2.getKeyProperty("interfaceName"));
170 protected void assertStatus(CommitStatus status, int expectedNewInstances,
171 int expectedRecreatedInstances, int expectedReusedInstances) {
172 assertEquals("New instances mismatch in " + status, expectedNewInstances, status.getNewInstances().size());
173 assertEquals("Recreated instances mismatch in " + status, expectedRecreatedInstances, status.getRecreatedInstances()
175 assertEquals("Reused instances mismatch in " + status, expectedReusedInstances, status.getReusedInstances()
179 protected ObjectName createTestConfigBean(
180 ConfigTransactionJMXClient transaction, String implementationName,
181 String name) throws InstanceAlreadyExistsException {
182 return transaction.createModule(implementationName,
186 protected void assertBeanCount(int i, String configMXBeanName) {
187 assertEquals(i, configRegistry.lookupConfigBeans(configMXBeanName)
191 protected void assertBeanExists(int count, String moduleName,
192 String instanceName) {
194 configRegistry.lookupConfigBeans(moduleName, instanceName)
200 * @param configBeanClass
201 * Empty constructor class of config bean to be instantiated
203 * @param implementationName
206 protected ClassBasedModuleFactory createClassBasedCBF(
207 Class<? extends Module> configBeanClass, String implementationName) {
208 return new ClassBasedModuleFactory(implementationName, configBeanClass);
212 public static interface BundleContextServiceRegistrationHandler {
214 void handleServiceRegistration(Object serviceInstance);
218 private class RegisterServiceAnswer implements Answer {
221 public Object answer(InvocationOnMock invocation) throws Throwable {
222 Object[] args = invocation.getArguments();
224 Preconditions.checkArgument(args.length == 3, "Unexpected arguments size (expected 3 was %s)", args.length);
226 Object serviceTypeRaw = args[0];
227 Object serviceInstance = args[1];
229 if (serviceTypeRaw instanceof Class) {
230 Class<?> serviceType = (Class<?>) serviceTypeRaw;
231 invokeServiceHandler(serviceInstance, serviceType);
233 } else if(serviceTypeRaw instanceof String[]) {
234 for (String className : (String[]) serviceTypeRaw) {
236 Class<?> serviceType = Class.forName(className);
237 invokeServiceHandler(serviceInstance, serviceType);
238 } catch (ClassNotFoundException e) {
239 logger.warn("Not handling service registration of type {} ", className, e);
244 logger.debug("Not handling service registration of type {}, Unknown type", serviceTypeRaw);
246 return mockedServiceRegistration;
249 private void invokeServiceHandler(Object serviceInstance, Class<?> serviceType) {
250 BundleContextServiceRegistrationHandler serviceRegistrationHandler = getBundleContextServiceRegistrationHandler(serviceType);
252 if (serviceRegistrationHandler != null) {
253 serviceRegistrationHandler.handleServiceRegistration(serviceType.cast(serviceInstance));
259 * Expand inner exception wrapped by JMX
261 * @param innerObject jmx proxy which will be wrapped and returned
263 protected <T> T rethrowCause(final T innerObject) {
265 Object proxy = Proxy.newProxyInstance(innerObject.getClass().getClassLoader(),
266 innerObject.getClass().getInterfaces(), new InvocationHandler() {
268 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
270 return method.invoke(innerObject, args);
271 } catch (InvocationTargetException e) {
273 throw e.getTargetException();
274 } catch (RuntimeMBeanException e2) {
275 throw e2.getTargetException();