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

Matthew Swift
29.40.2016 95d5c1406fb12c27d1c906063c9daccde36329ca
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
/*
 * 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 2016 ForgeRock AS.
 *
 */
package org.forgerock.opendj.rest2ldap;
 
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static org.forgerock.http.routing.RouteMatchers.newResourceApiVersionBehaviourManager;
import static org.forgerock.http.routing.RoutingMode.STARTS_WITH;
import static org.forgerock.http.routing.Version.version;
import static org.forgerock.http.util.Json.readJsonLenient;
import static org.forgerock.json.JsonValueFunctions.enumConstant;
import static org.forgerock.json.JsonValueFunctions.pointer;
import static org.forgerock.json.JsonValueFunctions.setOf;
import static org.forgerock.json.resource.RouteMatchers.requestUriMatcher;
import static org.forgerock.json.resource.RouteMatchers.resourceApiVersionContextFilter;
import static org.forgerock.opendj.ldap.Connections.LOAD_BALANCER_MONITORING_INTERVAL;
import static org.forgerock.opendj.ldap.Connections.newCachedConnectionPool;
import static org.forgerock.opendj.ldap.Connections.newFailoverLoadBalancer;
import static org.forgerock.opendj.ldap.Connections.newRoundRobinLoadBalancer;
import static org.forgerock.opendj.ldap.KeyManagers.useJvmDefaultKeyStore;
import static org.forgerock.opendj.ldap.KeyManagers.useKeyStoreFile;
import static org.forgerock.opendj.ldap.KeyManagers.usePKCS11Token;
import static org.forgerock.opendj.ldap.KeyManagers.useSingleCertificate;
import static org.forgerock.opendj.ldap.LDAPConnectionFactory.*;
import static org.forgerock.opendj.ldap.TrustManagers.checkUsingTrustStore;
import static org.forgerock.opendj.ldap.TrustManagers.trustAll;
import static org.forgerock.opendj.rest2ldap.ReadOnUpdatePolicy.CONTROLS;
import static org.forgerock.opendj.rest2ldap.Rest2Ldap.*;
import static org.forgerock.opendj.rest2ldap.Rest2ldapMessages.*;
import static org.forgerock.opendj.rest2ldap.Utils.newJsonValueException;
import static org.forgerock.util.Utils.joinAsString;
import static org.forgerock.util.time.Duration.duration;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
 
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509KeyManager;
 
import org.forgerock.http.routing.ResourceApiVersionBehaviourManager;
import org.forgerock.i18n.LocalizedIllegalArgumentException;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.forgerock.json.JsonValue;
import org.forgerock.json.resource.BadRequestException;
import org.forgerock.json.resource.FilterChain;
import org.forgerock.json.resource.Request;
import org.forgerock.json.resource.RequestHandler;
import org.forgerock.json.resource.ResourceException;
import org.forgerock.json.resource.Router;
import org.forgerock.opendj.ldap.ConnectionFactory;
import org.forgerock.opendj.ldap.LDAPConnectionFactory;
import org.forgerock.opendj.ldap.SSLContextBuilder;
import org.forgerock.opendj.ldap.requests.BindRequest;
import org.forgerock.opendj.ldap.requests.Requests;
import org.forgerock.services.context.Context;
import org.forgerock.util.Options;
import org.forgerock.util.promise.Promise;
import org.forgerock.util.time.Duration;
 
