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

Matthew Swift
26.41.2013 f537744cea5b0e4dcdf1786437346b5131272829
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
/*
 * 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 ForgeRock AS.
 */
 
package org.forgerock.opendj.rest2ldap;
 
import static org.forgerock.opendj.ldap.requests.Requests.newSearchRequest;
import static org.forgerock.opendj.ldap.schema.CoreSchema.getEntryUUIDAttributeType;
import static org.forgerock.opendj.rest2ldap.ReadOnUpdatePolicy.CONTROLS;
import static org.forgerock.opendj.rest2ldap.Utils.ensureNotNull;
 
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
 
import org.forgerock.json.fluent.JsonValue;
import org.forgerock.json.fluent.JsonValueException;
import org.forgerock.json.resource.BadRequestException;
import org.forgerock.json.resource.CollectionResourceProvider;
import org.forgerock.json.resource.ResourceException;
import org.forgerock.opendj.ldap.AssertionFailureException;
import org.forgerock.opendj.ldap.Attribute;
import org.forgerock.opendj.ldap.AttributeDescription;
import org.forgerock.opendj.ldap.AuthenticationException;
import org.forgerock.opendj.ldap.AuthorizationException;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ConnectionException;
import org.forgerock.opendj.ldap.ConnectionFactory;
import org.forgerock.opendj.ldap.Connections;
import org.forgerock.opendj.ldap.ConstraintViolationException;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.Entry;
import org.forgerock.opendj.ldap.EntryNotFoundException;
import org.forgerock.opendj.ldap.ErrorResultException;
import org.forgerock.opendj.ldap.FailoverLoadBalancingAlgorithm;
import org.forgerock.opendj.ldap.Filter;
import org.forgerock.opendj.ldap.LDAPConnectionFactory;
import org.forgerock.opendj.ldap.LDAPOptions;
import org.forgerock.opendj.ldap.LinkedAttribute;
import org.forgerock.opendj.ldap.MultipleEntriesFoundException;
import org.forgerock.opendj.ldap.RDN;
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.RoundRobinLoadBalancingAlgorithm;
import org.forgerock.opendj.ldap.SSLContextBuilder;
import org.forgerock.opendj.ldap.SearchScope;
import org.forgerock.opendj.ldap.TimeoutResultException;
import org.forgerock.opendj.ldap.TrustManagers;
import org.forgerock.opendj.ldap.requests.BindRequest;
import org.forgerock.opendj.ldap.requests.Requests;
import org.forgerock.opendj.ldap.requests.SearchRequest;
import org.forgerock.opendj.ldap.schema.AttributeType;
import org.forgerock.opendj.ldap.schema.Schema;
 
/**
 * Provides core factory methods and builders for constructing LDAP resource
 * collections.
 */
public final class Rest2LDAP {
 
    /**
     * Indicates whether or not LDAP client connections should use SSL or
     * StartTLS.
     */
    private enum ConnectionSecurity {
        NONE, SSL, STARTTLS
    }
 
    /**
     * Specifies the mechanism which should be used for trusting certificates
     * presented by the LDAP server.
     */
    private enum TrustManagerType {
        TRUSTALL, JVM, FILE
    }
 
    /**
     * A builder for incrementally constructing LDAP resource collections.
     */
    public static final class Builder {
        private final List<Attribute> additionalLDAPAttributes = new LinkedList<Attribute>();
        private AuthorizationPolicy authzPolicy = AuthorizationPolicy.NONE;
        private DN baseDN; // TODO: support template variables.
        private AttributeDescription etagAttribute;
        private ConnectionFactory factory;
        private NameStrategy nameStrategy;
        private AuthzIdTemplate proxiedAuthzTemplate;
        private ReadOnUpdatePolicy readOnUpdatePolicy = CONTROLS;
        private AttributeMapper rootMapper;
        private Schema schema = Schema.getDefaultSchema();
        private boolean usePermissiveModify;
        private boolean useSubtreeDelete;
 
        private Builder() {
            useEtagAttribute();
            useClientDNNaming("uid");
        }
 
