mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Nicolas Capponi
11.32.2016 6f14605908036dd6c2cfc64f31f1d5d8d17f86a8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
/*
 * The contents of this file are subject to the terms of the Common Development and
 * Distribution License (the License). You may not use this file except in compliance with the
 * License.
 *
 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
 * specific language governing permission and limitations under the License.
 *
 * When distributing Covered Software, include this CDDL Header Notice in each file and include
 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
 * Header, with the fields enclosed by brackets [] replaced by your own identifying
 * information: "Portions Copyright [year] [name of copyright owner]".
 *
 * Copyright 2013-2015 ForgeRock AS.
 */
package org.opends.server;
 
import static org.mockito.Mockito.mock;
 
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.SortedSet;
import java.util.TreeSet;
 
import org.forgerock.opendj.config.AbsoluteInheritedDefaultBehaviorProvider;
import org.forgerock.opendj.config.AliasDefaultBehaviorProvider;
import org.forgerock.opendj.config.Configuration;
import org.forgerock.opendj.config.DefaultBehaviorProvider;
import org.forgerock.opendj.config.DefaultBehaviorProviderVisitor;
import org.forgerock.opendj.config.DefinedDefaultBehaviorProvider;
import org.forgerock.opendj.config.ManagedObjectDefinition;
import org.forgerock.opendj.config.PropertyDefinition;
import org.forgerock.opendj.config.PropertyOption;
import org.forgerock.opendj.config.RelativeInheritedDefaultBehaviorProvider;
import org.forgerock.opendj.config.UndefinedDefaultBehaviorProvider;
import org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues;
import org.mockito.invocation.InvocationOnMock;
 
/**
 * Provides Mockito mocks for Configuration objects with default values
 * corresponding to those defined in xml configuration files.
 * <p>
 * These mocks can be used like any other mocks, e.g, you can define stubs using
 * {@code when} method or verify calls using {@code verify} method.
 * <p>
 * Example:
 *
 * <pre>
 *  LDAPConnectionHandlerCfg mockCfg = mockCfg(LDAPConnectionHandlerCfg.class);
 *  assertThat(mockCfg.getMaxRequestSize()).isEqualTo(5 * 1000 * 1000);
 * </pre>
 */
public final class ConfigurationMock {
 
    private static final ConfigAnswer CONFIG_ANSWER = new ConfigAnswer();
 
    private static final LegacyConfigAnswer LEGACY_CONFIG_ANSWER = new LegacyConfigAnswer();
 
    /**
     * Returns a mock for the provided configuration class.
     * <p>
     * If a setting has a default value, the mock automatically returns the
     * default value when the getter is called on the setting.
     * <p>
     * It is possible to override this default behavior with the usual methods
     * calls with Mockito (e.g, {@code when} method).
     *
     * @param <T>
     *            The type of configuration.
     * @param configClass
     *            The configuration class.
     * @return a mock
     */
    public static <T extends Configuration> T mockCfg(Class<T> configClass) {
        return mock(configClass, CONFIG_ANSWER);
    }
 
    /**
     * Returns a mock for the provided configuration class.
     * <p>
     * If a setting has a default value, the mock automatically returns the
     * default value when the getter is called on the setting.
     * <p>
     * It is possible to override this default behavior with the usual methods
     * calls with Mockito (e.g, {@code when} method).
     *
     * @param <T>
     *            The type of configuration.
     * @param configClass
     *            The configuration class.
     * @return a mock
     */
    public static <T extends org.opends.server.admin.Configuration> T legacyMockCfg(Class<T> configClass) {
        return mock(configClass, LEGACY_CONFIG_ANSWER);
    }
 
    /**
     * A stubbed answer for Configuration objects, allowing to return default
     * value for settings when available.
     */
    private static class ConfigAnswer extends ReturnsEmptyValues {
 
        private static final long serialVersionUID = 1L;
 