/** Provides core factory methods and builders for constructing Rest2Ldap endpoints from JSON configuration. */
public final class Rest2LdapJsonConfigurator {
    private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
    /**
     * Parses Rest2Ldap configuration options. The JSON configuration must have the following format:
     * <p>
     * <pre>
     * {
     *      "readOnUpdatePolicy": "controls",
     *      "useSubtreeDelete": true,
     *      "usePermissiveModify": true,
     *      "useMvcc": true
     *      "mvccAttribute": "etag"
     * }
     * </pre>
     * <p>
     * See the sample configuration file for a detailed description of its content.
     *
     * @param config
     *         The JSON configuration.
     * @return The parsed Rest2Ldap configuration options.
     * @throws IllegalArgumentException
     *         If the configuration is invalid.
     */
    public static Options configureOptions(final JsonValue config) {
        final Options options = Options.defaultOptions();
 
        options.set(READ_ON_UPDATE_POLICY,
                    config.get("readOnUpdatePolicy").defaultTo(CONTROLS).as(enumConstant(ReadOnUpdatePolicy.class)));
 
        // Default to false, even though it is supported by OpenDJ, because it requires additional permissions.
        options.set(USE_SUBTREE_DELETE, config.get("useSubtreeDelete").defaultTo(false).asBoolean());
 
        // Default to true because it is supported by OpenDJ and does not require additional permissions.
        options.set(USE_PERMISSIVE_MODIFY, config.get("usePermissiveModify").defaultTo(false).asBoolean());
 
        options.set(USE_MVCC, config.get("useMvcc").defaultTo(true).asBoolean());
        options.set(MVCC_ATTRIBUTE, config.get("mvccAttribute").defaultTo("etag").asString());
 
        return options;
    }
 
    /**
     * Parses a list of Rest2Ldap resource definitions. The JSON configuration must have the following format:
     * <p>
     * <pre>
     * "top": {
     *     "isAbstract": true,
     *     "properties": {
     *         "_rev": {
     *             "type": "simple"
     *             "ldapAttribute": "etag",
     *             "writability": "readOnly"
     *         },
     *         ...
     *     },
     *     ...
     * },
     * ...
     * </pre>
     * <p>
     * See the sample configuration file for a detailed description of its content.
     *
     * @param config
     *         The JSON configuration.
     * @return The parsed list of Rest2Ldap resource definitions.
     * @throws IllegalArgumentException
     *         If the configuration is invalid.
     */
    public static List<Resource> configureResources(final JsonValue config) {
        final JsonValue resourcesConfig = config.required().expect(Map.class);
        final List<Resource> resources = new LinkedList<>();
        for (final String resourceId : resourcesConfig.keys()) {
            resources.add(configureResource(resourceId, resourcesConfig.get(resourceId)));
        }
        return resources;
    }
 
    /**
     * Creates a new CREST {@link Router} using the provided endpoints configuration directory and Rest2Ldap options.
     * The Rest2Ldap configuration typically has the following structure on disk:
     * <ul>
     * <li> config.json - contains the configuration for the LDAP connection factories and authorization
     * <li> rest2ldap/rest2ldap.json - defines Rest2Ldap configuration options
     * <li> rest2ldap/endpoints/{api} - a directory containing the endpoint's resource definitions for endpoint {api}
     * <li> rest2ldap/endpoints/{api}/{resource-id}.json - the resource definitions for a specific version of API {api}.
     * The name of the file, {resource-id}, determines which resource type definition in the mapping file will be
     * used as the root resource.
     * </ul>
     *
     * @param endpointsDirectory The directory representing the Rest2Ldap "endpoints" directory.
     * @param options The Rest2Ldap configuration options.
     * @return A new CREST {@link Router} configured using the provided options and endpoints.
     * @throws IOException If the endpoints configuration cannot be read.
     * @throws IllegalArgumentException
     *         If the configuration is invalid.
     */
    public static Router configureEndpoints(final File endpointsDirectory, final Options options) throws IOException {
        final Router pathRouter = new Router();
 
        final File[] endpoints = endpointsDirectory.listFiles(new FileFilter() {
            @Override
            public boolean accept(final File pathname) {
                return pathname.isDirectory() && pathname.canRead();
            }
        });
 
        if (endpoints == null) {
            throw new LocalizedIllegalArgumentException(ERR_INVALID_ENDPOINTS_DIRECTORY.get(endpointsDirectory));
        }
 
        for (final File endpoint : endpoints) {
            final RequestHandler endpointHandler = configureEndpoint(endpoint, options);
            pathRouter.addRoute(requestUriMatcher(STARTS_WITH, endpoint.getName()), endpointHandler);
        }
        return pathRouter;
    }
 