        /**
         * Specifies an additional LDAP attribute which should be included with
         * new LDAP entries when they are created. Use this method to specify
         * the LDAP objectClass attribute.
         *
         * @param attribute
         *            The additional LDAP attribute to be included with new LDAP
         *            entries.
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder additionalLDAPAttribute(final Attribute attribute) {
            additionalLDAPAttributes.add(attribute);
            return this;
        }
 
        /**
         * Specifies an additional LDAP attribute which should be included with
         * new LDAP entries when they are created. Use this method to specify
         * the LDAP objectClass attribute.
         *
         * @param attribute
         *            The name of the additional LDAP attribute to be included
         *            with new LDAP entries.
         * @param values
         *            The value(s) of the additional LDAP attribute.
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder additionalLDAPAttribute(final String attribute, final Object... values) {
            return additionalLDAPAttribute(new LinkedAttribute(ad(attribute), values));
        }
 
        /**
         * Sets the policy which should be for performing authorization.
         *
         * @param policy
         *            The policy which should be for performing authorization.
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder authorizationPolicy(final AuthorizationPolicy policy) {
            this.authzPolicy = ensureNotNull(policy);
            return this;
        }
 
        /**
         * Sets the base DN beneath which LDAP entries (resources) are to be
         * found.
         *
         * @param dn
         *            The base DN.
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder baseDN(final DN dn) {
            ensureNotNull(dn);
            this.baseDN = dn;
            return this;
        }
 
        /**
         * Sets the base DN beneath which LDAP entries (resources) are to be
         * found.
         *
         * @param dn
         *            The base DN.
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder baseDN(final String dn) {
            return baseDN(DN.valueOf(dn, schema));
        }
 
        /**
         * Creates a new LDAP resource collection configured using this builder.
         *
         * @return The new LDAP resource collection.
         */
        public CollectionResourceProvider build() {
            ensureNotNull(baseDN);
            if (rootMapper == null) {
                throw new IllegalStateException("No mappings provided");
            }
            switch (authzPolicy) {
            case NONE:
                if (factory == null) {
                    throw new IllegalStateException(
                            "A connection factory must be specified when the authorization policy is 'none'");
                }
                break;
            case PROXY:
                if (proxiedAuthzTemplate == null) {
                    throw new IllegalStateException(
                            "Proxied authorization enabled but no template defined");
                }
                if (factory == null) {
                    throw new IllegalStateException(
                            "A connection factory must be specified when using proxied authorization");
                }
                break;
            case REUSE:
                // This is always ok.
                break;
            }
            return new LDAPCollectionResourceProvider(baseDN, rootMapper, nameStrategy,
                    etagAttribute, new Config(factory, readOnUpdatePolicy, authzPolicy,
                            proxiedAuthzTemplate, useSubtreeDelete, usePermissiveModify, schema),
                    additionalLDAPAttributes);
        }
 
        /**
         * Configures the JSON to LDAP mapping using the provided JSON
         * configuration. The caller is still required to set the connection
         * factory. See the sample configuration file for a detailed description
         * of its content.
         *
         * @param configuration
         *            The JSON configuration.
         * @return A reference to this LDAP resource collection builder.
         * @throws IllegalArgumentException
         *             If the configuration is invalid.
         */
        public Builder configureMapping(final JsonValue configuration) {
            baseDN(configuration.get("baseDN").required().asString());
 
            final JsonValue readOnUpdatePolicy = configuration.get("readOnUpdatePolicy");
            if (!readOnUpdatePolicy.isNull()) {
                readOnUpdatePolicy(readOnUpdatePolicy.asEnum(ReadOnUpdatePolicy.class));
            }
 
            for (final JsonValue v : configuration.get("additionalLDAPAttributes")) {
                final String type = v.get("type").required().asString();
                final List<Object> values = v.get("values").required().asList();
                additionalLDAPAttribute(new LinkedAttribute(type, values));
            }
 
            final JsonValue namingStrategy = configuration.get("namingStrategy");
            if (!namingStrategy.isNull()) {
                final String name = namingStrategy.get("strategy").required().asString();
                if (name.equalsIgnoreCase("clientDNNaming")) {
                    useClientDNNaming(namingStrategy.get("dnAttribute").required().asString());
                } else if (name.equalsIgnoreCase("clientNaming")) {
                    useClientNaming(namingStrategy.get("dnAttribute").required().asString(),
                            namingStrategy.get("idAttribute").required().asString());
                } else if (name.equalsIgnoreCase("serverNaming")) {
                    useServerNaming(namingStrategy.get("dnAttribute").required().asString(),
                            namingStrategy.get("idAttribute").required().asString());
                } else {
                    throw new IllegalArgumentException(
                            "Illegal naming strategy. Must be one of: clientDNNaming, clientNaming, or serverNaming");
                }
            }
 
            final JsonValue etagAttribute = configuration.get("etagAttribute");
            if (!etagAttribute.isNull()) {
                useEtagAttribute(etagAttribute.asString());
            }
 
            /*
             * Default to false, even though it is supported by OpenDJ, because
             * it requires additional permissions.
             */
            if (configuration.get("useSubtreeDelete").defaultTo(false).asBoolean()) {
                useSubtreeDelete();
            }
 
            /*
             * Default to true because it is supported by OpenDJ and does not
             * require additional permissions.
             */
            if (configuration.get("usePermissiveModify").defaultTo(true).asBoolean()) {
                usePermissiveModify();
            }
 
            mapper(configureObjectMapper(configuration.get("attributes").required()));
 
            return this;
        }
 
