30da27f1a1dee6951d05fe59b96b81e319d936c6
[controller.git] / opendaylight / config / config-manager / src / test / java / org / opendaylight / controller / config / manager / impl / AbstractConfigTest.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.config.manager.impl;
9
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
16 import com.google.common.base.Preconditions;
17 import java.lang.management.ManagementFactory;
18 import java.lang.reflect.InvocationHandler;
19 import java.lang.reflect.InvocationTargetException;
20 import java.lang.reflect.Method;
21 import java.lang.reflect.Proxy;
22 import java.util.Dictionary;
23 import java.util.LinkedList;
24 import java.util.List;
25 import java.util.Set;
26 import javax.management.InstanceAlreadyExistsException;
27 import javax.management.MBeanServer;
28 import javax.management.ObjectName;
29 import javax.management.RuntimeMBeanException;
30 import org.junit.After;
31 import org.junit.Before;
32 import org.mockito.Matchers;
33 import org.mockito.Mock;
34 import org.mockito.MockitoAnnotations;
35 import org.mockito.invocation.InvocationOnMock;
36 import org.mockito.stubbing.Answer;
37 import org.opendaylight.controller.config.api.jmx.CommitStatus;
38 import org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver;
39 import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
40 import org.opendaylight.controller.config.manager.impl.jmx.ConfigRegistryJMXRegistrator;
41 import org.opendaylight.controller.config.manager.impl.jmx.InternalJMXRegistrator;
42 import org.opendaylight.controller.config.manager.impl.osgi.mapping.BindingContextProvider;
43 import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolImpl;
44 import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPool;
45 import org.opendaylight.controller.config.spi.Module;
46 import org.opendaylight.controller.config.util.ConfigRegistryJMXClient;
47 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
48 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
49 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
50 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
51 import org.osgi.framework.BundleContext;
52 import org.osgi.framework.ServiceRegistration;
53
54 /**
55  * Each test that relies on
56  * {@link org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl}
57  * needs to subclass this test.
58  * {@link org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl} is
59  * registered to platform MBean Server using
60  * {@link #initConfigTransactionManagerImpl(org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver)}
61  * typically during setting up the each test.
62  */
63 public abstract class AbstractConfigTest extends
64         AbstractLockedPlatformMBeanServerTest {
65     protected ConfigRegistryJMXRegistrator configRegistryJMXRegistrator;
66     protected ConfigRegistryImpl configRegistry;
67     protected ConfigRegistryJMXClient configRegistryClient;
68     protected BaseJMXRegistrator baseJmxRegistrator;
69     protected InternalJMXRegistrator internalJmxRegistrator;
70     @Mock
71     protected BundleContext mockedContext;
72     @Mock
73     protected ServiceRegistration<?> mockedServiceRegistration;
74
75     @Before
76     public void setUpMocks() {
77         MockitoAnnotations.initMocks(this);
78     }
79
80
81     // Default handler for OSGi service registration
82     protected static class RecordingBundleContextServiceRegistrationHandler implements BundleContextServiceRegistrationHandler {
83         private final List<RegistrationHolder> registrations = new LinkedList<>();
84         @Override
85         public void handleServiceRegistration(Class<?> clazz, Object serviceInstance, Dictionary<String, ?> props) {
86
87             registrations.add(new RegistrationHolder(clazz, serviceInstance, props));
88         }
89
90         public List<RegistrationHolder> getRegistrations() {
91             return registrations;
92         }
93
94         protected static class RegistrationHolder {
95             protected final Class<?> clazz;
96             protected final Object instance;
97             protected final Dictionary<String, ?> props;
98
99             public RegistrationHolder(Class<?> clazz, Object instance, Dictionary<String, ?> props) {
100                 this.clazz = clazz;
101                 this.instance = instance;
102                 this.props = props;
103             }
104         }
105
106     }
107
108     protected BundleContextServiceRegistrationHandler currentBundleContextServiceRegistrationHandler;
109
110     protected BundleContextServiceRegistrationHandler getBundleContextServiceRegistrationHandler(Class<?> serviceType) {
111         return currentBundleContextServiceRegistrationHandler;
112     }
113
114     // this method should be called in @Before
115     protected void initConfigTransactionManagerImpl(
116             ModuleFactoriesResolver resolver) {
117
118         final MBeanServer platformMBeanServer = ManagementFactory
119                 .getPlatformMBeanServer();
120
121         configRegistryJMXRegistrator = new ConfigRegistryJMXRegistrator(platformMBeanServer);
122         initBundleContext();
123
124         internalJmxRegistrator = new InternalJMXRegistrator(platformMBeanServer);
125         baseJmxRegistrator = new BaseJMXRegistrator(internalJmxRegistrator);
126
127         configRegistry = new ConfigRegistryImpl(resolver, platformMBeanServer, baseJmxRegistrator, new BindingContextProvider() {
128             @Override
129             public synchronized void update(final ClassLoadingStrategy classLoadingStrategy, final SchemaContextProvider ctxProvider) {
130                 // NOOP
131             }
132
133             @Override
134             public synchronized BindingRuntimeContext getBindingContext() {
135                 return getBindingRuntimeContext();
136             }
137         });
138
139         try {
140             configRegistryJMXRegistrator.registerToJMX(configRegistry);
141         } catch (InstanceAlreadyExistsException e) {
142             throw new RuntimeException(e);
143         }
144         configRegistryClient = new ConfigRegistryJMXClient(platformMBeanServer);
145         currentBundleContextServiceRegistrationHandler = new RecordingBundleContextServiceRegistrationHandler();
146     }
147
148     private void initBundleContext() {
149         doNothing().when(mockedServiceRegistration).unregister();
150         RegisterServiceAnswer answer = new RegisterServiceAnswer();
151         doAnswer(answer).when(mockedContext).registerService(Matchers.<String>any(), any(), Matchers.<Dictionary<String, ?>>any());
152         doAnswer(answer).when(mockedContext).registerService(Matchers.<Class>any(), any(), Matchers.<Dictionary<String, ?>>any());
153     }
154
155     @After
156     public final void cleanUpConfigTransactionManagerImpl() {
157         configRegistryJMXRegistrator.close();
158         configRegistry.close();
159         TestingFixedThreadPool.cleanUp();
160         TestingScheduledThreadPoolImpl.cleanUp();
161     }
162
163     /**
164      * Can be called in @After of tests if some other cleanup is needed that
165      * would be discarded by closing config beans in this method
166      */
167     protected void destroyAllConfigBeans() throws Exception {
168         ConfigTransactionJMXClient transaction = configRegistryClient
169                 .createTransaction();
170         Set<ObjectName> all = transaction.lookupConfigBeans();
171         // workaround for getting same Module more times
172         while (all.size() > 0) {
173             transaction.destroyModule(all.iterator().next());
174             all = transaction.lookupConfigBeans();
175         }
176         transaction.commit();
177     }
178
179     protected void assertStatus(CommitStatus status, int expectedNewInstances,
180             int expectedRecreatedInstances, int expectedReusedInstances) {
181         assertEquals("New instances mismatch in " + status, expectedNewInstances, status.getNewInstances().size());
182         assertEquals("Recreated instances mismatch in " + status, expectedRecreatedInstances, status.getRecreatedInstances()
183                 .size());
184         assertEquals("Reused instances mismatch in " + status, expectedReusedInstances, status.getReusedInstances()
185                 .size());
186     }
187
188
189     protected void assertBeanCount(int i, String configMXBeanName) {
190         assertEquals(i, configRegistry.lookupConfigBeans(configMXBeanName)
191                 .size());
192     }
193
194     /**
195      *
196      * @param configBeanClass
197      *            Empty constructor class of config bean to be instantiated
198      *            whenever create
199      * @param implementationName
200      * @return
201      */
202     protected ClassBasedModuleFactory createClassBasedCBF(
203             Class<? extends Module> configBeanClass, String implementationName) {
204         return new ClassBasedModuleFactory(implementationName, configBeanClass);
205     }
206
207     protected BindingRuntimeContext getBindingRuntimeContext() {
208         return mock(BindingRuntimeContext.class);
209     }
210
211     public static interface BundleContextServiceRegistrationHandler {
212
213         void handleServiceRegistration(Class<?> clazz, Object serviceInstance, Dictionary<String, ?> props);
214
215     }
216
217     private class RegisterServiceAnswer implements Answer<ServiceRegistration<?>> {
218
219         @Override
220         public ServiceRegistration<?> answer(InvocationOnMock invocation) throws Throwable {
221             Object[] args = invocation.getArguments();
222
223             Preconditions.checkArgument(args.length == 3, "Unexpected arguments size (expected 3 was %s)", args.length);
224
225             Object serviceTypeRaw = args[0];
226             Object serviceInstance = args[1];
227             Dictionary<String, ?> props = (Dictionary<String, ?>) args[2];
228
229             if (serviceTypeRaw instanceof Class) {
230                 Class<?> serviceType = (Class<?>) serviceTypeRaw;
231                 invokeServiceHandler(serviceInstance, serviceType, props);
232
233             } else if(serviceTypeRaw instanceof String[]) {
234                 for (String className : (String[]) serviceTypeRaw) {
235                     invokeServiceHandler(serviceInstance, className, props);
236                 }
237             } else if (serviceTypeRaw instanceof String) {
238                 invokeServiceHandler(serviceInstance, (String) serviceTypeRaw, props);
239             } else {
240                 throw new IllegalStateException("Not handling service registration of type, Unknown type" +  serviceTypeRaw);
241             }
242
243
244             return mockedServiceRegistration;
245         }
246
247         public void invokeServiceHandler(Object serviceInstance, String className, Dictionary<String, ?> props) {
248             try {
249                 Class<?> serviceType = Class.forName(className);
250                 invokeServiceHandler(serviceInstance, serviceType, props);
251             } catch (ClassNotFoundException e) {
252                 throw new IllegalStateException("Not handling service registration of type " +  className, e);
253             }
254         }
255
256         private void invokeServiceHandler(Object serviceInstance, Class<?> serviceType, Dictionary<String, ?> props) {
257             BundleContextServiceRegistrationHandler serviceRegistrationHandler = getBundleContextServiceRegistrationHandler(serviceType);
258
259             if (serviceRegistrationHandler != null) {
260                 serviceRegistrationHandler.handleServiceRegistration(serviceType, serviceInstance, props);
261             }
262         }
263     }
264
265     /**
266      * Expand inner exception wrapped by JMX
267      *
268      * @param innerObject jmx proxy which will be wrapped and returned
269      */
270     protected <T> T rethrowCause(final T innerObject) {
271
272         Object proxy = Proxy.newProxyInstance(innerObject.getClass().getClassLoader(),
273                 innerObject.getClass().getInterfaces(), new InvocationHandler() {
274                         @Override
275                         public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
276                             try {
277                                 return method.invoke(innerObject, args);
278                             } catch (InvocationTargetException e) {
279                                 try {
280                                     throw e.getTargetException();
281                                 } catch (RuntimeMBeanException e2) {
282                                     throw e2.getTargetException();
283                                 }
284                             }
285                         }
286                     }
287         );
288         return (T) proxy;
289     }
290
291 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.