    /**
     * Creates a new CREST {@link RequestHandler} representing a single endpoint whose configuration is defined in the
     * provided {@code endpointDirectory} parameter. The directory should contain a separate file for each supported
     * version of the REST endpoint. The name of the file, excluding the suffix, identifies the resource definition
     * which acts as the entry point into the endpoint.
     *
     * @param endpointDirectory The directory containing the endpoint's resource definitions, e.g.
     *                          rest2ldap/routes/api would contain definitions for the "api" endpoint.
     * @param options The Rest2Ldap configuration options.
     * @return A new CREST {@link RequestHandler} configured using the provided options and endpoint mappings.
     * @throws IOException If the endpoint configuration cannot be read.
     * @throws IllegalArgumentException If the configuration is invalid.
     */
    public static RequestHandler configureEndpoint(File endpointDirectory, Options options) throws IOException {
        final Router versionRouter = new Router();
        final File[] endpointVersions = endpointDirectory.listFiles(new FileFilter() {
            @Override
            public boolean accept(final File pathname) {
                return pathname.isFile() && pathname.canRead() && pathname.getName().endsWith(".json");
            }
        });
 
        if (endpointVersions == null) {
            throw new LocalizedIllegalArgumentException(ERR_INVALID_ENDPOINT_DIRECTORY.get(endpointDirectory));
        }
 
        final List<String> supportedVersions = new ArrayList<>();
        boolean hasWildCardVersion = false;
        for (final File endpointVersion : endpointVersions) {
            final JsonValue mappingConfig = readJson(endpointVersion);
            final String version = mappingConfig.get("version").defaultTo("*").asString();
            final List<Resource> resourceTypes = configureResources(mappingConfig.get("resourceTypes"));
            final Rest2Ldap rest2Ldap = rest2Ldap(options, resourceTypes);
 
            final String endpointVersionFileName = endpointVersion.getName();
            final int endIndex = endpointVersionFileName.lastIndexOf('.');
            final String rootResourceType = endpointVersionFileName.substring(0, endIndex);
            final RequestHandler handler = rest2Ldap.newRequestHandlerFor(rootResourceType);
 
            if (version.equals("*")) {
                versionRouter.setDefaultRoute(handler);
                hasWildCardVersion = true;
            } else {
                versionRouter.addRoute(version(version), handler);
                supportedVersions.add(version);
            }
            logger.debug(INFO_REST2LDAP_CREATING_ENDPOINT.get(endpointDirectory.getName(), version));
        }
        if (!hasWildCardVersion) {
            versionRouter.setDefaultRoute(new AbstractRequestHandler() {
                @Override
                protected <V> Promise<V, ResourceException> handleRequest(Context context, Request request) {
                    final String message = ERR_BAD_API_RESOURCE_VERSION.get(request.getResourceVersion(),
                                                                            joinAsString(", ", supportedVersions))
                                                                       .toString();
                    return new BadRequestException(message).asPromise();
                }
            });
        }
 
        // FIXME: Disable the warning header for now due to CREST-389 / CREST-390.
        final ResourceApiVersionBehaviourManager behaviourManager = newResourceApiVersionBehaviourManager();
        behaviourManager.setWarningEnabled(false);
        return new FilterChain(versionRouter, resourceApiVersionContextFilter(behaviourManager));
    }
 
    static JsonValue readJson(final File resource) throws IOException {
        try (InputStream in = new FileInputStream(resource)) {
            return new JsonValue(readJsonLenient(in));
        }
    }
 
    private static Resource configureResource(final String resourceId, final JsonValue config) {
        final Resource resource = resource(resourceId)
                .isAbstract(config.get("isAbstract").defaultTo(false).asBoolean())
                .superType(config.get("superType").asString())
                .objectClasses(config.get("objectClasses")
                                     .defaultTo(emptyList()).asList(String.class).toArray(new String[0]))
                .supportedActions(config.get("supportedActions")
                                        .defaultTo(emptyList())
                                        .as(setOf(enumConstant(Action.class))).toArray(new Action[0]))
                .resourceTypeProperty(config.get("resourceTypeProperty").as(pointer()))
                .includeAllUserAttributesByDefault(config.get("includeAllUserAttributesByDefault")
                                                         .defaultTo(false).asBoolean())
                .excludedDefaultUserAttributes(config.get("excludedDefaultUserAttributes")
                                                     .defaultTo(Collections.emptyList()).asList(String.class));
 
        final JsonValue properties = config.get("properties").expect(Map.class);
        for (final String property : properties.keys()) {
            resource.property(property, configurePropertyMapper(properties.get(property), property));
        }
 
        final JsonValue subResources = config.get("subResources").expect(Map.class);
        for (final String urlTemplate : subResources.keys()) {
            resource.subResource(configureSubResource(urlTemplate, subResources.get(urlTemplate)));
        }
 
        return resource;
    }
 
