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