        /**
         * Sets the LDAP connection factory to be used for accessing the LDAP
         * directory. Each HTTP request will obtain a single connection from the
         * factory and then close it once the HTTP response has been sent. It is
         * recommended that the provided connection factory supports connection
         * pooling.
         *
         * @param factory
         *            The LDAP connection factory to be used for accessing the
         *            LDAP directory.
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder ldapConnectionFactory(final ConnectionFactory factory) {
            this.factory = factory;
            return this;
        }
 
        /**
         * Sets the attribute mapper which should be used for mapping JSON
         * resources to and from LDAP entries.
         *
         * @param mapper
         *            The attribute mapper.
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder mapper(final AttributeMapper mapper) {
            this.rootMapper = mapper;
            return this;
        }
 
        /**
         * Sets the authorization ID template which will be used for proxied
         * authorization. Template parameters are specified by including the
         * parameter name surrounded by curly braces. The template should
         * contain fields which are expected to be found in the security context
         * create during authentication, e.g. "dn:{dn}" or "u:{id}".
         *
         * @param template
         *            The authorization ID template which will be used for
         *            proxied authorization.
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder proxyAuthzIdTemplate(final String template) {
            this.proxiedAuthzTemplate = template != null ? new AuthzIdTemplate(template) : null;
            return this;
        }
 
        /**
         * Sets the policy which should be used in order to read an entry before
         * it is deleted, or after it is added or modified. The default read on
         * update policy is to use {@link ReadOnUpdatePolicy#CONTROLS controls}.
         *
         * @param policy
         *            The policy which should be used in order to read an entry
         *            before it is deleted, or after it is added or modified.
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder readOnUpdatePolicy(final ReadOnUpdatePolicy policy) {
            this.readOnUpdatePolicy = ensureNotNull(policy);
            return this;
        }
 
        /**
         * Sets the schema which should be used when attribute types and
         * controls.
         *
         * @param schema
         *            The schema which should be used when attribute types and
         *            controls.
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder schema(final Schema schema) {
            this.schema = ensureNotNull(schema);
            return this;
        }
 
        /**
         * Indicates that the JSON resource ID must be provided by the user, and
         * will be used for naming the associated LDAP entry. More specifically,
         * LDAP entry names will be derived by appending a single RDN to the
         * {@link #baseDN(String) base DN} composed of the specified attribute
         * type and LDAP value taken from the LDAP entry once attribute mapping
         * has been performed.
         * <p>
         * Note that this naming policy requires that the user provides the
         * resource name when creating new resources, which means it must be
         * included in the resource content when not specified explicitly in the
         * create request.
         *
         * @param attribute
         *            The LDAP attribute which will be used for naming.
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder useClientDNNaming(final AttributeType attribute) {
            this.nameStrategy = new DNNameStrategy(attribute);
            return this;
        }
 
        /**
         * Indicates that the JSON resource ID must be provided by the user, and
         * will be used for naming the associated LDAP entry. More specifically,
         * LDAP entry names will be derived by appending a single RDN to the
         * {@link #baseDN(String) base DN} composed of the specified attribute
         * type and LDAP value taken from the LDAP entry once attribute mapping
         * has been performed.
         * <p>
         * Note that this naming policy requires that the user provides the
         * resource name when creating new resources, which means it must be
         * included in the resource content when not specified explicitly in the
         * create request.
         *
         * @param attribute
         *            The LDAP attribute which will be used for naming.
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder useClientDNNaming(final String attribute) {
            return useClientDNNaming(at(attribute));
        }
 
        /**
         * Indicates that the JSON resource ID must be provided by the user, but
         * will not be used for naming the associated LDAP entry. Instead the
         * JSON resource ID will be taken from the {@code idAttribute} in the
         * LDAP entry, and the LDAP entry name will be derived by appending a
         * single RDN to the {@link #baseDN(String) base DN} composed of the
         * {@code dnAttribute} taken from the LDAP entry once attribute mapping
         * has been performed.
         * <p>
         * Note that this naming policy requires that the user provides the
         * resource name when creating new resources, which means it must be
         * included in the resource content when not specified explicitly in the
         * create request.
         *
         * @param dnAttribute
         *            The attribute which will be used for naming LDAP entries.
         * @param idAttribute
         *            The attribute which will be used for JSON resource IDs.
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder useClientNaming(final AttributeType dnAttribute,
                final AttributeDescription idAttribute) {
            this.nameStrategy = new AttributeNameStrategy(dnAttribute, idAttribute, false);
            return this;
        }
 
        /**
         * Indicates that the JSON resource ID must be provided by the user, but
         * will not be used for naming the associated LDAP entry. Instead the
         * JSON resource ID will be taken from the {@code idAttribute} in the
         * LDAP entry, and the LDAP entry name will be derived by appending a
         * single RDN to the {@link #baseDN(String) base DN} composed of the
         * {@code dnAttribute} taken from the LDAP entry once attribute mapping
         * has been performed.
         * <p>
         * Note that this naming policy requires that the user provides the
         * resource name when creating new resources, which means it must be
         * included in the resource content when not specified explicitly in the
         * create request.
         *
         * @param dnAttribute
         *            The attribute which will be used for naming LDAP entries.
         * @param idAttribute
         *            The attribute which will be used for JSON resource IDs.
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder useClientNaming(final String dnAttribute, final String idAttribute) {
            return useClientNaming(at(dnAttribute), ad(idAttribute));
        }
 
        /**
         * Indicates that the "etag" LDAP attribute should be used for resource
         * versioning. This is the default behavior.
         *
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder useEtagAttribute() {
            return useEtagAttribute("etag");
        }
 
        /**
         * Indicates that the provided LDAP attribute should be used for
         * resource versioning. The "etag" attribute will be used by default.
         *
         * @param attribute
         *            The name of the attribute to use for versioning, or
         *            {@code null} if resource versioning will not supported.
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder useEtagAttribute(final AttributeDescription attribute) {
            this.etagAttribute = attribute;
            return this;
        }
 
        /**
         * Indicates that the provided LDAP attribute should be used for
         * resource versioning. The "etag" attribute will be used by default.
         *
         * @param attribute
         *            The name of the attribute to use for versioning, or
         *            {@code null} if resource versioning will not supported.
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder useEtagAttribute(final String attribute) {
            return useEtagAttribute(attribute != null ? ad(attribute) : null);
        }
 
        /**
         * Indicates that all LDAP modify operations should be performed using
         * the LDAP permissive modify control. The default behavior is to not
         * use the permissive modify control. Use of the control is strongly
         * recommended.
         *
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder usePermissiveModify() {
            this.usePermissiveModify = true;
            return this;
        }
 
        /**
         * Indicates that the JSON resource ID will be derived from the server
         * provided "entryUUID" LDAP attribute. The LDAP entry name will be
         * derived by appending a single RDN to the {@link #baseDN(String) base
         * DN} composed of the {@code dnAttribute} taken from the LDAP entry
         * once attribute mapping has been performed.
         * <p>
         * Note that this naming policy requires that the server provides the
         * resource name when creating new resources, which means it must not be
         * specified in the create request, nor included in the resource
         * content.
         *
         * @param dnAttribute
         *            The attribute which will be used for naming LDAP entries.
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder useServerEntryUUIDNaming(final AttributeType dnAttribute) {
            return useServerNaming(dnAttribute, AttributeDescription
                    .create(getEntryUUIDAttributeType()));
        }
 
        /**
         * Indicates that the JSON resource ID will be derived from the server
         * provided "entryUUID" LDAP attribute. The LDAP entry name will be
         * derived by appending a single RDN to the {@link #baseDN(String) base
         * DN} composed of the {@code dnAttribute} taken from the LDAP entry
         * once attribute mapping has been performed.
         * <p>
         * Note that this naming policy requires that the server provides the
         * resource name when creating new resources, which means it must not be
         * specified in the create request, nor included in the resource
         * content.
         *
         * @param dnAttribute
         *            The attribute which will be used for naming LDAP entries.
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder useServerEntryUUIDNaming(final String dnAttribute) {
            return useServerEntryUUIDNaming(at(dnAttribute));
        }
 
        /**
         * Indicates that the JSON resource ID must not be provided by the user,
         * and will not be used for naming the associated LDAP entry. Instead
         * the JSON resource ID will be taken from the {@code idAttribute} in
         * the LDAP entry, and the LDAP entry name will be derived by appending
         * a single RDN to the {@link #baseDN(String) base DN} composed of the
         * {@code dnAttribute} taken from the LDAP entry once attribute mapping
         * has been performed.
         * <p>
         * Note that this naming policy requires that the server provides the
         * resource name when creating new resources, which means it must not be
         * specified in the create request, nor included in the resource
         * content.
         *
         * @param dnAttribute
         *            The attribute which will be used for naming LDAP entries.
         * @param idAttribute
         *            The attribute which will be used for JSON resource IDs.
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder useServerNaming(final AttributeType dnAttribute,
                final AttributeDescription idAttribute) {
            this.nameStrategy = new AttributeNameStrategy(dnAttribute, idAttribute, true);
            return this;
        }
 
        /**
         * Indicates that the JSON resource ID must not be provided by the user,
         * and will not be used for naming the associated LDAP entry. Instead
         * the JSON resource ID will be taken from the {@code idAttribute} in
         * the LDAP entry, and the LDAP entry name will be derived by appending
         * a single RDN to the {@link #baseDN(String) base DN} composed of the
         * {@code dnAttribute} taken from the LDAP entry once attribute mapping
         * has been performed.
         * <p>
         * Note that this naming policy requires that the server provides the
         * resource name when creating new resources, which means it must not be
         * specified in the create request, nor included in the resource
         * content.
         *
         * @param dnAttribute
         *            The attribute which will be used for naming LDAP entries.
         * @param idAttribute
         *            The attribute which will be used for JSON resource IDs.
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder useServerNaming(final String dnAttribute, final String idAttribute) {
            return useServerNaming(at(dnAttribute), ad(idAttribute));
        }
 
        /**
         * Indicates that all LDAP delete operations should be performed using
         * the LDAP subtree delete control. The default behavior is to not use
         * the subtree delete control.
         *
         * @return A reference to this LDAP resource collection builder.
         */
        public Builder useSubtreeDelete() {
            this.useSubtreeDelete = true;
            return this;
        }
 
