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