        /** {@inheritDoc} */
        @Override
        public Object answer(InvocationOnMock invocation) {
            try {
                String definitionClassName =
                    toDefinitionClassName(invocation.getMethod().getDeclaringClass().getName());
                Class<?> definitionClass = Class.forName(definitionClassName);
                ManagedObjectDefinition<?, ?> definition =
                    (ManagedObjectDefinition<?, ?>) definitionClass.getMethod("getInstance").invoke(null);
                String invokedMethodName = invocation.getMethod().getName();
                if (!isGetterMethod(invokedMethodName)) {
                    return answerFromDefaultMockitoBehavior(invocation);
                }
                Method getPropertyDefMethod = getPropertyDefinitionMethod(definitionClass, invokedMethodName);
                Class<?> propertyReturnType = getPropertyReturnType(getPropertyDefMethod);
                Object defaultValue = getDefaultValue(definition, getPropertyDefMethod, propertyReturnType);
                if (defaultValue == null) {
                    return answerFromDefaultMockitoBehavior(invocation);
                }
                return defaultValue;
            } catch (Exception e) {
                return answerFromDefaultMockitoBehavior(invocation);
            }
        }
 
        private Object answerFromDefaultMockitoBehavior(InvocationOnMock invocation) {
            return super.answer(invocation);
        }
 
        private static boolean isGetterMethod(String invokedMethodName) {
            return invokedMethodName.startsWith("get") || invokedMethodName.startsWith("is");
        }
 
        private static Method getPropertyDefinitionMethod(Class<?> definitionClass, String invokedMethodName)
                throws SecurityException, NoSuchMethodException {
            // Methods for boolean starts with "is" in Cfg class but with "get" in CfgDefn class.
            return definitionClass.getMethod(invokedMethodName.replaceAll("^is", "get") + "PropertyDefinition");
        }
 
        /**
         * Returns the type of values returned by the property.
         */
        private static Class<?> getPropertyReturnType(Method getPropertyDefMethod) {
            Class<?> returnClass = getPropertyDefMethod.getReturnType();
            return ((ParameterizedType) returnClass.getGenericSuperclass())
                    .getActualTypeArguments()[0].getClass();
        }
 
        /**
         * Retrieve class name of definition from class name of configuration.
         * <p>
         * Convert class name "[package].server.FooCfg" to "[package].meta.FooCfgDef"
         */
        private static String toDefinitionClassName(String configClassName) {
            int finalDot = configClassName.lastIndexOf('.');
            return configClassName.substring(0, finalDot - 6) + "meta."
                    + configClassName.substring(finalDot + 1) + "Defn";
        }
 
        /**
         * Returns the default value corresponding to the provided property
         * definition getter method from the provided managed object definition.
         *
         * @param <T>
         *            The data type of values provided by the property
         *            definition.
         * @param definition
         *            The definition of the managed object.
         * @param getPropertyDefMethod
         *            The method to retrieve the property definition from the
         *            definition.
         * @param propertyReturnClass
         *            The class of values provided by the property definition.
         * @return the default value of property definition, or
         *         {@code null} if there is no default value.
         * @throws Exception
         *             If an error occurs.
         */
        @SuppressWarnings("unchecked")
        private static <T> Object getDefaultValue(ManagedObjectDefinition<?, ?> definition,
                Method getPropertyDefMethod, Class<T> propertyReturnClass) throws Exception {
            PropertyDefinition<T> propertyDefinition = (PropertyDefinition<T>) getPropertyDefMethod.invoke(definition);
            DefaultBehaviorProvider<T> defaultBehaviorProvider = (DefaultBehaviorProvider<T>) propertyDefinition
                    .getClass().getMethod("getDefaultBehaviorProvider").invoke(propertyDefinition);
            MockProviderVisitor<T> visitor = new MockProviderVisitor<>(propertyDefinition);
            Collection<T> values = defaultBehaviorProvider.accept(visitor, null);
 
            if (values == null) {
                // No default behavior defined
                return null;
            } else if (propertyDefinition.hasOption(PropertyOption.MULTI_VALUED)) {
                return values;
            } else {
                // Single value returned
                return values.iterator().next();
            }
        }
 
    }
 