        private AttributeDescription ad(final String attribute) {
            return AttributeDescription.valueOf(attribute, schema);
        }
 
        private AttributeType at(final String attribute) {
            return schema.getAttributeType(attribute);
        }
 
        private AttributeMapper configureMapper(final JsonValue mapper) {
            if (mapper.isDefined("constant")) {
                return constant(mapper.get("constant").getObject());
            } else if (mapper.isDefined("simple")) {
                final JsonValue config = mapper.get("simple");
                final SimpleAttributeMapper s =
                        simple(ad(config.get("ldapAttribute").required().asString()));
                if (config.isDefined("defaultJSONValue")) {
                    s.defaultJSONValue(config.get("defaultJSONValue").getObject());
                }
                if (config.get("isBinary").defaultTo(false).asBoolean()) {
                    s.isBinary();
                }
                if (config.get("isRequired").defaultTo(false).asBoolean()) {
                    s.isRequired();
                }
                if (config.get("isSingleValued").defaultTo(false).asBoolean()) {
                    s.isSingleValued();
                }
                s.writability(parseWritability(mapper, config));
                return s;
            } else if (mapper.isDefined("reference")) {
                final JsonValue config = mapper.get("reference");
                final AttributeDescription ldapAttribute =
                        ad(config.get("ldapAttribute").required().asString());
                final DN baseDN = DN.valueOf(config.get("baseDN").required().asString(), schema);
                final AttributeDescription primaryKey =
                        ad(config.get("primaryKey").required().asString());
                final AttributeMapper m = configureMapper(config.get("mapper").required());
                final ReferenceAttributeMapper r = reference(ldapAttribute, baseDN, primaryKey, m);
                if (config.get("isRequired").defaultTo(false).asBoolean()) {
                    r.isRequired();
                }
                if (config.get("isSingleValued").defaultTo(false).asBoolean()) {
                    r.isSingleValued();
                }
                if (config.isDefined("searchFilter")) {
                    r.searchFilter(config.get("searchFilter").asString());
                }
                r.writability(parseWritability(mapper, config));
                return r;
            } else if (mapper.isDefined("object")) {
                return configureObjectMapper(mapper.get("object"));
            } else {
                throw new JsonValueException(mapper,
                        "Illegal mapping: must contain constant, simple, or object");
            }
        }
 
