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

©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.