    /**
     * A stubbed answer for Configuration objects, allowing to return default
     * value for settings when available.
     */
    private static class LegacyConfigAnswer extends ReturnsEmptyValues {
 
        private static final long serialVersionUID = 1L;
 
        /** {@inheritDoc} */
        @Override
        public Object answer(InvocationOnMock invocation) {
            try {
                String definitionClassName =
                    toDefinitionClassName(invocation.getMethod().getDeclaringClass().getName());
                Class<?> definitionClass = Class.forName(definitionClassName);
                org.opends.server.admin.ManagedObjectDefinition<?, ?> definition =
                    (org.opends.server.admin.ManagedObjectDefinition<?, ?>) definitionClass.getMethod("getInstance").invoke(null);
                String invokedMethodName = invocation.getMethod().getName();
                if (!isGetterMethod(invokedMethodName)) {
                    return answerFromDefaultMockitoBehavior(invocation);
                }
                Method getPropertyDefMethod = getPropertyDefinitionMethod(definitionClass, invokedMethodName);
                Class<?> propertyReturnType = getPropertyReturnType(getPropertyDefMethod);
                Object defaultValue = getDefaultValue(definition, getPropertyDefMethod, propertyReturnType);
                if (defaultValue == null) {
                    return answerFromDefaultMockitoBehavior(invocation);
                }
                return defaultValue;
            } catch (Exception e) {
                return answerFromDefaultMockitoBehavior(invocation);
            }
        }
 
        private Object answerFromDefaultMockitoBehavior(InvocationOnMock invocation) {
            return super.answer(invocation);
        }
 
        private static boolean isGetterMethod(String invokedMethodName) {
            return invokedMethodName.startsWith("get") || invokedMethodName.startsWith("is");
        }
 
        private static Method getPropertyDefinitionMethod(Class<?> definitionClass, String invokedMethodName)
                throws SecurityException, NoSuchMethodException {
            // Methods for boolean starts with "is" in Cfg class but with "get" in CfgDefn class.
            return definitionClass.getMethod(invokedMethodName.replaceAll("^is", "get") + "PropertyDefinition");
        }
 
        /**
         * Returns the type of values returned by the property.
         */
        private static Class<?> getPropertyReturnType(Method getPropertyDefMethod) {
            Class<?> returnClass = getPropertyDefMethod.getReturnType();
            return ((ParameterizedType) returnClass.getGenericSuperclass()).getActualTypeArguments()[0].getClass();
        }
 
        /**
         * Retrieve class name of definition from class name of configuration.
         * <p>
         * Convert class name "[package].server.FooCfg" to "[package].meta.FooCfgDef"
         */
        private static String toDefinitionClassName(String configClassName) {
            int finalDot = configClassName.lastIndexOf('.');
            return configClassName.substring(0, finalDot - 6) + "meta." + configClassName.substring(finalDot + 1)
                    + "Defn";
        }
 
        /**
         * Returns the default value corresponding to the provided property
         * definition getter method from the provided managed object definition.
         *
         * @param <T>
         *            The data type of values provided by the property
         *            definition.
         * @param definition
         *            The definition of the managed object.
         * @param getPropertyDefMethod
         *            The method to retrieve the property definition from the
         *            definition.
         * @param propertyReturnClass
         *            The class of values provided by the property definition.
         * @return the default value of property definition, or
         *         {@code null} if there is no default value.
         * @throws Exception
         *             If an error occurs.
         */
        @SuppressWarnings("unchecked")
        private static <T> Object getDefaultValue(org.opends.server.admin.ManagedObjectDefinition<?, ?> definition,
                Method getPropertyDefMethod, Class<T> propertyReturnClass) throws Exception {
            org.opends.server.admin.PropertyDefinition<T> propertyDefinition = (org.opends.server.admin.PropertyDefinition<T>) getPropertyDefMethod.invoke(definition);
            org.opends.server.admin.DefaultBehaviorProvider<T> defaultBehaviorProvider = (org.opends.server.admin.DefaultBehaviorProvider<T>) propertyDefinition
                    .getClass().getMethod("getDefaultBehaviorProvider").invoke(propertyDefinition);
            LegacyMockProviderVisitor<T> visitor = new LegacyMockProviderVisitor<>(propertyDefinition);
            Collection<T> values = defaultBehaviorProvider.accept(visitor, null);
 
            if (values == null) {
                // No default behavior defined
                return null;
            } else if (propertyDefinition.hasOption(org.opends.server.admin.PropertyOption.MULTI_VALUED)) {
                return values;
            } else {
                // Single value returned
                return values.iterator().next();
            }
        }
 
    }
 
