Mechanical code cleanup (config)
[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.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
50 import org.opendaylight.yangtools.sal.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             registrations.add(new RegistrationHolder(clazz, serviceInstance, props));
87         }
88
89         public List<RegistrationHolder> getRegistrations() {
90             return 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 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         configRegistryJMXRegistrator = new ConfigRegistryJMXRegistrator(platformMBeanServer);
116         initBundleContext();
117
118         baseJmxRegistrator = new BaseJMXRegistrator(platformMBeanServer);
119
120         configRegistry = new ConfigRegistryImpl(resolver, platformMBeanServer, 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         notifyingConfigRegistry = new JMXNotifierConfigRegistry(this.configRegistry, platformMBeanServer);
132
133         try {
134             configRegistryJMXRegistrator.registerToJMXNoNotifications(configRegistry);
135             configRegistryJMXRegistrator.registerToJMX(notifyingConfigRegistry);
136         } catch (InstanceAlreadyExistsException e) {
137             throw new RuntimeException(e);
138         }
139         configRegistryClient = new ConfigRegistryJMXClient(platformMBeanServer);
140         currentBundleContextServiceRegistrationHandler = new RecordingBundleContextServiceRegistrationHandler();
141     }
142
143     private void initBundleContext() {
144         doNothing().when(mockedServiceRegistration).unregister();
145         RegisterServiceAnswer answer = new RegisterServiceAnswer();
146         doAnswer(answer).when(mockedContext).registerService(Matchers.<String>any(), any(), Matchers.<Dictionary<String, ?>>any());
147         doAnswer(answer).when(mockedContext).registerService(Matchers.<Class>any(), any(), Matchers.<Dictionary<String, ?>>any());
148     }
149
150     @After
151     public final void cleanUpConfigTransactionManagerImpl() {
152         configRegistryJMXRegistrator.close();
153         notifyingConfigRegistry.close();
154         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         ConfigTransactionJMXClient transaction = 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, 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             Object[] args = invocation.getArguments();
214
215             Preconditions.checkArgument(args.length == 3, "Unexpected arguments size (expected 3 was %s)", args.length);
216
217             Object serviceTypeRaw = args[0];
218             Object serviceInstance = args[1];
219             @SuppressWarnings("unchecked")
220             Dictionary<String, ?> props = (Dictionary<String, ?>) args[2];
221
222             if (serviceTypeRaw instanceof Class) {
223                 Class<?> serviceType = (Class<?>) serviceTypeRaw;
224                 invokeServiceHandler(serviceInstance, serviceType, props);
225             } else if (serviceTypeRaw instanceof String[]) {
226                 for (String className : (String[]) serviceTypeRaw) {
227                     invokeServiceHandler(serviceInstance, className, props);
228                 }
229             } else if (serviceTypeRaw instanceof String) {
230                 invokeServiceHandler(serviceInstance, (String) serviceTypeRaw, props);
231             } else {
232                 throw new IllegalStateException("Not handling service registration of type, Unknown type" +  serviceTypeRaw);
233             }
234
235             return mockedServiceRegistration;
236         }
237
238         public void invokeServiceHandler(final Object serviceInstance, final String className, final Dictionary<String, ?> props) {
239             try {
240                 Class<?> serviceType = Class.forName(className);
241                 invokeServiceHandler(serviceInstance, serviceType, props);
242             } catch (ClassNotFoundException e) {
243                 throw new IllegalStateException("Not handling service registration of type " +  className, e);
244             }
245         }
246
247         private void invokeServiceHandler(final Object serviceInstance, final Class<?> serviceType, final Dictionary<String, ?> props) {
248             BundleContextServiceRegistrationHandler serviceRegistrationHandler = getBundleContextServiceRegistrationHandler(serviceType);
249
250             if (serviceRegistrationHandler != null) {
251                 serviceRegistrationHandler.handleServiceRegistration(serviceType, serviceInstance, props);
252             }
253         }
254     }
255
256     /**
257      * Expand inner exception wrapped by JMX
258      *
259      * @param innerObject jmx proxy which will be wrapped and returned
260      */
261     protected <T> T rethrowCause(final T innerObject) {
262         @SuppressWarnings("unchecked")
263         final T proxy = (T)Proxy.newProxyInstance(innerObject.getClass().getClassLoader(),
264                 innerObject.getClass().getInterfaces(), new InvocationHandler() {
265                         @Override
266                         public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
267                             try {
268                                 return method.invoke(innerObject, args);
269                             } catch (InvocationTargetException e) {
270                                 try {
271                                     throw e.getTargetException();
272                                 } catch (RuntimeMBeanException e2) {
273                                     throw e2.getTargetException();
274                                 }
275                             }
276                         }
277                     }
278         );
279         return proxy;
280     }
281
282     /**
283      * removes contents of the directory
284      * @param dir to be cleaned
285      * @throws IOException
286      */
287     protected void cleanDirectory(final File dir) throws IOException {
288         if (!dir.isDirectory()) {
289             throw new IllegalStateException("dir must be a directory");
290         }
291
292         final File[] files = dir.listFiles();
293         if (files == null) {
294             throw new IOException("Failed to list contents of " + dir);
295         }
296
297         for (File file : files) {
298             if (file.isDirectory()) {
299                 cleanDirectory(dir);
300             }
301             file.delete();
302         }
303     }
304 }

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