    private enum NamingStrategyType { CLIENTDNNAMING, CLIENTNAMING, SERVERNAMING }
    private enum SubResourceType { COLLECTION, SINGLETON }
 
    private static SubResource configureSubResource(final String urlTemplate, final JsonValue config) {
        final String dnTemplate = config.get("dnTemplate").defaultTo("").asString();
        final Boolean isReadOnly = config.get("isReadOnly").defaultTo(false).asBoolean();
        final String resourceId = config.get("resource").required().asString();
 
        if (config.get("type").required().as(enumConstant(SubResourceType.class)) == SubResourceType.COLLECTION) {
            final String[] glueObjectClasses = config.get("glueObjectClasses")
                                                     .defaultTo(emptyList())
                                                     .asList(String.class)
                                                     .toArray(new String[0]);
 
            final SubResourceCollection collection = collectionOf(resourceId).urlTemplate(urlTemplate)
                                                                             .dnTemplate(dnTemplate)
                                                                             .isReadOnly(isReadOnly)
                                                                             .glueObjectClasses(glueObjectClasses);
 
            final JsonValue namingStrategy = config.get("namingStrategy").required();
            switch (namingStrategy.get("type").required().as(enumConstant(NamingStrategyType.class))) {
            case CLIENTDNNAMING:
                collection.useClientDnNaming(namingStrategy.get("dnAttribute").required().asString());
                break;
            case CLIENTNAMING:
                collection.useClientNaming(namingStrategy.get("dnAttribute").required().asString(),
                                           namingStrategy.get("idAttribute").required().asString());
                break;
            case SERVERNAMING:
                collection.useServerNaming(namingStrategy.get("dnAttribute").required().asString(),
                                           namingStrategy.get("idAttribute").required().asString());
                break;
            }
 
            return collection;
        } else {
            return singletonOf(resourceId).urlTemplate(urlTemplate).dnTemplate(dnTemplate).isReadOnly(isReadOnly);
        }
    }
 
    private static PropertyMapper configurePropertyMapper(final JsonValue mapper, final String defaultLdapAttribute) {
        switch (mapper.get("type").required().asString()) {
        case "resourceType":
            return resourceType();
        case "constant":
            return constant(mapper.get("value").getObject());
        case "simple":
            return simple(mapper.get("ldapAttribute").defaultTo(defaultLdapAttribute).required().asString())
                    .defaultJsonValue(mapper.get("defaultJsonValue").getObject())
                    .isBinary(mapper.get("isBinary").defaultTo(false).asBoolean())
                    .isRequired(mapper.get("isRequired").defaultTo(false).asBoolean())
                    .isMultiValued(mapper.get("isMultiValued").defaultTo(false).asBoolean())
                    .writability(parseWritability(mapper));
        case "reference":
            final String ldapAttribute = mapper.get("ldapAttribute")
                                               .defaultTo(defaultLdapAttribute).required().asString();
            final String baseDN = mapper.get("baseDn").required().asString();
            final String primaryKey = mapper.get("primaryKey").required().asString();
            final PropertyMapper m = configurePropertyMapper(mapper.get("mapper").required(), primaryKey);
            return reference(ldapAttribute, baseDN, primaryKey, m)
                    .isRequired(mapper.get("isRequired").defaultTo(false).asBoolean())
                    .isMultiValued(mapper.get("isMultiValued").defaultTo(false).asBoolean())
                    .searchFilter(mapper.get("searchFilter").defaultTo("(objectClass=*)").asString())
                    .writability(parseWritability(mapper));
        case "object":
            final JsonValue properties = mapper.get("properties");
            final ObjectPropertyMapper object = object();
            for (final String attribute : properties.keys()) {
                object.property(attribute, configurePropertyMapper(properties.get(attribute), attribute));
            }
            return object;
        default:
            throw newJsonValueException(mapper, ERR_CONFIG_NO_MAPPING_IN_CONFIGURATION.get(
                    "constant, simple, reference, object"));
        }
    }
 
