Merge "Minor fixes in md-sal and 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 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;
31
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;
48 import java.util.Set;
49
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;
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     protected BundleContext mockedContext = mock(BundleContext.class);
73     protected ServiceRegistration<?> mockedServiceRegistration;
74
75     private static final Logger logger = LoggerFactory.getLogger(AbstractConfigTest.class);
76
77     // Default handler for OSGi service registration
78     private static final BundleContextServiceRegistrationHandler noopServiceRegHandler = new BundleContextServiceRegistrationHandler() {
79         @Override
80         public void handleServiceRegistration(Object serviceInstance) {}
81     };
82
83     protected BundleContextServiceRegistrationHandler getBundleContextServiceRegistrationHandler(Class<?> serviceType) {
84         return noopServiceRegHandler;
85     }
86
87     // this method should be called in @Before
88     protected void initConfigTransactionManagerImpl(
89             ModuleFactoriesResolver resolver) {
90         final MBeanServer platformMBeanServer = ManagementFactory
91                 .getPlatformMBeanServer();
92
93         configRegistryJMXRegistrator = new ConfigRegistryJMXRegistrator(
94                 platformMBeanServer);
95         initBundleContext();
96
97         internalJmxRegistrator = new InternalJMXRegistrator(platformMBeanServer);
98         baseJmxRegistrator = new BaseJMXRegistrator(internalJmxRegistrator);
99
100         configRegistry = new ConfigRegistryImpl(resolver,
101                 platformMBeanServer, baseJmxRegistrator, getCodecRegistry());
102
103         try {
104             configRegistryJMXRegistrator.registerToJMX(configRegistry);
105         } catch (InstanceAlreadyExistsException e) {
106             throw new RuntimeException(e);
107         }
108         configRegistryClient = new ConfigRegistryJMXClient(platformMBeanServer);
109     }
110
111     private void initBundleContext() {
112         this.mockedServiceRegistration = mock(ServiceRegistration.class);
113         doNothing().when(mockedServiceRegistration).unregister();
114
115         RegisterServiceAnswer answer = new RegisterServiceAnswer();
116
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());
121     }
122
123
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);
131             } else {
132                 resources.add(resourceAsStream);
133             }
134         }
135         Assert.assertEquals("Some files were not found", Collections.<String>emptyList(), failedToFind);
136
137         return resources;
138     }
139
140     @After
141     public final void cleanUpConfigTransactionManagerImpl() {
142         configRegistryJMXRegistrator.close();
143         configRegistry.close();
144         TestingFixedThreadPool.cleanUp();
145         TestingScheduledThreadPoolImpl.cleanUp();
146     }
147
148     /**
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
151      */
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();
160         }
161         transaction.commit();
162     }
163
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"));
169     }
170
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()
175                 .size());
176         assertEquals("Reused instances mismatch in " + status, expectedReusedInstances, status.getReusedInstances()
177                 .size());
178     }
179
180     protected ObjectName createTestConfigBean(
181             ConfigTransactionJMXClient transaction, String implementationName,
182             String name) throws InstanceAlreadyExistsException {
183         return transaction.createModule(implementationName,
184                 name);
185     }
186
187     protected void assertBeanCount(int i, String configMXBeanName) {
188         assertEquals(i, configRegistry.lookupConfigBeans(configMXBeanName)
189                 .size());
190     }
191
192     protected void assertBeanExists(int count, String moduleName,
193             String instanceName) {
194         assertEquals(1,
195                 configRegistry.lookupConfigBeans(moduleName, instanceName)
196                         .size());
197     }
198
199     /**
200      *
201      * @param configBeanClass
202      *            Empty constructor class of config bean to be instantiated
203      *            whenever create
204      * @param implementationName
205      * @return
206      */
207     protected ClassBasedModuleFactory createClassBasedCBF(
208             Class<? extends Module> configBeanClass, String implementationName) {
209         return new ClassBasedModuleFactory(implementationName, configBeanClass);
210     }
211
212     protected CodecRegistry getCodecRegistry() {
213         return mock(CodecRegistry.class);
214     }
215
216
217     public static interface BundleContextServiceRegistrationHandler {
218
219        void handleServiceRegistration(Object serviceInstance);
220
221     }
222
223     private class RegisterServiceAnswer implements Answer<ServiceRegistration<?>> {
224
225         @Override
226         public ServiceRegistration<?> answer(InvocationOnMock invocation) throws Throwable {
227             Object[] args = invocation.getArguments();
228
229             Preconditions.checkArgument(args.length == 3, "Unexpected arguments size (expected 3 was %s)", args.length);
230
231             Object serviceTypeRaw = args[0];
232             Object serviceInstance = args[1];
233
234             if (serviceTypeRaw instanceof Class) {
235                 Class<?> serviceType = (Class<?>) serviceTypeRaw;
236                 invokeServiceHandler(serviceInstance, serviceType);
237
238             } else if(serviceTypeRaw instanceof String[]) {
239                 for (String className : (String[]) serviceTypeRaw) {
240                     try {
241                         Class<?> serviceType = Class.forName(className);
242                         invokeServiceHandler(serviceInstance, serviceType);
243                     } catch (ClassNotFoundException e) {
244                         logger.warn("Not handling service registration of type {} ", className, e);
245                     }
246                 }
247
248             } else
249                 logger.debug("Not handling service registration of type {}, Unknown type", serviceTypeRaw);
250
251             return mockedServiceRegistration;
252         }
253
254         private void invokeServiceHandler(Object serviceInstance, Class<?> serviceType) {
255             BundleContextServiceRegistrationHandler serviceRegistrationHandler = getBundleContextServiceRegistrationHandler(serviceType);
256
257             if (serviceRegistrationHandler != null) {
258                 serviceRegistrationHandler.handleServiceRegistration(serviceType.cast(serviceInstance));
259             }
260         }
261     }
262
263     /**
264      * Expand inner exception wrapped by JMX
265      *
266      * @param innerObject jmx proxy which will be wrapped and returned
267      */
268     protected <T> T rethrowCause(final T innerObject) {
269
270         Object proxy = Proxy.newProxyInstance(innerObject.getClass().getClassLoader(),
271                 innerObject.getClass().getInterfaces(), new InvocationHandler() {
272             @Override
273             public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
274                 try {
275                     return method.invoke(innerObject, args);
276                 } catch (InvocationTargetException e) {
277                     try {
278                         throw e.getTargetException();
279                     } catch (RuntimeMBeanException e2) {
280                         throw e2.getTargetException();
281                     }
282                 }
283             }
284         });
285         return (T) proxy;
286     }
287
288 }