        private ObjectAttributeMapper configureObjectMapper(final JsonValue mapper) {
            final ObjectAttributeMapper object = object();
            for (final String attribute : mapper.keys()) {
                object.attribute(attribute, configureMapper(mapper.get(attribute)));
            }
            return object;
        }
 
        private WritabilityPolicy parseWritability(final JsonValue mapper, final JsonValue config) {
            if (config.isDefined("writability")) {
                final String writability = config.get("writability").asString();
                if (writability.equalsIgnoreCase("readOnly")) {
                    return WritabilityPolicy.READ_ONLY;
                } else if (writability.equalsIgnoreCase("readOnlyDiscardWrites")) {
                    return WritabilityPolicy.READ_ONLY_DISCARD_WRITES;
                } else if (writability.equalsIgnoreCase("createOnly")) {
                    return WritabilityPolicy.CREATE_ONLY;
                } else if (writability.equalsIgnoreCase("createOnlyDiscardWrites")) {
                    return WritabilityPolicy.CREATE_ONLY_DISCARD_WRITES;
                } else if (writability.equalsIgnoreCase("readWrite")) {
                    return WritabilityPolicy.READ_WRITE;
                } else {
                    throw new JsonValueException(mapper,
                            "Illegal writability: must be one of readOnly, readOnlyDiscardWrites, "
                                    + "createOnly, createOnlyDiscardWrites, or readWrite");
                }
            } else {
                return WritabilityPolicy.READ_WRITE;
            }
        }
    }
 
    private static final class AttributeNameStrategy extends NameStrategy {
        private final AttributeDescription dnAttribute;
        private final AttributeDescription idAttribute;
        private final boolean isServerProvided;
 