    private static WritabilityPolicy parseWritability(final JsonValue mapper) {
        return mapper.get("writability").defaultTo("readWrite").as(enumConstant(WritabilityPolicy.class));
    }
 
    /** Indicates whether LDAP client connections should use SSL or StartTLS. */
    private enum ConnectionSecurity { NONE, SSL, STARTTLS }
 
    /** Specifies the mechanism which will be used for trusting certificates presented by the LDAP server. */
    private enum TrustManagerType { TRUSTALL, JVM, FILE }
 
    /** Specifies the type of key-store to use when performing SSL client authentication. */
    private enum KeyManagerType { JVM, FILE, PKCS11 }
 
    /**
     * Configures a {@link X509KeyManager} using the provided JSON configuration.
     *
     * @param configuration
     *         The JSON object containing the key manager configuration.
     * @return The configured key manager.
     */
    public static X509KeyManager configureKeyManager(final JsonValue configuration) {
        try {
            return configureKeyManager(configuration, KeyManagerType.JVM);
        } catch (GeneralSecurityException | IOException e) {
            throw new IllegalArgumentException(ERR_CONFIG_INVALID_KEY_MANAGER.get(
                    configuration.getPointer(), e.getLocalizedMessage()).toString(), e);
        }
    }
 
    private static X509KeyManager configureKeyManager(JsonValue config, KeyManagerType defaultIfMissing)
            throws GeneralSecurityException, IOException {
        final KeyManagerType keyManagerType = config.get("keyManager")
                                                    .defaultTo(defaultIfMissing)
                                                    .as(enumConstant(KeyManagerType.class));
        switch (keyManagerType) {
        case JVM:
            return useJvmDefaultKeyStore();
        case FILE:
            final String fileName = config.get("fileBasedKeyManagerFile").required().asString();
            final String passwordFile = config.get("fileBasedKeyManagerPasswordFile").asString();
            final String password = passwordFile != null
                    ? readPasswordFromFile(passwordFile) : config.get("fileBasedKeyManagerPassword").asString();
            final String type = config.get("fileBasedKeyManagerType").asString();
            final String provider = config.get("fileBasedKeyManagerProvider").asString();
            return useKeyStoreFile(fileName, password != null ? password.toCharArray() : null, type, provider);
        case PKCS11:
            final String pkcs11PasswordFile = config.get("pkcs11KeyManagerPasswordFile").asString();
            return usePKCS11Token(pkcs11PasswordFile != null
                                          ? readPasswordFromFile(pkcs11PasswordFile).toCharArray() : null);
        default:
            throw new IllegalArgumentException("Unsupported key-manager type: " + keyManagerType);
        }
    }
 
