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.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
27 import org.osgi.framework.BundleContext;
28 import org.osgi.framework.ServiceRegistration;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
32 import javax.management.InstanceAlreadyExistsException;
33 import javax.management.MBeanServer;
34 import javax.management.ObjectName;
35 import javax.management.RuntimeMBeanException;
36 import java.io.Closeable;
37 import java.io.InputStream;
38 import java.lang.management.ManagementFactory;
39 import java.util.ArrayList;
40 import java.util.Collection;
41 import java.util.Collections;
42 import java.lang.reflect.InvocationHandler;
43 import java.lang.reflect.InvocationTargetException;
44 import java.lang.reflect.Method;
45 import java.lang.reflect.Proxy;
46 import java.util.Dictionary;
47 import java.util.List;
50 import static org.junit.Assert.assertEquals;
51 import static org.mockito.Matchers.any;
52 import static org.mockito.Mockito.doAnswer;
53 import static org.mockito.Mockito.doNothing;
54 import static org.mockito.Mockito.mock;
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;
72 protected BundleContext mockedContext = mock(BundleContext.class);
73 protected ServiceRegistration<?> mockedServiceRegistration;
75 private static final Logger logger = LoggerFactory.getLogger(AbstractConfigTest.class);
77 // Default handler for OSGi service registration
78 private static final BundleContextServiceRegistrationHandler noopServiceRegHandler = new BundleContextServiceRegistrationHandler() {
80 public void handleServiceRegistration(Object serviceInstance) {}
83 protected BundleContextServiceRegistrationHandler getBundleContextServiceRegistrationHandler(Class<?> serviceType) {
84 return noopServiceRegHandler;
87 // this method should be called in @Before
88 protected void initConfigTransactionManagerImpl(
89 ModuleFactoriesResolver resolver) {
90 final MBeanServer platformMBeanServer = ManagementFactory
91 .getPlatformMBeanServer();
93 configRegistryJMXRegistrator = new ConfigRegistryJMXRegistrator(
97 internalJmxRegistrator = new InternalJMXRegistrator(platformMBeanServer);
98 baseJmxRegistrator = new BaseJMXRegistrator(internalJmxRegistrator);
100 configRegistry = new ConfigRegistryImpl(resolver,
101 platformMBeanServer, baseJmxRegistrator, getCodecRegistry());
104 configRegistryJMXRegistrator.registerToJMX(configRegistry);
105 } catch (InstanceAlreadyExistsException e) {
106 throw new RuntimeException(e);
108 configRegistryClient = new ConfigRegistryJMXClient(platformMBeanServer);
111 private void initBundleContext() {
112 this.mockedServiceRegistration = mock(ServiceRegistration.class);
113 doNothing().when(mockedServiceRegistration).unregister();
115 RegisterServiceAnswer answer = new RegisterServiceAnswer();
117 doAnswer(answer).when(mockedContext).registerService(Matchers.any(String[].class),
118 any(Closeable.class), Matchers.<Dictionary<String, ?>>any());
119 doAnswer(answer).when(mockedContext).registerService(Matchers.<Class<Closeable>>any(), any(Closeable.class),
120 Matchers.<Dictionary<String, ?>>any());
124 public Collection<InputStream> getFilesAsInputStreams(List<String> paths) {
125 final Collection<InputStream> resources = new ArrayList<>();
126 List<String> failedToFind = new ArrayList<>();
127 for (String path : paths) {
128 InputStream resourceAsStream = getClass().getResourceAsStream(path);
129 if (resourceAsStream == null) {
130 failedToFind.add(path);
132 resources.add(resourceAsStream);
135 Assert.assertEquals("Some files were not found", Collections.<String>emptyList(), failedToFind);
141 public final void cleanUpConfigTransactionManagerImpl() {
142 configRegistryJMXRegistrator.close();
143 configRegistry.close();
144 TestingFixedThreadPool.cleanUp();
145 TestingScheduledThreadPoolImpl.cleanUp();
149 * Can be called in @After of tests if some other cleanup is needed that
150 * would be discarded by closing config beans in this method
152 protected void destroyAllConfigBeans() throws Exception {
153 ConfigTransactionJMXClient transaction = configRegistryClient
154 .createTransaction();
155 Set<ObjectName> all = transaction.lookupConfigBeans();
156 // workaround for getting same Module more times
157 while (all.size() > 0) {
158 transaction.destroyModule(all.iterator().next());
159 all = transaction.lookupConfigBeans();
161 transaction.commit();
164 protected void assertSame(ObjectName oN1, ObjectName oN2) {
165 assertEquals(oN1.getKeyProperty("instanceName"),
166 oN2.getKeyProperty("instanceName"));
167 assertEquals(oN1.getKeyProperty("interfaceName"),
168 oN2.getKeyProperty("interfaceName"));
171 protected void assertStatus(CommitStatus status, int expectedNewInstances,
172 int expectedRecreatedInstances, int expectedReusedInstances) {
173 assertEquals("New instances mismatch in " + status, expectedNewInstances, status.getNewInstances().size());
174 assertEquals("Recreated instances mismatch in " + status, expectedRecreatedInstances, status.getRecreatedInstances()
176 assertEquals("Reused instances mismatch in " + status, expectedReusedInstances, status.getReusedInstances()
180 protected ObjectName createTestConfigBean(
181 ConfigTransactionJMXClient transaction, String implementationName,
182 String name) throws InstanceAlreadyExistsException {
183 return transaction.createModule(implementationName,
187 protected void assertBeanCount(int i, String configMXBeanName) {
188 assertEquals(i, configRegistry.lookupConfigBeans(configMXBeanName)
192 protected void assertBeanExists(int count, String moduleName,
193 String instanceName) {
195 configRegistry.lookupConfigBeans(moduleName, instanceName)
201 * @param configBeanClass
202 * Empty constructor class of config bean to be instantiated
204 * @param implementationName
207 protected ClassBasedModuleFactory createClassBasedCBF(
208 Class<? extends Module> configBeanClass, String implementationName) {
209 return new ClassBasedModuleFactory(implementationName, configBeanClass);
212 protected CodecRegistry getCodecRegistry() {
213 return mock(CodecRegistry.class);
216 public static interface BundleContextServiceRegistrationHandler {
218 void handleServiceRegistration(Object serviceInstance);
222 private class RegisterServiceAnswer implements Answer<ServiceRegistration<?>> {
225 public ServiceRegistration<?> answer(InvocationOnMock invocation) throws Throwable {
226 Object[] args = invocation.getArguments();
228 Preconditions.checkArgument(args.length == 3, "Unexpected arguments size (expected 3 was %s)", args.length);
230 Object serviceTypeRaw = args[0];
231 Object serviceInstance = args[1];
233 if (serviceTypeRaw instanceof Class) {
234 Class<?> serviceType = (Class<?>) serviceTypeRaw;
235 invokeServiceHandler(serviceInstance, serviceType);
237 } else if(serviceTypeRaw instanceof String[]) {
238 for (String className : (String[]) serviceTypeRaw) {
240 Class<?> serviceType = Class.forName(className);
241 invokeServiceHandler(serviceInstance, serviceType);
242 } catch (ClassNotFoundException e) {
243 logger.warn("Not handling service registration of type {} ", className, e);
248 logger.debug("Not handling service registration of type {}, Unknown type", serviceTypeRaw);
250 return mockedServiceRegistration;
253 private void invokeServiceHandler(Object serviceInstance, Class<?> serviceType) {
254 BundleContextServiceRegistrationHandler serviceRegistrationHandler = getBundleContextServiceRegistrationHandler(serviceType);
256 if (serviceRegistrationHandler != null) {
257 serviceRegistrationHandler.handleServiceRegistration(serviceType.cast(serviceInstance));
263 * Expand inner exception wrapped by JMX
265 * @param innerObject jmx proxy which will be wrapped and returned
267 protected <T> T rethrowCause(final T innerObject) {
269 Object proxy = Proxy.newProxyInstance(innerObject.getClass().getClassLoader(),
270 innerObject.getClass().getInterfaces(), new InvocationHandler() {
272 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
274 return method.invoke(innerObject, args);
275 } catch (InvocationTargetException e) {
277 throw e.getTargetException();
278 } catch (RuntimeMBeanException e2) {
279 throw e2.getTargetException();