        private AttributeNameStrategy(final AttributeType dnAttribute,
                final AttributeDescription idAttribute, final boolean isServerProvided) {
            this.dnAttribute = AttributeDescription.create(dnAttribute);
            if (this.dnAttribute.equals(idAttribute)) {
                throw new IllegalArgumentException("DN and ID attributes must be different");
            }
            this.idAttribute = ensureNotNull(idAttribute);
            this.isServerProvided = isServerProvided;
        }
 
        @Override
        SearchRequest createSearchRequest(final Context c, final DN baseDN, final String resourceId) {
            return newSearchRequest(baseDN, SearchScope.SINGLE_LEVEL, Filter.equality(idAttribute
                    .toString(), resourceId));
        }
 
        @Override
        void getLDAPAttributes(final Context c, final Set<String> ldapAttributes) {
            ldapAttributes.add(idAttribute.toString());
        }
 
        @Override
        String getResourceId(final Context c, final Entry entry) {
            return entry.parseAttribute(idAttribute).asString();
        }
 
        @Override
        void setResourceId(final Context c, final DN baseDN, final String resourceId,
                final Entry entry) throws ResourceException {
            if (isServerProvided) {
                if (resourceId != null) {
                    throw new BadRequestException("Resources cannot be created with a "
                            + "client provided resource ID");
                }
            } else {
                entry.addAttribute(new LinkedAttribute(idAttribute, ByteString.valueOf(resourceId)));
            }
            final String rdnValue = entry.parseAttribute(dnAttribute).asString();
            final RDN rdn = new RDN(dnAttribute.getAttributeType(), rdnValue);
            entry.setName(baseDN.child(rdn));
 
        }
    }
 
    private static final class DNNameStrategy extends NameStrategy {
        private final AttributeDescription attribute;
 
        private DNNameStrategy(final AttributeType attribute) {
            this.attribute = AttributeDescription.create(attribute);
        }
 
        @Override
        SearchRequest createSearchRequest(final Context c, final DN baseDN, final String resourceId) {
            return newSearchRequest(baseDN.child(rdn(resourceId)), SearchScope.BASE_OBJECT, Filter
                    .objectClassPresent());
        }
 
        @Override
        void getLDAPAttributes(final Context c, final Set<String> ldapAttributes) {
            ldapAttributes.add(attribute.toString());
        }
 
        @Override
        String getResourceId(final Context c, final Entry entry) {
            return entry.parseAttribute(attribute).asString();
        }
 
        @Override
        void setResourceId(final Context c, final DN baseDN, final String resourceId,
                final Entry entry) throws ResourceException {
            if (resourceId != null) {
                entry.setName(baseDN.child(rdn(resourceId)));
                entry.addAttribute(new LinkedAttribute(attribute, ByteString.valueOf(resourceId)));
            } else if (entry.getAttribute(attribute) != null) {
                entry.setName(baseDN.child(rdn(entry.parseAttribute(attribute).asString())));
            } else {
                throw new BadRequestException("Resources cannot be created without a "
                        + "client provided resource ID");
            }
        }
 
        private RDN rdn(final String resourceId) {
            return new RDN(attribute.getAttributeType(), resourceId);
        }
 
    }
 
    /**
     * Adapts a {@code Throwable} to a {@code ResourceException}. If the
     * {@code Throwable} is an LDAP {@code ErrorResultException} then an
     * appropriate {@code ResourceException} is returned, otherwise an
     * {@code InternalServerErrorException} is returned.
     *
     * @param t
     *            The {@code Throwable} to be converted.
     * @return The equivalent resource exception.
     */
    public static ResourceException asResourceException(final Throwable t) {
        int resourceResultCode;
        try {
            throw t;
        } catch (final ResourceException e) {
            return e;
        } catch (final AssertionFailureException e) {
            resourceResultCode = ResourceException.VERSION_MISMATCH;
        } catch (final ConstraintViolationException e) {
            final ResultCode rc = e.getResult().getResultCode();
            if (rc.equals(ResultCode.ENTRY_ALREADY_EXISTS)) {
                resourceResultCode = ResourceException.VERSION_MISMATCH; // Consistent with MVCC.
            } else {
                // Schema violation, etc.
                resourceResultCode = ResourceException.BAD_REQUEST;
            }
        } catch (final AuthenticationException e) {
            resourceResultCode = 401;
        } catch (final AuthorizationException e) {
            resourceResultCode = ResourceException.FORBIDDEN;
        } catch (final ConnectionException e) {
            resourceResultCode = ResourceException.UNAVAILABLE;
        } catch (final EntryNotFoundException e) {
            resourceResultCode = ResourceException.NOT_FOUND;
        } catch (final MultipleEntriesFoundException e) {
            resourceResultCode = ResourceException.INTERNAL_ERROR;
        } catch (final TimeoutResultException e) {
            resourceResultCode = 408;
        } catch (final ErrorResultException e) {
            final ResultCode rc = e.getResult().getResultCode();
            if (rc.equals(ResultCode.ADMIN_LIMIT_EXCEEDED)) {
                resourceResultCode = 413; // Request Entity Too Large
            } else if (rc.equals(ResultCode.SIZE_LIMIT_EXCEEDED)) {
                resourceResultCode = 413; // Request Entity Too Large
            } else {
                resourceResultCode = ResourceException.INTERNAL_ERROR;
            }
        } catch (final Throwable tmp) {
            resourceResultCode = ResourceException.INTERNAL_ERROR;
        }
        return ResourceException.getException(resourceResultCode, t.getMessage(), t);
    }
 