    private static String readPasswordFromFile(String fileName) throws IOException {
        try (final BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)))) {
            return reader.readLine();
        }
    }
 
    /**
     * Configures a {@link TrustManager} using the provided JSON configuration.
     *
     * @param configuration
     *         The JSON object containing the trust manager configuration.
     * @return The configured trust manager.
     */
    public static TrustManager configureTrustManager(final JsonValue configuration) {
        try {
            return configureTrustManager(configuration, TrustManagerType.JVM);
        } catch (GeneralSecurityException | IOException e) {
            throw new IllegalArgumentException(ERR_CONFIG_INVALID_TRUST_MANAGER.get(
                    configuration.getPointer(), e.getLocalizedMessage()).toString(), e);
        }
    }
 
    private static TrustManager configureTrustManager(JsonValue config, TrustManagerType defaultIfMissing)
            throws GeneralSecurityException, IOException {
        final TrustManagerType trustManagerType = config.get("trustManager")
                                                        .defaultTo(defaultIfMissing)
                                                        .as(enumConstant(TrustManagerType.class));
        switch (trustManagerType) {
        case TRUSTALL:
            return trustAll();
        case JVM:
            return null;
        case FILE:
            final String fileName = config.get("fileBasedTrustManagerFile").required().asString();
            final String passwordFile = config.get("fileBasedTrustManagerPasswordFile").asString();
            final String password = passwordFile != null
                    ? readPasswordFromFile(passwordFile) : config.get("fileBasedTrustManagerPassword").asString();
            final String type = config.get("fileBasedTrustManagerType").asString();
            return checkUsingTrustStore(fileName, password != null ? password.toCharArray() : null, type);
        default:
            throw new IllegalArgumentException("Unsupported trust-manager type: " + trustManagerType);
        }
    }
 
    /**
     * Creates a new connection factory using the named configuration in the provided JSON list of factory
     * configurations. See the sample configuration file for a detailed description of its content.
     *
     * @param configuration
     *         The JSON configuration.
     * @param name
     *         The name of the connection factory configuration to be parsed.
     * @param trustManager
     *            The trust manager to use for secure connection. Can be {@code null}
     *            to use the default JVM trust manager.
     * @param keyManager
     *            The key manager to use for secure connection. Can be {@code null}
     *            to use the default JVM key manager.
     * @param providerClassLoader
     *         The {@link ClassLoader} used to fetch the {@link org.forgerock.opendj.ldap.spi.TransportProvider}. This
     *         can be useful in OSGI environments.
     * @return A new connection factory using the provided JSON configuration.
     * @throws IllegalArgumentException
     *         If the configuration is invalid.
     */
    public static ConnectionFactory configureConnectionFactory(final JsonValue configuration,
                                                               final String name,
                                                               final TrustManager trustManager,
                                                               final X509KeyManager keyManager,
                                                               final ClassLoader providerClassLoader) {
        final JsonValue normalizedConfiguration = normalizeConnectionFactory(configuration, name, 0);
        return configureConnectionFactory(normalizedConfiguration, trustManager, keyManager, providerClassLoader);
    }
 
    /**
     * Creates a new connection factory using the named configuration in the provided JSON list of factory
     * configurations. See the sample configuration file for a detailed description of its content.
     *
     * @param configuration
     *         The JSON configuration.
     * @param name
     *         The name of the connection factory configuration to be parsed.
     * @param trustManager
     *            The trust manager to use for secure connection. Can be {@code null}
     *            to use the default JVM trust manager.
     * @param keyManager
     *            The key manager to use for secure connection. Can be {@code null}
     *            to use the default JVM key manager.
     * @return A new connection factory using the provided JSON configuration.
     * @throws IllegalArgumentException
     *         If the configuration is invalid.
     */
    public static ConnectionFactory configureConnectionFactory(final JsonValue configuration,
                                                               final String name,
                                                               final TrustManager trustManager,
                                                               final X509KeyManager keyManager) {
        return configureConnectionFactory(configuration, name, trustManager, keyManager, null);
    }
 
    private static ConnectionFactory configureConnectionFactory(final JsonValue configuration,
                                                                final TrustManager trustManager,
                                                                final X509KeyManager keyManager,
                                                                final ClassLoader providerClassLoader) {
        final long heartBeatIntervalSeconds = configuration.get("heartBeatIntervalSeconds").defaultTo(30L).asLong();
        final Duration heartBeatInterval = duration(Math.max(heartBeatIntervalSeconds, 1L), TimeUnit.SECONDS);
 
        final long heartBeatTimeoutMillis = configuration.get("heartBeatTimeoutMilliSeconds").defaultTo(500L).asLong();
        final Duration heartBeatTimeout = duration(Math.max(heartBeatTimeoutMillis, 100L), TimeUnit.MILLISECONDS);
 
        final Options options = Options.defaultOptions()
                                       .set(TRANSPORT_PROVIDER_CLASS_LOADER, providerClassLoader)
                                       .set(HEARTBEAT_ENABLED, true)
                                       .set(HEARTBEAT_INTERVAL, heartBeatInterval)
                                       .set(HEARTBEAT_TIMEOUT, heartBeatTimeout)
                                       .set(LOAD_BALANCER_MONITORING_INTERVAL, heartBeatInterval);
 
        // Parse pool parameters,
        final int connectionPoolSize =
                Math.max(configuration.get("connectionPoolSize").defaultTo(10).asInteger(), 1);
 
        // Parse authentication parameters.
        if (configuration.isDefined("authentication")) {
            final JsonValue authn = configuration.get("authentication");
            if (authn.isDefined("simple")) {
                final JsonValue simple = authn.get("simple");
                final BindRequest bindRequest =
                        Requests.newSimpleBindRequest(simple.get("bindDn").required().asString(),
                                                      simple.get("bindPassword").required().asString().toCharArray());
                options.set(AUTHN_BIND_REQUEST, bindRequest);
            } else {
                throw new LocalizedIllegalArgumentException(ERR_CONFIG_INVALID_AUTHENTICATION.get());
            }
        }
 
        // Parse SSL/StartTLS parameters.
        final ConnectionSecurity connectionSecurity = configuration.get("connectionSecurity")
                                                                   .defaultTo(ConnectionSecurity.NONE)
                                                                   .as(enumConstant(ConnectionSecurity.class));
        if (connectionSecurity != ConnectionSecurity.NONE) {
            try {
                // Configure SSL.
                final SSLContextBuilder builder = new SSLContextBuilder();
                builder.setTrustManager(trustManager);
                final String sslCertAlias = configuration.get("sslCertAlias").asString();
                builder.setKeyManager(sslCertAlias != null
                                              ? useSingleCertificate(sslCertAlias, keyManager)
                                              : keyManager);
                options.set(SSL_CONTEXT, builder.getSSLContext());
                options.set(SSL_USE_STARTTLS, connectionSecurity == ConnectionSecurity.STARTTLS);
            } catch (GeneralSecurityException e) {
                // Rethrow as unchecked exception.
                throw new IllegalArgumentException(e);
            }
        }
 
        // Parse primary data center.
        final JsonValue primaryLdapServers = configuration.get("primaryLdapServers");
        if (!primaryLdapServers.isList() || primaryLdapServers.size() == 0) {
            throw new IllegalArgumentException("No primaryLdapServers");
        }
        final ConnectionFactory primary = parseLdapServers(primaryLdapServers, connectionPoolSize, options);
 
        // Parse secondary data center(s).
        final JsonValue secondaryLdapServers = configuration.get("secondaryLdapServers");
        ConnectionFactory secondary = null;
        if (secondaryLdapServers.isList()) {
            if (secondaryLdapServers.size() > 0) {
                secondary = parseLdapServers(secondaryLdapServers, connectionPoolSize, options);
            }
        } else if (!secondaryLdapServers.isNull()) {
            throw new LocalizedIllegalArgumentException(ERR_CONFIG_INVALID_SECONDARY_LDAP_SERVER.get());
        }
 
        // Create fail-over.
        if (secondary != null) {
            return newFailoverLoadBalancer(asList(primary, secondary), options);
        } else {
            return primary;
        }
    }
 
    private static JsonValue normalizeConnectionFactory(final JsonValue configuration,
                                                        final String name, final int depth) {
        // Protect against infinite recursion in the configuration.
        if (depth > 100) {
            throw new LocalizedIllegalArgumentException(ERR_CONFIG_SERVER_CIRCULAR_DEPENDENCIES.get(name));
        }
 
        final JsonValue current = configuration.get(name).required();
        if (current.isDefined("inheritFrom")) {
            // Inherit missing fields from inherited configuration.
            final JsonValue parent =
                    normalizeConnectionFactory(configuration,
                                               current.get("inheritFrom").asString(), depth + 1);
            final Map<String, Object> normalized = new LinkedHashMap<>(parent.asMap());
            normalized.putAll(current.asMap());
            normalized.remove("inheritFrom");
            return new JsonValue(normalized);
        } else {
            // No normalization required.
            return current;
        }
    }
 
    private static ConnectionFactory parseLdapServers(JsonValue config, int poolSize, Options options) {
        final List<ConnectionFactory> servers = new ArrayList<>(config.size());
        for (final JsonValue server : config) {
            final String host = server.get("hostname").required().asString();
            final int port = server.get("port").required().asInteger();
            final ConnectionFactory factory = new LDAPConnectionFactory(host, port, options);
            if (poolSize > 1) {
                servers.add(newCachedConnectionPool(factory, 0, poolSize, 60L, TimeUnit.SECONDS));
            } else {
                servers.add(factory);
            }
        }
        if (servers.size() > 1) {
            return newRoundRobinLoadBalancer(servers, options);
        } else {
            return servers.get(0);
        }
    }
 
    private Rest2LdapJsonConfigurator() {
        // Prevent instantiation.
    }
}