    /** Visitor used to retrieve the default value. */
    private static class MockProviderVisitor<T> implements DefaultBehaviorProviderVisitor<T, Collection<T>, Void> {
 
        /** The property definition used to decode the values. */
        private PropertyDefinition<T> propertyDef;
 
        MockProviderVisitor(PropertyDefinition<T> propertyDef) {
            this.propertyDef = propertyDef;
        }
 
        /** {@inheritDoc} */
        @Override
        public Collection<T> visitAbsoluteInherited(AbsoluteInheritedDefaultBehaviorProvider<T> provider, Void p) {
            // not handled
            return null;
        }
 
        /** {@inheritDoc} */
        @Override
        public Collection<T> visitAlias(AliasDefaultBehaviorProvider<T> provider, Void p) {
            // not handled
            return null;
        }
 
        /**
         * Returns the default value for the property as a collection.
         */
        @Override
        public Collection<T> visitDefined(DefinedDefaultBehaviorProvider<T> provider, Void p) {
            SortedSet<T> values = new TreeSet<>();
            for (String stringValue : provider.getDefaultValues()) {
                values.add(propertyDef.decodeValue(stringValue));
            }
            return values;
        }
 
        /** {@inheritDoc} */
        @Override
        public Collection<T> visitRelativeInherited(RelativeInheritedDefaultBehaviorProvider<T> d, Void p) {
            // not handled
            return null;
        }
 
        /** {@inheritDoc} */
        @Override
        public Collection<T> visitUndefined(UndefinedDefaultBehaviorProvider<T> d, Void p) {
            // not handled
            return null;
        }
    }
 
    /** Visitor used to retrieve the default value. */
    private static class LegacyMockProviderVisitor<T> implements org.opends.server.admin.DefaultBehaviorProviderVisitor<T, Collection<T>, Void> {
 
        /** The property definition used to decode the values. */
        private org.opends.server.admin.PropertyDefinition<T> propertyDef;
 
        LegacyMockProviderVisitor(org.opends.server.admin.PropertyDefinition<T> propertyDef) {
            this.propertyDef = propertyDef;
        }
 
        /** {@inheritDoc} */
        @Override
        public Collection<T> visitAbsoluteInherited(org.opends.server.admin.AbsoluteInheritedDefaultBehaviorProvider<T> provider, Void p) {
            // not handled
            return null;
        }
 
        /** {@inheritDoc} */
        @Override
        public Collection<T> visitAlias(org.opends.server.admin.AliasDefaultBehaviorProvider<T> provider, Void p) {
            // not handled
            return null;
        }
 
        /**
         * Returns the default value for the property as a collection.
         */
        @Override
        public Collection<T> visitDefined(org.opends.server.admin.DefinedDefaultBehaviorProvider<T> provider, Void p) {
            SortedSet<T> values = new TreeSet<>();
            for (String stringValue : provider.getDefaultValues()) {
                values.add(propertyDef.decodeValue(stringValue));
            }
            return values;
        }
 
        /** {@inheritDoc} */
        @Override
        public Collection<T> visitRelativeInherited(org.opends.server.admin.RelativeInheritedDefaultBehaviorProvider<T> d, Void p) {
            // not handled
            return null;
        }
 
        /** {@inheritDoc} */
        @Override
        public Collection<T> visitUndefined(org.opends.server.admin.UndefinedDefaultBehaviorProvider<T> d, Void p) {
            // not handled
            return null;
        }
    }
}