    /**
     * Returns a builder for incrementally constructing LDAP resource
     * collections.
     *
     * @return An LDAP resource collection builder.
     */
    public static Builder builder() {
        return new Builder();
    }
 
    /**
     * 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.
     * @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 JsonValue normalizedConfiguration =
                normalizeConnectionFactory(configuration, name, 0);
        return configureConnectionFactory(normalizedConfiguration);
    }
 
    /**
     * Returns an attribute mapper which maps a single JSON attribute to a JSON
     * constant.
     *
     * @param value
     *            The constant JSON value (a Boolean, Number, String, Map, or
     *            List).
     * @return The attribute mapper.
     */
    public static AttributeMapper constant(final Object value) {
        return new JSONConstantAttributeMapper(value);
    }
 
    /**
     * Returns an attribute mapper which maps JSON objects to LDAP attributes.
     *
     * @return The attribute mapper.
     */
    public static ObjectAttributeMapper object() {
        return new ObjectAttributeMapper();
    }
 
    /**
     * Returns an attribute mapper which provides a mapping from a JSON value to
     * a single DN valued LDAP attribute.
     *
     * @param attribute
     *            The DN valued LDAP attribute to be mapped.
     * @param baseDN
     *            The search base DN for performing reverse lookups.
     * @param primaryKey
     *            The search primary key LDAP attribute to use for performing
     *            reverse lookups.
     * @param mapper
     *            An attribute mapper which will be used to map LDAP attributes
     *            in the referenced entry.
     * @return The attribute mapper.
     */
    public static ReferenceAttributeMapper reference(final AttributeDescription attribute,
            final DN baseDN, final AttributeDescription primaryKey, final AttributeMapper mapper) {
        return new ReferenceAttributeMapper(attribute, baseDN, primaryKey, mapper);
    }
 
    /**
     * Returns an attribute mapper which provides a mapping from a JSON value to
     * a single DN valued LDAP attribute.
     *
     * @param attribute
     *            The DN valued LDAP attribute to be mapped.
     * @param baseDN
     *            The search base DN for performing reverse lookups.
     * @param primaryKey
     *            The search primary key LDAP attribute to use for performing
     *            reverse lookups.
     * @param mapper
     *            An attribute mapper which will be used to map LDAP attributes
     *            in the referenced entry.
     * @return The attribute mapper.
     */
    public static ReferenceAttributeMapper reference(final String attribute, final String baseDN,
            final String primaryKey, final AttributeMapper mapper) {
        return reference(AttributeDescription.valueOf(attribute), DN.valueOf(baseDN),
                AttributeDescription.valueOf(primaryKey), mapper);
    }
 
    /**
     * Returns an attribute mapper which provides a simple mapping from a JSON
     * value to a single LDAP attribute.
     *
     * @param attribute
     *            The LDAP attribute to be mapped.
     * @return The attribute mapper.
     */
    public static SimpleAttributeMapper simple(final AttributeDescription attribute) {
        return new SimpleAttributeMapper(attribute);
    }
 
    /**
     * Returns an attribute mapper which provides a simple mapping from a JSON
     * value to a single LDAP attribute.
     *
     * @param attribute
     *            The LDAP attribute to be mapped.
     * @return The attribute mapper.
     */
    public static SimpleAttributeMapper simple(final String attribute) {
        return simple(AttributeDescription.valueOf(attribute));
    }
 
    private static ConnectionFactory configureConnectionFactory(final JsonValue configuration) {
        // Parse pool parameters,
        final int connectionPoolSize =
                Math.max(configuration.get("connectionPoolSize").defaultTo(10).asInteger(), 1);
        final int heartBeatIntervalSeconds =
                Math.max(configuration.get("heartBeatIntervalSeconds").defaultTo(30).asInteger(), 1);
        final int heartBeatTimeoutMilliSeconds =
                Math.max(configuration.get("heartBeatTimeoutMilliSeconds").defaultTo(500)
                        .asInteger(), 100);
 
        // Parse authentication parameters.
        final BindRequest bindRequest;
        if (configuration.isDefined("authentication")) {
            final JsonValue authn = configuration.get("authentication");
            if (authn.isDefined("simple")) {
                final JsonValue simple = authn.get("simple");
                bindRequest =
                        Requests.newSimpleBindRequest(simple.get("bindDN").required().asString(),
                                simple.get("bindPassword").required().asString().toCharArray());
            } else {
                throw new IllegalArgumentException("Only simple authentication is supported");
            }
        } else {
            bindRequest = null;
        }
 
        // Parse SSL/StartTLS parameters.
        final ConnectionSecurity connectionSecurity =
                configuration.get("connectionSecurity").defaultTo(ConnectionSecurity.NONE).asEnum(
                        ConnectionSecurity.class);
        final LDAPOptions options = new LDAPOptions();
        if (connectionSecurity != ConnectionSecurity.NONE) {
            try {
                // Configure SSL.
                final SSLContextBuilder builder = new SSLContextBuilder();
 
                // Parse trust store configuration.
                final TrustManagerType trustManagerType =
                        configuration.get("trustManager").defaultTo(TrustManagerType.TRUSTALL)
                                .asEnum(TrustManagerType.class);
                switch (trustManagerType) {
                case TRUSTALL:
                    builder.setTrustManager(TrustManagers.trustAll());
                    break;
                case JVM:
                    // Do nothing: JVM trust manager is the default.
                    break;
                case FILE:
                    final String fileName =
                            configuration.get("fileBasedTrustManagerFile").required().asString();
                    final String password =
                            configuration.get("fileBasedTrustManagerPassword").asString();
                    final String type = configuration.get("fileBasedTrustManagerType").asString();
                    builder.setTrustManager(TrustManagers.checkUsingTrustStore(fileName,
                            password != null ? password.toCharArray() : null, type));
                    break;
                }
                options.setSSLContext(builder.getSSLContext());
                options.setUseStartTLS(connectionSecurity == ConnectionSecurity.STARTTLS);
            } catch (GeneralSecurityException e) {
                // Rethrow as unchecked exception.
                throw new IllegalArgumentException(e);
            } catch (IOException 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, bindRequest, connectionPoolSize,
                        heartBeatIntervalSeconds, heartBeatTimeoutMilliSeconds, options);
 
        // Parse secondary data center(s).
        final JsonValue secondaryLDAPServers = configuration.get("secondaryLDAPServers");
        final ConnectionFactory secondary;
        if (secondaryLDAPServers.isList()) {
            if (secondaryLDAPServers.size() > 0) {
                secondary =
                        parseLDAPServers(secondaryLDAPServers, bindRequest, connectionPoolSize,
                                heartBeatIntervalSeconds, heartBeatTimeoutMilliSeconds, options);
            } else {
                secondary = null;
            }
        } else if (!secondaryLDAPServers.isNull()) {
            throw new IllegalArgumentException("Invalid secondaryLDAPServers configuration");
        } else {
            secondary = null;
        }
 
        // Create fail-over.
        if (secondary != null) {
            return Connections.newLoadBalancer(new FailoverLoadBalancingAlgorithm(Arrays.asList(
                    primary, secondary), heartBeatIntervalSeconds, TimeUnit.SECONDS));
        } 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 IllegalArgumentException(
                    "The LDAP server configuration '"
                            + name
                            + "' could not be parsed because of potential circular inheritance dependencies");
        }
 
        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<String, Object>(parent.asMap());
            normalized.putAll(current.asMap());
            normalized.remove("inheritFrom");
            return new JsonValue(normalized);
        } else {
            // No normalization required.
            return current;
        }
    }
 
    private static ConnectionFactory parseLDAPServers(final JsonValue config,
            final BindRequest bindRequest, final int connectionPoolSize,
            final int heartBeatIntervalSeconds, final int heartBeatTimeoutMilliSeconds,
            final LDAPOptions options) {
        final List<ConnectionFactory> servers = new ArrayList<ConnectionFactory>(config.size());
        for (final JsonValue server : config) {
            final String host = server.get("hostname").required().asString();
            final int port = server.get("port").required().asInteger();
            ConnectionFactory factory = new LDAPConnectionFactory(host, port, options);
            factory =
                    Connections.newHeartBeatConnectionFactory(factory,
                            heartBeatIntervalSeconds * 1000, heartBeatTimeoutMilliSeconds,
                            TimeUnit.MILLISECONDS);
            if (bindRequest != null) {
                factory = Connections.newAuthenticatedConnectionFactory(factory, bindRequest);
            }
            if (connectionPoolSize > 1) {
                factory =
                        Connections.newCachedConnectionPool(factory, 0, connectionPoolSize, 60L,
                                TimeUnit.SECONDS);
            }
            servers.add(factory);
        }
        if (servers.size() > 1) {
            return Connections.newLoadBalancer(new RoundRobinLoadBalancingAlgorithm(servers,
                    heartBeatIntervalSeconds, TimeUnit.SECONDS));
        } else {
            return servers.get(0);
        }
    }
 
    private Rest2LDAP() {
        // Prevent instantiation.
    }
 
}