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

Jean-Noël Rouvignac
04.47.2016 61dfebf3a3931588ff5d5d4b17dcea60c1e6f197
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
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
/*
 * 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 2007-2010 Sun Microsystems, Inc.
 * Portions Copyright 2012-2016 ForgeRock AS.
 */
package org.opends.admin.ads;
 
import static org.forgerock.opendj.ldap.Filter.*;
import static org.forgerock.opendj.ldap.ModificationType.*;
import static org.forgerock.opendj.ldap.SearchScope.*;
import static org.forgerock.opendj.ldap.requests.Requests.*;
import static org.forgerock.util.Utils.*;
import static org.opends.messages.QuickSetupMessages.*;
import static org.opends.server.schema.SchemaConstants.*;
 
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
 
import javax.naming.ldap.Rdn;
 
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.forgerock.opendj.ldap.Attribute;
import org.forgerock.opendj.ldap.AuthorizationException;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.Connection;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.EntryNotFoundException;
import org.forgerock.opendj.ldap.Filter;
import org.forgerock.opendj.ldap.LdapException;
import org.forgerock.opendj.ldap.LinkedAttribute;
import org.forgerock.opendj.ldap.Modification;
import org.forgerock.opendj.ldap.ModificationType;
import org.forgerock.opendj.ldap.RDN;
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.controls.SubtreeDeleteRequestControl;
import org.forgerock.opendj.ldap.requests.AddRequest;
import org.forgerock.opendj.ldap.requests.DeleteRequest;
import org.forgerock.opendj.ldap.requests.ModifyRequest;
import org.forgerock.opendj.ldap.requests.SearchRequest;
import org.forgerock.opendj.ldap.responses.Result;
import org.forgerock.opendj.ldap.responses.SearchResultEntry;
import org.forgerock.opendj.ldap.schema.AttributeType;
import org.forgerock.opendj.ldif.ConnectionEntryReader;
import org.opends.admin.ads.ADSContextException.ErrorType;
import org.opends.admin.ads.util.ConnectionWrapper;
import org.opends.quicksetup.Constants;
import org.opends.server.types.HostPort;
 
/** Class used to update and read the contents of the Administration Data. */
public class ADSContext
{
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
  /**
   * Enumeration containing the different server properties syntaxes that could
   * be stored in the ADS.
   */
  public enum ADSPropertySyntax
  {
    /** String syntax. */
    STRING,
    /** Integer syntax. */
    INTEGER,
    /** Boolean syntax. */
    BOOLEAN,
    /** Certificate;binary syntax. */
    CERTIFICATE_BINARY
  }
 
  /** Enumeration containing the different server properties that are stored in the ADS. */
  public enum ServerProperty
  {
    /** The ID used to identify the server (hostname + port). */
    ID("id",ADSPropertySyntax.STRING),
    /** The host name of the server. */
    HOST_NAME("hostname",ADSPropertySyntax.STRING),
    /** The LDAP port of the server. */
    LDAP_PORT("ldapport",ADSPropertySyntax.INTEGER),
    /** The JMX port of the server. */
    JMX_PORT("jmxport",ADSPropertySyntax.INTEGER),
    /** The JMX secure port of the server. */
    JMXS_PORT("jmxsport",ADSPropertySyntax.INTEGER),
    /** The LDAPS port of the server. */
    LDAPS_PORT("ldapsport",ADSPropertySyntax.INTEGER),
    /** The administration connector port of the server. */
    ADMIN_PORT("adminport",ADSPropertySyntax.INTEGER),
    /** The certificate used by the server. */
    CERTIFICATE("certificate",ADSPropertySyntax.STRING),
    /** The path where the server is installed. */
    INSTANCE_PATH("instancepath",ADSPropertySyntax.STRING),
    /** The description of the server. */
    DESCRIPTION("description",ADSPropertySyntax.STRING),
    /** The OS of the machine where the server is installed. */
    HOST_OS("os",ADSPropertySyntax.STRING),
    /** Whether LDAP is enabled or not. */
    LDAP_ENABLED("ldapEnabled",ADSPropertySyntax.BOOLEAN),
    /** Whether LDAPS is enabled or not. */
    LDAPS_ENABLED("ldapsEnabled",ADSPropertySyntax.BOOLEAN),
    /** Whether ADMIN is enabled or not. */
    ADMIN_ENABLED("adminEnabled",ADSPropertySyntax.BOOLEAN),
    /** Whether StartTLS is enabled or not. */
    STARTTLS_ENABLED("startTLSEnabled",ADSPropertySyntax.BOOLEAN),
    /** Whether JMX is enabled or not. */
    JMX_ENABLED("jmxEnabled",ADSPropertySyntax.BOOLEAN),
    /** Whether JMX is enabled or not. */
    JMXS_ENABLED("jmxsEnabled",ADSPropertySyntax.BOOLEAN),
    /** The location of the server. */
    LOCATION("location",ADSPropertySyntax.STRING),
    /** The groups to which this server belongs. */
    GROUPS("memberofgroups",ADSPropertySyntax.STRING),
    /** The unique name of the instance key public-key certificate. */
    INSTANCE_KEY_ID("ds-cfg-key-id",ADSPropertySyntax.STRING),
    /**
     * The instance key-pair public-key certificate. Note: This attribute
     * belongs to an instance key entry, separate from the server entry and
     * named by the ds-cfg-key-id attribute from the server entry.
     */
    INSTANCE_PUBLIC_KEY_CERTIFICATE("ds-cfg-public-key-certificate", ADSPropertySyntax.CERTIFICATE_BINARY);
 
    private final String attrName;
    private final ADSPropertySyntax attSyntax;
 
    /**
     * Private constructor.
     *
     * @param n
     *          the name of the attribute.
     * @param s
     *          the name of the syntax.
     */
    private ServerProperty(String n, ADSPropertySyntax s)
    {
      attrName = n;
      attSyntax = s;
    }
 
    /**
     * Returns the attribute name.
     *
     * @return the attribute name.
     */
    public String getAttributeName()
    {
      return attrName;
    }
 
    /**
     * Returns the attribute syntax.
     *
     * @return the attribute syntax.
     */
    public ADSPropertySyntax getAttributeSyntax()
    {
      return attSyntax;
    }
  }
 
  /** Default global admin UID. */
  public static final String GLOBAL_ADMIN_UID = "admin";
 
  /** The list of server properties that are multivalued. */
  private static final Set<ServerProperty> MULTIVALUED_SERVER_PROPERTIES = new HashSet<>();
  static
  {
    MULTIVALUED_SERVER_PROPERTIES.add(ServerProperty.GROUPS);
  }
 
  /** The default server group which will contain all registered servers. */
  private static final String ALL_SERVERGROUP_NAME = "all-servers";
 
  /** Enumeration containing the different server group properties that are stored in the ADS. */
  private enum ServerGroupProperty
  {
    /** The UID of the server group. */
    UID("cn"),
    /** The description of the server group. */
    DESCRIPTION("description"),
    /** The members of the server group. */
    MEMBERS("uniqueMember");
 
    private final String attrName;
 
    /**
     * Private constructor.
     *
     * @param n
     *          the attribute name.
     */
    private ServerGroupProperty(String n)
    {
      attrName = n;
    }
 
    /**
     * Returns the attribute name.
     *
     * @return the attribute name.
     */
    public String getAttributeName()
    {
      return attrName;
    }
  }
 
  /** The list of server group properties that are multivalued. */
  private static final Set<ServerGroupProperty> MULTIVALUED_SERVER_GROUP_PROPERTIES = new HashSet<>();
  static
  {
    MULTIVALUED_SERVER_GROUP_PROPERTIES.add(ServerGroupProperty.MEMBERS);
  }
 
  /** The enumeration containing the different Administrator properties. */
  public enum AdministratorProperty
  {
    /** The UID of the administrator. */
    UID("id", ADSPropertySyntax.STRING),
    /** The password of the administrator. */
    PASSWORD("password", ADSPropertySyntax.STRING),
    /** The description of the administrator. */
    DESCRIPTION("description", ADSPropertySyntax.STRING),
    /** The DN of the administrator. */
    ADMINISTRATOR_DN("administrator dn", ADSPropertySyntax.STRING),
    /** The administrator privilege. */
    PRIVILEGE("privilege", ADSPropertySyntax.STRING);
 
    private final String attrName;
    private final ADSPropertySyntax attrSyntax;
 
    /**
     * Private constructor.
     *
     * @param n
     *          the name of the attribute.
     * @param s
     *          the name of the syntax.
     */
    private AdministratorProperty(String n, ADSPropertySyntax s)
    {
      attrName = n;
      attrSyntax = s;
    }
 
    /**
     * Returns the attribute name.
     *
     * @return the attribute name.
     */
    public String getAttributeName()
    {
      return attrName;
    }
 
    /**
     * Returns the attribute syntax.
     *
     * @return the attribute syntax.
     */
    public ADSPropertySyntax getAttributeSyntax()
    {
      return attrSyntax;
    }
  }
 
  /** The context used to retrieve information. */
  private final ConnectionWrapper connectionWrapper;
 
  /**
   * Constructor of the ADSContext.
   *
   * @param connectionWrapper
   *          provide an Ldap Connection
   */
  public ADSContext(ConnectionWrapper connectionWrapper)
  {
    this.connectionWrapper = connectionWrapper;
  }
 
  /**
   * Returns the connection used to retrieve information by this ADSContext.
   *
   * @return the connection
   */
  public ConnectionWrapper getConnection()
  {
    return connectionWrapper;
  }
 
  /**
   * Returns the host name and port number of this connection.
   *
   * @return the hostPort of this connection
   */
  public HostPort getHostPort()
  {
    return connectionWrapper.getHostPort();
  }
 
  /**
   * Method called to register a server in the ADS.
   *
   * @param serverProperties
   *          the properties of the server.
   * @throws ADSContextException
   *           if the server could not be registered.
   */
  public void registerServer(Map<ServerProperty, Object> serverProperties) throws ADSContextException
  {
    DN dn = makeDNFromServerProperties(serverProperties);
 
    AddRequest request = newAddRequest(dn);
    for (ServerProperty prop : serverProperties.keySet())
    {
      Attribute attribute = makeAttrFromServerProperty(prop, serverProperties.get(prop));
      if (attribute != null)
      {
        request.addAttribute(attribute);
      }
    }
    // TODO: use another structural objectclass
    request.addAttribute("objectclass", "top", "ds-cfg-branch", "extensibleobject");
    try
    {
      // This check is required because by default the server container entry
      // does not exist.
      if (!isExistingEntry(getServerContainerDN()))
      {
        createContainerEntry(getServerContainerDN());
      }
      throwIfNotSuccess(connectionWrapper.getConnection().add(request));
      if (serverProperties.containsKey(ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE))
      {
        registerInstanceKeyCertificate(serverProperties, dn);
      }
 
      // register this server into "all" groups
      Map<ServerGroupProperty, Object> serverGroupProperties = new HashMap<>();
      Set<String> memberList = getServerGroupMemberList(ALL_SERVERGROUP_NAME);
      if (memberList == null)
      {
        memberList = new HashSet<>();
      }
      String newMember = "cn=" + Rdn.escapeValue(serverProperties.get(ServerProperty.ID));
 
      memberList.add(newMember);
      serverGroupProperties.put(ServerGroupProperty.MEMBERS, memberList);
 
      updateServerGroup(ALL_SERVERGROUP_NAME, serverGroupProperties);
 
      // Update the server property "GROUPS"
      Set<?> rawGroupList = (Set<?>) serverProperties.get(ServerProperty.GROUPS);
      Set<String> groupList = new HashSet<>();
      if (rawGroupList != null)
      {
        for (Object elm : rawGroupList)
        {
          groupList.add(elm.toString());
        }
      }
      groupList.add(ALL_SERVERGROUP_NAME);
      serverProperties.put(ServerProperty.GROUPS, groupList);
      updateServer(serverProperties);
    }
    catch (ADSContextException ace)
    {
      throw ace;
    }
    catch (LdapException x)
    {
      if (x.getResult().getResultCode().equals(ResultCode.ENTRY_ALREADY_EXISTS))
      {
        throw new ADSContextException(ErrorType.ALREADY_REGISTERED);
      }
      throw new ADSContextException(ErrorType.ERROR_UNEXPECTED, x);
    }
  }
 
  /**
   * Method called to update the properties of a server in the ADS.
   *
   * @param serverProperties
   *          the new properties of the server.
   * @param newServerId
   *          The new server Identifier, or null.
   * @throws ADSContextException
   *           if the server could not be registered.
   */
  private void updateServer(Map<ServerProperty, Object> serverProperties)
      throws ADSContextException
  {
    DN dn = makeDNFromServerProperties(serverProperties);
 
    try
    {
      ModifyRequest request = newModifyRequest(dn);
      for (ServerProperty prop : serverProperties.keySet())
      {
        Attribute attr = makeAttrFromServerProperty(prop, serverProperties.get(prop));
        if (attr != null)
        {
          request.addModification(new Modification(REPLACE, attr));
        }
      }
      throwIfNotSuccess(connectionWrapper.getConnection().modify(request));
 
      if (serverProperties.containsKey(ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE))
      {
        registerInstanceKeyCertificate(serverProperties, dn);
      }
    }
    catch (ADSContextException ace)
    {
      throw ace;
    }
    catch (EntryNotFoundException x)
    {
      throw new ADSContextException(ErrorType.NOT_YET_REGISTERED);
    }
    catch (Exception x)
    {
      throw new ADSContextException(ErrorType.ERROR_UNEXPECTED, x);
    }
  }
 
  /**
   * Method called to unregister a server in the ADS. Note that the server's
   * instance key-pair public-key certificate entry (created in
   * <tt>registerServer()</tt>) is left untouched.
   *
   * @param serverProperties
   *          the properties of the server.
   * @throws ADSContextException
   *           if the server could not be unregistered.
   */
  public void unregisterServer(Map<ServerProperty, Object> serverProperties) throws ADSContextException
  {
    DN dn = makeDNFromServerProperties(serverProperties);
    Connection conn = connectionWrapper.getConnection();
    try
    {
      // Unregister the server from the server groups.
      String member = "cn=" + Rdn.escapeValue(serverProperties.get(ServerProperty.ID));
      Set<Map<ServerGroupProperty, Object>> serverGroups = readServerGroupRegistry();
      for (Map<ServerGroupProperty, Object> serverGroup : serverGroups)
      {
        Set<?> memberList = (Set<?>) serverGroup.get(ServerGroupProperty.MEMBERS);
        if (memberList != null && memberList.remove(member))
        {
          Map<ServerGroupProperty, Object> serverGroupProperties = new HashMap<>();
          serverGroupProperties.put(ServerGroupProperty.MEMBERS, memberList);
          String groupName = (String) serverGroup.get(ServerGroupProperty.UID);
          updateServerGroup(groupName, serverGroupProperties);
        }
      }
 
      throwIfNotSuccess(conn.delete(newDeleteRequest(dn)));
    }
    catch (EntryNotFoundException x)
    {
      throw new ADSContextException(ErrorType.NOT_YET_REGISTERED);
    }
    catch (LdapException x)
    {
      throw new ADSContextException(ErrorType.ERROR_UNEXPECTED, x);
    }
 
    String serverID = getServerID(serverProperties);
    if (serverID != null)
    {
      // Unregister the server in server groups
      String memberAttrName = ServerGroupProperty.MEMBERS.getAttributeName();
      Filter filter = Filter.valueOf("(" + memberAttrName + "=cn=" + serverID + ")");
      SearchRequest request = newSearchRequest(getServerGroupContainerDN(), SINGLE_LEVEL, filter);
      try (ConnectionEntryReader entryReader = conn.search(request);)
      {
        while (entryReader.hasNext())
        {
          SearchResultEntry sr = entryReader.readEntry();
          DN groupDn = sr.getName();
          Attribute newAttr = new LinkedAttribute(memberAttrName);
          for (Attribute attr : sr.getAllAttributes())
          {
            AttributeType attrType = attr.getAttributeDescription().getAttributeType();
            if (attrType.hasName(memberAttrName))
            {
              for (ByteString value : attr)
              {
                if (!value.toString().equalsIgnoreCase("cn=" + serverID))
                {
                  newAttr.add(value);
                }
              }
            }
          }
          ModificationType modType = newAttr.size() > 0 ? REPLACE : DELETE;
          ModifyRequest modRequest = newModifyRequest(groupDn)
              .addModification(new Modification(modType, newAttr));
          throwIfNotSuccess(conn.modify(modRequest));
        }
      }
      catch (EntryNotFoundException x)
      {
        throw new ADSContextException(ErrorType.BROKEN_INSTALL);
      }
      catch (AuthorizationException x)
      {
        throw new ADSContextException(ErrorType.ACCESS_PERMISSION);
      }
      catch (IOException x)
      {
        throw new ADSContextException(ErrorType.ERROR_UNEXPECTED, x);
      }
    }
  }
 
  /**
   * Returns whether a given server is already registered or not.
   *
   * @param serverProperties
   *          the server properties.
   * @return <CODE>true</CODE> if the server was registered and
   *         <CODE>false</CODE> otherwise.
   * @throws ADSContextException
   *           if something went wrong.
   */
  private boolean isServerAlreadyRegistered(Map<ServerProperty, Object> serverProperties) throws ADSContextException
  {
    return isExistingEntry(makeDNFromServerProperties(serverProperties));
  }
 
  /**
   * Returns whether a given administrator is already registered or not.
   *
   * @param uid
   *          the administrator UID.
   * @return <CODE>true</CODE> if the administrator was registered and
   *         <CODE>false</CODE> otherwise.
   * @throws ADSContextException
   *           if something went wrong.
   */
  private boolean isAdministratorAlreadyRegistered(String uid) throws ADSContextException
  {
    return isExistingEntry(getAdministratorDN(uid));
  }
 
  /**
   * A convenience method that takes some server properties as parameter and if
   * there is no server registered associated with those properties, registers
   * it and if it is already registered, updates it.
   *
   * @param serverProperties
   *          the server properties.
   * @return 0 if the server was registered; 1 if updated (i.e., the server
   *         entry was already in ADS).
   * @throws ADSContextException
   *           if something goes wrong.
   */
  public int registerOrUpdateServer(Map<ServerProperty, Object> serverProperties) throws ADSContextException
  {
    try
    {
      registerServer(serverProperties);
      return 0;
    }
    catch (ADSContextException x)
    {
      if (x.getError() == ErrorType.ALREADY_REGISTERED)
      {
        updateServer(serverProperties);
        return 1;
      }
 
      throw x;
    }
  }
 
  /**
   * Returns the member list of a group of server.
   *
   * @param serverGroupId
   *          The group name.
   * @return the member list of a group of server.
   * @throws ADSContextException
   *           if something goes wrong.
   */
  private Set<String> getServerGroupMemberList(String serverGroupId) throws ADSContextException
  {
    String dn = "cn=" + Rdn.escapeValue(serverGroupId) + "," + getServerGroupContainerDN();
 
    SearchRequest request = newSearchRequest(dn, BASE_OBJECT, "(objectclass=*)");
    try (ConnectionEntryReader entryReader = getConnection().getConnection().search(request))
    {
      Set<String> result = new HashSet<>();
      if (!entryReader.hasNext())
      {
        return result;
      }
      for (Attribute attr : entryReader.readEntry().getAllAttributes())
      {
        AttributeType attrType = attr.getAttributeDescription().getAttributeType();
        if (attrType.hasName(ServerGroupProperty.MEMBERS.getAttributeName()))
        {
          // We have the members list
          toStrings(result, attr);
          break;
        }
      }
      return result;
    }
    catch (EntryNotFoundException x)
    {
      return new HashSet<>();
    }
    catch (AuthorizationException x)
    {
      throw new ADSContextException(ErrorType.ACCESS_PERMISSION);
    }
    catch (IOException x)
    {
      throw new ADSContextException(ErrorType.ERROR_UNEXPECTED, x);
    }
  }
 
  private void toStrings(Set<String> result, Attribute attr)
  {
    for (ByteString value : attr)
    {
      result.add(value.toString());
    }
  }
 
  /**
   * Returns a set containing the servers that are registered in the ADS.
   *
   * @return a set containing the servers that are registered in the ADS.
   * @throws ADSContextException
   *           if something goes wrong.
   */
  public Set<Map<ServerProperty, Object>> readServerRegistry() throws ADSContextException
  {
    Set<Map<ServerProperty, Object>> result = new HashSet<>();
 
    SearchRequest request = newSearchRequest(getServerContainerDN(), SINGLE_LEVEL, objectClassPresent());
    try (ConnectionEntryReader entryReader = connectionWrapper.getConnection().search(request))
    {
      while (entryReader.hasNext())
      {
        SearchResultEntry sr = entryReader.readEntry();
        Map<ServerProperty, Object> properties = makePropertiesFromServerAttrs(sr);
        Object keyId = properties.get(ServerProperty.INSTANCE_KEY_ID);
        if (keyId != null)
        {
          SearchRequest request2 = newSearchRequest(
              getInstanceKeysContainerDN(), SINGLE_LEVEL, Filter.valueOf("(ds-cfg-key-id=" + keyId + ")"),
              "ds-cfg-public-key-certificate;binary");
          try (ConnectionEntryReader entryReader2 = connectionWrapper.getConnection().search(request2))
          {
            boolean found = false;
            while (entryReader2.hasNext())
            {
              SearchResultEntry certEntry = entryReader2.readEntry();
              Attribute certAttr = certEntry.getAttribute("ds-cfg-public-key-certificate;binary");
              properties.put(ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE, certAttr.firstValue().toByteArray());
              found = true;
            }
            if (!found)
            {
              logger.warn(LocalizableMessage.raw("Could not find public key for " + properties));
            }
          }
          catch (EntryNotFoundException x)
          {
            logger.warn(LocalizableMessage.raw("Could not find public key for " + properties));
          }
        }
        result.add(properties);
      }
      return result;
    }
    catch (EntryNotFoundException x)
    {
      throw new ADSContextException(ErrorType.BROKEN_INSTALL);
    }
    catch (AuthorizationException x)
    {
      throw new ADSContextException(ErrorType.ACCESS_PERMISSION);
    }
    catch (IOException x)
    {
      throw new ADSContextException(ErrorType.ERROR_UNEXPECTED, x);
    }
  }
 
  /**
   * Creates a Server Group in the ADS.
   *
   * @param serverGroupProperties
   *          the properties of the server group to be created.
   * @throws ADSContextException
   *           if something goes wrong.
   */
  private void createServerGroup(Map<ServerGroupProperty, Object> serverGroupProperties) throws ADSContextException
  {
    String dn = makeDNFromServerGroupProperties(serverGroupProperties);
    AddRequest request = newAddRequest(dn)
        .addAttribute("objectclass", "top", "groupOfUniqueNames");
    for (ServerGroupProperty prop : serverGroupProperties.keySet())
    {
      request.addAttribute(makeAttrFromServerGroupProperty(prop, serverGroupProperties.get(prop)));
    }
 
    try
    {
      throwIfNotSuccess(connectionWrapper.getConnection().add(request));
    }
    catch (LdapException x)
    {
      if (x.getResult().getResultCode().equals(ResultCode.ENTRY_ALREADY_EXISTS))
      {
        throw new ADSContextException(ErrorType.ALREADY_REGISTERED);
      }
      throw new ADSContextException(ErrorType.BROKEN_INSTALL, x);
    }
  }
 
  /**
   * Updates the properties of a Server Group in the ADS.
   *
   * @param serverGroupProperties
   *          the new properties of the server group to be updated.
   * @param groupID
   *          The group name.
   * @throws ADSContextException
   *           if something goes wrong.
   */
  private void updateServerGroup(String groupID, Map<ServerGroupProperty, Object> serverGroupProperties)
      throws ADSContextException
  {
    String dn = "cn=" + Rdn.escapeValue(groupID) + "," + getServerGroupContainerDN();
    try
    {
      // Entry renaming ?
      if (serverGroupProperties.containsKey(ServerGroupProperty.UID))
      {
        String newGroupId = serverGroupProperties.get(ServerGroupProperty.UID).toString();
        if (!newGroupId.equals(groupID))
        {
          // Rename to entry
          String newDN = ("cn=" + Rdn.escapeValue(newGroupId) + "," + getServerGroupContainerDN());
          throwIfNotSuccess(connectionWrapper.getConnection().modifyDN(dn, newDN));
          dn = newDN;
        }
 
        // In any case, we remove the "cn" attribute.
        serverGroupProperties.remove(ServerGroupProperty.UID);
      }
      if (serverGroupProperties.isEmpty())
      {
        return;
      }
 
      // Transform 'properties' into 'attributes'
      ModifyRequest request = newModifyRequest(dn);
      for (ServerGroupProperty prop : serverGroupProperties.keySet())
      {
        request.addModification(new Modification(
            REPLACE, makeAttrFromServerGroupProperty(prop, serverGroupProperties.get(prop))));
      }
      throwIfNotSuccess(connectionWrapper.getConnection().modify(request));
    }
    catch (EntryNotFoundException x)
    {
      throw new ADSContextException(ErrorType.NOT_YET_REGISTERED);
    }
    catch (LdapException x)
    {
      if (x.getResult().getResultCode().equals(ResultCode.ENTRY_ALREADY_EXISTS))
      {
        throw new ADSContextException(ErrorType.ALREADY_REGISTERED);
      }
      throw new ADSContextException(ErrorType.ERROR_UNEXPECTED, x);
    }
  }
 
  /**
   * Returns a set containing the server groups that are defined in the ADS.
   *
   * @return a set containing the server groups that are defined in the ADS.
   * @throws ADSContextException
   *           if something goes wrong.
   */
  private Set<Map<ServerGroupProperty, Object>> readServerGroupRegistry() throws ADSContextException
  {
    SearchRequest request = newSearchRequest(getServerGroupContainerDN(), SINGLE_LEVEL, objectClassPresent());
    try (ConnectionEntryReader entryReader = connectionWrapper.getConnection().search(request))
    {
      Set<Map<ServerGroupProperty, Object>> result = new HashSet<>();
      while (entryReader.hasNext())
      {
        SearchResultEntry sr = entryReader.readEntry();
        result.add(makePropertiesFromServerGroupAttrs(sr));
      }
      return result;
    }
    catch (EntryNotFoundException x)
    {
      throw new ADSContextException(ErrorType.BROKEN_INSTALL);
    }
    catch (AuthorizationException x)
    {
      throw new ADSContextException(ErrorType.ACCESS_PERMISSION);
    }
    catch (IOException x)
    {
      throw new ADSContextException(ErrorType.ERROR_UNEXPECTED, x);
    }
  }
 
  /**
   * Returns a set containing the administrators that are defined in the ADS.
   *
   * @return a set containing the administrators that are defined in the ADS.
   * @throws ADSContextException
   *           if something goes wrong.
   */
  public Set<Map<AdministratorProperty, Object>> readAdministratorRegistry() throws ADSContextException
  {
    Set<Map<AdministratorProperty, Object>> result = new HashSet<>();
    SearchRequest request = newSearchRequest(
        getAdministratorContainerDN(), SINGLE_LEVEL, objectClassPresent(),
        "cn", "userpassword", "ds-privilege-name", "description");
    try (ConnectionEntryReader entryReader = connectionWrapper.getConnection().search(request))
    {
      while (entryReader.hasNext())
      {
        SearchResultEntry sr = entryReader.readEntry();
        result.add(makePropertiesFromAdministratorAttrs(sr.getName().rdn(), sr.getAllAttributes()));
      }
    }
    catch (EntryNotFoundException x)
    {
      throw new ADSContextException(ErrorType.BROKEN_INSTALL);
    }
    catch (AuthorizationException x)
    {
      throw new ADSContextException(ErrorType.ACCESS_PERMISSION);
    }
    catch (IOException x)
    {
      throw new ADSContextException(ErrorType.ERROR_UNEXPECTED, x);
    }
 
    return result;
  }
 
  /**
   * Creates the Administration Data in the server. The call to this method
   * assumes that OpenDJ.jar has already been loaded.
   *
   * @param backendName
   *          the backend name which will handle admin information.
   *          <CODE>null</CODE> to use the default backend name for the admin
   *          information.
   * @throws ADSContextException
   *           if something goes wrong.
   */
  public void createAdminData(String backendName) throws ADSContextException
  {
    // Add the administration suffix
    createAdministrationSuffix(backendName);
    createAdminDataContainers();
  }
 
  /** Create container entries. */
  private void createAdminDataContainers() throws ADSContextException
  {
    // Create the DIT below the administration suffix
    if (!isExistingEntry(getAdministrationSuffixDN()))
    {
      createTopContainerEntry();
    }
    if (!isExistingEntry(getAdministratorContainerDN()))
    {
      createAdministratorContainerEntry();
    }
    if (!isExistingEntry(getServerContainerDN()))
    {
      createContainerEntry(getServerContainerDN());
    }
    if (!isExistingEntry(getServerGroupContainerDN()))
    {
      createContainerEntry(getServerGroupContainerDN());
    }
 
    // Add the default "all-servers" group
    if (!isExistingEntry((getAllServerGroupDN())))
    {
      Map<ServerGroupProperty, Object> allServersGroupsMap = new HashMap<>();
      allServersGroupsMap.put(ServerGroupProperty.UID, ALL_SERVERGROUP_NAME);
      createServerGroup(allServersGroupsMap);
    }
 
    // Create the CryptoManager instance key DIT below the administration suffix
    if (!isExistingEntry(getInstanceKeysContainerDN()))
    {
      createContainerEntry(getInstanceKeysContainerDN());
    }
 
    // Create the CryptoManager secret key DIT below the administration suffix
    if (!isExistingEntry(getSecretKeysContainerDN()))
    {
      createContainerEntry(getSecretKeysContainerDN());
    }
  }
 
  /**
   * Removes the administration data.
   *
   * @param removeAdministrators
   *          {@code true} if administrators should be removed. It may not be
   *          possible to remove administrators if the operation is being
   *          performed by one of the administrators because it will cause the
   *          administrator to be disconnected.
   * @throws ADSContextException
   *           if something goes wrong.
   */
  public void removeAdminData(boolean removeAdministrators) throws ADSContextException
  {
    DN[] dns = { getServerContainerDN(), getServerGroupContainerDN(),
      removeAdministrators ? getAdministratorContainerDN() : null };
    try
    {
      for (DN dn : dns)
      {
        if (dn != null)
        {
          if (isExistingEntry(dn))
          {
            DeleteRequest request = newDeleteRequest(dn)
                .addControl(SubtreeDeleteRequestControl.newControl(true));
            connectionWrapper.getConnection().delete(request);
          }
        }
      }
      // Recreate the container entries:
      createAdminDataContainers();
    }
    catch (LdapException x)
    {
      throw new ADSContextException(ErrorType.ERROR_UNEXPECTED, x);
    }
  }
 
  /**
   * Returns <CODE>true</CODE> if the server contains Administration Data and
   * <CODE>false</CODE> otherwise.
   *
   * @return <CODE>true</CODE> if the server contains Administration Data and
   *         <CODE>false</CODE> otherwise.
   * @throws ADSContextException
   *           if something goes wrong.
   */
  public boolean hasAdminData() throws ADSContextException
  {
    DN[] dns = { getAdministratorContainerDN(), getAllServerGroupDN(), getServerContainerDN(),
      getInstanceKeysContainerDN(), getSecretKeysContainerDN() };
    boolean hasAdminData = true;
    for (int i = 0; i < dns.length && hasAdminData; i++)
    {
      hasAdminData = isExistingEntry(dns[i]);
    }
    return hasAdminData;
  }
 
  /**
   * Returns the DN of the administrator for a given UID.
   *
   * @param uid
   *          the UID to be used to generate the DN.
   * @return the DN of the administrator for the given UID:
   */
  public static DN getAdministratorDN(String uid)
  {
    return DN.valueOf("cn=" + Rdn.escapeValue(uid) + "," + getAdministratorContainerDN());
  }
 
  /**
   * Creates an Administrator in the ADS.
   *
   * @param adminProperties
   *          the properties of the administrator to be created.
   * @throws ADSContextException
   *           if something goes wrong.
   */
  public void createAdministrator(Map<AdministratorProperty, Object> adminProperties) throws ADSContextException
  {
    AddRequest request = newAddRequest(getAdministratorDN(getAdministratorUID(adminProperties)));
    addAttrsFromAdministratorProperties(request, adminProperties, true);
 
    try
    {
      throwIfNotSuccess(connectionWrapper.getConnection().add(request));
    }
    catch (AuthorizationException x)
    {
      throw new ADSContextException(ErrorType.ACCESS_PERMISSION);
    }
    catch (LdapException x)
    {
      if (x.getResult().getResultCode().equals(ResultCode.ENTRY_ALREADY_EXISTS))
      {
        throw new ADSContextException(ErrorType.ALREADY_REGISTERED);
      }
      throw new ADSContextException(ErrorType.ERROR_UNEXPECTED, x);
    }
  }
 
  /**
   * Deletes the administrator in the ADS.
   *
   * @param adminProperties
   *          the properties of the administrator to be deleted.
   * @throws ADSContextException
   *           if something goes wrong.
   */
  public void deleteAdministrator(Map<AdministratorProperty, Object> adminProperties) throws ADSContextException
  {
    DN dnCentralAdmin = getAdministratorDN(getAdministratorUID(adminProperties));
    try
    {
      throwIfNotSuccess(connectionWrapper.getConnection().delete(newDeleteRequest(dnCentralAdmin)));
    }
    catch (EntryNotFoundException x)
    {
      throw new ADSContextException(ErrorType.NOT_YET_REGISTERED);
    }
    catch (AuthorizationException x)
    {
      throw new ADSContextException(ErrorType.ACCESS_PERMISSION);
    }
    catch (LdapException x)
    {
      throw new ADSContextException(ErrorType.ERROR_UNEXPECTED, x);
    }
  }
 
  /**
   * Returns the DN of the suffix that contains the administration data.
   *
   * @return the DN of the suffix that contains the administration data.
   */
  public static DN getAdministrationSuffixDN()
  {
    return DN.valueOf("cn=admin data");
  }
 
  /**
   * This method returns the DN of the entry that corresponds to the given host
   * name and installation path.
   *
   * @param hostname
   *          the host name.
   * @param ipath
   *          the installation path.
   * @return the DN of the entry that corresponds to the given host name and
   *         installation path.
   * @throws ADSContextException
   *           if something goes wrong.
   */
  private static DN makeDNFromHostnameAndPath(String hostname, String ipath) throws ADSContextException
  {
    return DN.valueOf("cn=" + Rdn.escapeValue(hostname + "@" + ipath) + "," + getServerContainerDN());
  }
 
  /**
   * This method returns the DN of the entry that corresponds to the given host
   * name port representation.
   *
   * @param serverUniqueId
   *          the host name and port.
   * @return the DN of the entry that corresponds to the given host name and
   *         port.
   * @throws ADSContextException
   *           if something goes wrong.
   */
  private static DN makeDNFromServerUniqueId(String serverUniqueId) throws ADSContextException
  {
    return DN.valueOf("cn=" + Rdn.escapeValue(serverUniqueId) + "," + getServerContainerDN());
  }
 
  /**
   * This method returns the DN of the entry that corresponds to the given
   * server group properties.
   *
   * @param serverGroupProperties
   *          the server group properties
   * @return the DN of the entry that corresponds to the given server group
   *         properties.
   * @throws ADSContextException
   *           if something goes wrong.
   */
  private static String makeDNFromServerGroupProperties(Map<ServerGroupProperty, Object> serverGroupProperties)
      throws ADSContextException
  {
    String serverGroupId = (String) serverGroupProperties.get(ServerGroupProperty.UID);
    if (serverGroupId == null)
    {
      throw new ADSContextException(ErrorType.MISSING_NAME);
    }
    return "cn=" + Rdn.escapeValue(serverGroupId) + "," + getServerGroupContainerDN();
  }
 
  /**
   * This method returns the DN of the entry that corresponds to the given
   * server properties.
   *
   * @param serverProperties
   *          the server properties.
   * @return the DN of the entry that corresponds to the given server
   *         properties.
   * @throws ADSContextException
   *           if something goes wrong.
   */
  private static DN makeDNFromServerProperties(Map<ServerProperty, Object> serverProperties)
      throws ADSContextException
  {
    String serverID = getServerID(serverProperties);
    if (serverID != null)
    {
      return makeDNFromServerUniqueId(serverID);
    }
 
    String hostname = getHostname(serverProperties);
    try
    {
      String ipath = getInstallPath(serverProperties);
      return makeDNFromHostnameAndPath(hostname, ipath);
    }
    catch (ADSContextException ace)
    {
      ServerDescriptor s = ServerDescriptor.createStandalone(serverProperties);
      return makeDNFromServerUniqueId(s.getHostPort(true).toString());
    }
  }
 
  /**
   * Enrich the provided add request with the attributes for some administrator properties.
   *
   * @param adminProperties
   *          the administrator properties.
   * @param passwordRequired
   *          Indicates if the properties should include the password.
   * @throws ADSContextException
   *           if something goes wrong.
   */
  private static void addAttrsFromAdministratorProperties(AddRequest request,
      Map<AdministratorProperty, Object> adminProperties, boolean passwordRequired) throws ADSContextException
  {
    if (passwordRequired)
    {
      request.addAttribute("userPassword", getAdministratorPassword(adminProperties));
    }
    request.addAttribute("objectclass", "top", "person");
    request.addAttribute("sn", GLOBAL_ADMIN_UID);
    if (adminProperties.containsKey(AdministratorProperty.DESCRIPTION))
    {
      request.addAttribute("description", adminProperties.get(AdministratorProperty.DESCRIPTION));
    }
    if (adminProperties.containsKey(AdministratorProperty.PRIVILEGE))
    {
      LinkedList<?> privileges = (LinkedList<?>) adminProperties.get(AdministratorProperty.PRIVILEGE);
      for (Object o : privileges)
      {
        String p = o.toString();
        if (p.startsWith("-"))
        {
          request.removeAttribute("ds-privilege-name", p.substring(1));
        }
        else
        {
          request.addAttribute("ds-privilege-name", p);
        }
      }
    }
    else
    {
      request.addAttribute(addRootPrivileges());
    }
 
    // Add the RootDNs Password policy so the password do not expire.
    request.addAttribute("ds-pwp-password-policy-dn", "cn=Root Password Policy,cn=Password Policies,cn=config");
  }
 
  /**
   * Builds an attribute which contains 'root' privileges.
   *
   * @return The attribute which contains 'root' privileges.
   */
  private static Attribute addRootPrivileges()
  {
    Attribute privilege = new LinkedAttribute("ds-privilege-name");
    privilege.add("bypass-acl");
    privilege.add("modify-acl");
    privilege.add("config-read");
    privilege.add("config-write");
    privilege.add("ldif-import");
    privilege.add("ldif-export");
    privilege.add("backend-backup");
    privilege.add("backend-restore");
    privilege.add("server-shutdown");
    privilege.add("server-restart");
    privilege.add("disconnect-client");
    privilege.add("cancel-request");
    privilege.add("password-reset");
    privilege.add("update-schema");
    privilege.add("privilege-change");
    privilege.add("unindexed-search");
    privilege.add("subentry-write");
    privilege.add("changelog-read");
    return privilege;
  }
 
  /**
   * Returns the attribute for a given server property.
   *
   * @param property
   *          the server property.
   * @param value
   *          the value.
   * @return the attribute for a given server property.
   */
  private static Attribute makeAttrFromServerProperty(ServerProperty property, Object value)
  {
    switch (property)
    {
    case INSTANCE_PUBLIC_KEY_CERTIFICATE:
      // used in separate instance key entry
      return null;
    case GROUPS:
      return new LinkedAttribute(ServerProperty.GROUPS.getAttributeName(), ((Collection<?>) value));
    default:
      return new LinkedAttribute(property.getAttributeName(), value);
    }
  }
 
  /**
   * Returns the attribute for a given server group property.
   *
   * @param property
   *          the server group property.
   * @param value
   *          the value.
   * @return the attribute for a given server group property.
   */
  private static Attribute makeAttrFromServerGroupProperty(ServerGroupProperty property, Object value)
  {
    switch (property)
    {
    case MEMBERS:
      return new LinkedAttribute(ServerGroupProperty.MEMBERS.getAttributeName(), (Collection<?>) value);
    default:
      return new LinkedAttribute(property.getAttributeName(), value);
    }
  }
 
  /**
   * Returns the properties of a server group for some LDAP attributes.
   *
   * @param entry
   *          the LDAP entry.
   * @return the properties of a server group for some LDAP attributes.
   * @throws ADSContextException
   *           if something goes wrong.
   */
  private Map<ServerGroupProperty, Object> makePropertiesFromServerGroupAttrs(SearchResultEntry entry)
      throws ADSContextException
  {
    Map<ServerGroupProperty, Object> result = new HashMap<>();
    for (ServerGroupProperty prop : ServerGroupProperty.values())
    {
      Attribute attr = entry.getAttribute(prop.getAttributeName());
      if (attr == null)
      {
        continue;
      }
      Object value;
 
      if (attr.size() >= 1 && MULTIVALUED_SERVER_GROUP_PROPERTIES.contains(prop))
      {
        Set<String> set = new HashSet<>();
        toStrings(set, attr);
        value = set;
      }
      else
      {
        value = attr.firstValueAsString();
      }
 
      result.put(prop, value);
    }
    return result;
  }
 
  /**
   * Returns the properties of a server for some LDAP attributes.
   *
   * @param entry
   *          the entry.
   * @return the properties of a server for some LDAP attributes.
   * @throws ADSContextException
   *           if something goes wrong.
   */
  private Map<ServerProperty, Object> makePropertiesFromServerAttrs(SearchResultEntry entry) throws ADSContextException
  {
    Map<ServerProperty, Object> result = new HashMap<>();
    for (Attribute attr : entry.getAllAttributes())
    {
      AttributeType attrType = attr.getAttributeDescription().getAttributeType();
      Object value;
 
      ServerProperty prop = null;
      ServerProperty[] props = ServerProperty.values();
      for (int i = 0; i < props.length && prop == null; i++)
      {
        String v = props[i].getAttributeName();
        if (attrType.hasName(v))
        {
          prop = props[i];
        }
      }
      if (prop == null)
      {
        // Do not handle it
      }
      else
      {
        if (attr.size() >= 1 && MULTIVALUED_SERVER_PROPERTIES.contains(prop))
        {
          Set<String> set = new HashSet<>();
          toStrings(set, attr);
          value = set;
        }
        else
        {
          value = attr.firstValueAsString();
        }
 
        result.put(prop, value);
      }
    }
    return result;
  }
 
  /**
   * Returns the properties of an administrator for some rdn and LDAP
   * attributes.
   *
   * @param rdn
   *          the RDN.
   * @param attrs
   *          the LDAP attributes.
   * @return the properties of an administrator for the given rdn and LDAP
   *         attributes.
   * @throws ADSContextException
   *           if something goes wrong.
   */
  private Map<AdministratorProperty, Object> makePropertiesFromAdministratorAttrs(RDN rdn, Iterable<Attribute> attrs)
  {
    Map<AdministratorProperty, Object> result = new HashMap<>();
    result.put(AdministratorProperty.ADMINISTRATOR_DN, rdn + "," + getAdministratorContainerDN());
    for (Attribute attr : attrs)
    {
      AttributeType attrName = attr.getAttributeDescription().getAttributeType();
 
      if (attrName.hasName("cn"))
      {
        result.put(AdministratorProperty.UID, attr.firstValueAsString());
      }
      else if (attrName.hasName("userpassword"))
      {
        result.put(AdministratorProperty.PASSWORD, new String(attr.firstValue().toByteArray()));
      }
      else if (attrName.hasName("description"))
      {
        result.put(AdministratorProperty.DESCRIPTION, attr.firstValueAsString());
      }
      else if (attrName.hasName("ds-privilege-name"))
      {
        LinkedHashSet<String> privileges = new LinkedHashSet<>();
        toStrings(privileges, attr);
        result.put(AdministratorProperty.PRIVILEGE, privileges);
      }
    }
    return result;
  }
 
  /**
   * Returns the parent entry of the server entries.
   *
   * @return the parent entry of the server entries.
   */
  private static DN getServerContainerDN()
  {
    return DN.valueOf("cn=Servers," + getAdministrationSuffixDN());
  }
 
  /**
   * Returns the parent entry of the administrator entries.
   *
   * @return the parent entry of the administrator entries.
   */
  public static DN getAdministratorContainerDN()
  {
    return DN.valueOf("cn=Administrators," + getAdministrationSuffixDN());
  }
 
  /**
   * Returns the parent entry of the server group entries.
   *
   * @return the parent entry of the server group entries.
   */
  private static DN getServerGroupContainerDN()
  {
    return DN.valueOf("cn=Server Groups," + getAdministrationSuffixDN());
  }
 
  /**
   * Returns the all server group entry DN.
   *
   * @return the all server group entry DN.
   */
  private static DN getAllServerGroupDN()
  {
    return DN.valueOf("cn=" + Rdn.escapeValue(ALL_SERVERGROUP_NAME) + "," + getServerGroupContainerDN());
  }
 
  /**
   * Returns the host name for the given properties.
   *
   * @param serverProperties
   *          the server properties.
   * @return the host name for the given properties.
   * @throws ADSContextException
   *           if the host name could not be found or its value is not valid.
   */
  private static String getHostname(Map<ServerProperty, Object> serverProperties) throws ADSContextException
  {
    String result = (String) serverProperties.get(ServerProperty.HOST_NAME);
    if (result == null)
    {
      throw new ADSContextException(ErrorType.MISSING_HOSTNAME);
    }
    else if (result.length() == 0)
    {
      throw new ADSContextException(ErrorType.NOVALID_HOSTNAME);
    }
    return result;
  }
 
  /**
   * Returns the Server ID for the given properties.
   *
   * @param serverProperties
   *          the server properties.
   * @return the server ID for the given properties or null.
   */
  private static String getServerID(Map<ServerProperty, Object> serverProperties)
  {
    String result = (String) serverProperties.get(ServerProperty.ID);
    if (result != null && result.length() == 0)
    {
      result = null;
    }
    return result;
  }
 
  /**
   * Returns the install path for the given properties.
   *
   * @param serverProperties
   *          the server properties.
   * @return the install path for the given properties.
   * @throws ADSContextException
   *           if the install path could not be found or its value is not valid.
   */
  private static String getInstallPath(Map<ServerProperty, Object> serverProperties) throws ADSContextException
  {
    String result = (String) serverProperties.get(ServerProperty.INSTANCE_PATH);
    if (result == null)
    {
      throw new ADSContextException(ErrorType.MISSING_IPATH);
    }
    else if (result.length() == 0)
    {
      throw new ADSContextException(ErrorType.NOVALID_IPATH);
    }
    return result;
  }
 
  /**
   * Returns the Administrator UID for the given properties.
   *
   * @param adminProperties
   *          the server properties.
   * @return the Administrator UID for the given properties.
   * @throws ADSContextException
   *           if the administrator UID could not be found.
   */
  private static String getAdministratorUID(Map<AdministratorProperty, Object> adminProperties)
      throws ADSContextException
  {
    String result = (String) adminProperties.get(AdministratorProperty.UID);
    if (result == null)
    {
      throw new ADSContextException(ErrorType.MISSING_ADMIN_UID);
    }
    return result;
  }
 
  /**
   * Returns the Administrator password for the given properties.
   *
   * @param adminProperties
   *          the server properties.
   * @return the Administrator password for the given properties.
   * @throws ADSContextException
   *           if the administrator password could not be found.
   */
  private static String getAdministratorPassword(Map<AdministratorProperty, Object> adminProperties)
      throws ADSContextException
  {
    String result = (String) adminProperties.get(AdministratorProperty.PASSWORD);
    if (result == null)
    {
      throw new ADSContextException(ErrorType.MISSING_ADMIN_PASSWORD);
    }
    return result;
  }
 
  // LDAP utilities
 
  /**
   * Tells whether an entry with the provided DN exists.
   *
   * @param dn
   *          the DN to check.
   * @return <CODE>true</CODE> if the entry exists and <CODE>false</CODE> if it
   *         does not.
   * @throws ADSContextException
   *           if an error occurred while checking if the entry exists or not.
   */
  private boolean isExistingEntry(DN dn) throws ADSContextException
  {
    SearchRequest request = newSearchRequest(dn, BASE_OBJECT, objectClassPresent(), NO_ATTRIBUTES);
    try (ConnectionEntryReader entryReader = getConnection().getConnection().search(request))
    {
      while (entryReader.hasNext())
      {
        entryReader.readEntry();
        return true;
      }
      return false;
    }
    catch (EntryNotFoundException x)
    {
      return false;
    }
    catch (AuthorizationException x)
    {
      throw new ADSContextException(ErrorType.ACCESS_PERMISSION);
    }
    catch (IOException x)
    {
      throw new ADSContextException(ErrorType.ERROR_UNEXPECTED, x);
    }
  }
 
  /**
   * Creates a container entry with the given dn.
   *
   * @param dn
   *          the entry of the new entry to be created.
   * @throws ADSContextException
   *           if the entry could not be created.
   */
  private void createContainerEntry(DN dn) throws ADSContextException
  {
    createEntry(newAddRequest(dn).addAttribute("objectclass", "top", "ds-cfg-branch"));
  }
 
  /**
   * Creates the administrator container entry.
   *
   * @throws ADSContextException
   *           if the entry could not be created.
   */
  private void createAdministratorContainerEntry() throws ADSContextException
  {
    AddRequest request = newAddRequest(getAdministratorContainerDN())
        .addAttribute("objectclass", "groupofurls")
        .addAttribute("memberURL", "ldap:///" + getAdministratorContainerDN() + "??one?(objectclass=*)")
        .addAttribute("description", "Group of identities which have full access.");
    createEntry(request);
  }
 
  /**
   * Creates the top container entry.
   *
   * @throws ADSContextException
   *           if the entry could not be created.
   */
  private void createTopContainerEntry() throws ADSContextException
  {
    AddRequest request = newAddRequest(getAdministrationSuffixDN())
        .addAttribute("objectclass", "top", "ds-cfg-branch");
    createEntry(request);
  }
 
  /**
   * Creates an entry with the provided add request.
   *
   * @param addRequest
   *          the add request.
   * @throws ADSContextException
   *           if the entry could not be created.
   */
  private void createEntry(AddRequest request) throws ADSContextException
  {
    try
    {
      throwIfNotSuccess(getConnection().getConnection().add(request));
    }
    catch (LdapException e)
    {
      throw new ADSContextException(ErrorType.ERROR_UNEXPECTED, e);
    }
  }
 
  private void throwIfNotSuccess(Result result) throws LdapException
  {
    ResultCode rc = result.getResultCode();
    if (rc.isExceptional())
    {
      throw LdapException.newLdapException(result);
    }
  }
 
  /**
   * Creates the Administration Suffix.
   *
   * @param backendName
   *          the backend name to be used for the Administration Suffix. If this
   *          value is null the default backendName for the Administration
   *          Suffix will be used.
   * @throws ADSContextException
   *           if something goes wrong.
   */
  private void createAdministrationSuffix(String backendName) throws ADSContextException
  {
    ADSContextHelper helper = new ADSContextHelper();
    String ben = backendName;
    if (backendName == null)
    {
      ben = getDefaultBackendName();
    }
    helper.createAdministrationSuffix(connectionWrapper, ben);
  }
 
  /**
   * Returns the default backend name of the administration data.
   *
   * @return the default backend name of the administration data.
   */
  public static String getDefaultBackendName()
  {
    return "adminRoot";
  }
 
  /**
   * Returns the LDIF file of the administration data.
   *
   * @return the LDIF file of the administration data.
   */
  static String getAdminLDIFFile()
  {
    return "config" + File.separator + "admin-backend.ldif";
  }
 
  /** CryptoManager related types, fields, and methods. */
 
  /**
   * Returns the parent entry of the server key entries in ADS.
   *
   * @return the parent entry of the server key entries in ADS.
   */
  static DN getInstanceKeysContainerDN()
  {
    return DN.valueOf("cn=instance keys," + getAdministrationSuffixDN());
  }
 
  /**
   * Returns the parent entry of the secret key entries in ADS.
   *
   * @return the parent entry of the secret key entries in ADS.
   */
  private static DN getSecretKeysContainerDN()
  {
    return DN.valueOf("cn=secret keys," + getAdministrationSuffixDN());
  }
 
  /**
   * Tells whether the provided server is registered in the registry.
   *
   * @param server
   *          the server.
   * @param registry
   *          the registry.
   * @return <CODE>true</CODE> if the server is registered in the registry and
   *         <CODE>false</CODE> otherwise.
   */
  public static boolean isRegistered(ServerDescriptor server, Set<Map<ADSContext.ServerProperty, Object>> registry)
  {
    for (Map<ADSContext.ServerProperty, Object> s : registry)
    {
      ServerDescriptor servInRegistry = ServerDescriptor.createStandalone(s);
      if (servInRegistry.getId().equals(server.getId()))
      {
        return true;
      }
    }
    return false;
  }
 
  /**
   * Register instance key-pair public-key certificate provided in
   * serverProperties: generate a key-id attribute if one is not provided (as
   * expected); add an instance key public-key certificate entry for the key
   * certificate; and associate the certificate entry with the server entry via
   * the key ID attribute.
   *
   * @param serverProperties
   *          Properties of the server being registered to which the instance
   *          key entry belongs.
   * @param serverEntryDn
   *          The server's ADS entry DN.
   * @throws ADSContextException
   *           In case there is a problem registering the instance public key certificate ID
   */
  private void registerInstanceKeyCertificate(Map<ServerProperty, Object> serverProperties, DN serverEntryDn)
      throws ADSContextException
  {
    ADSContextHelper helper = new ADSContextHelper();
    helper.registerInstanceKeyCertificate(connectionWrapper, serverProperties, serverEntryDn);
  }
 
  /**
   * Return the set of valid (i.e., not tagged as compromised) instance key-pair
   * public-key certificate entries in ADS. NOTE: calling this method assumes
   * that all the jar files are present in the classpath.
   *
   * @return The set of valid (i.e., not tagged as compromised) instance
   *         key-pair public-key certificate entries in ADS represented as a Map
   *         from ds-cfg-key-id value to ds-cfg-public-key-certificate;binary
   *         value. Note that the collection might be empty.
   * @throws ADSContextException
   *           in case of problems with the entry search.
   * @see org.opends.server.crypto.CryptoManagerImpl#getTrustedCertificates
   */
  public Map<String, byte[]> getTrustedCertificates() throws ADSContextException
  {
    final DN baseDN = getInstanceKeysContainerDN();
    ADSContextHelper helper = new ADSContextHelper();
    final String FILTER_OC_INSTANCE_KEY = "(objectclass=" + helper.getOcCryptoInstanceKey() + ")";
    final String FILTER_NOT_COMPROMISED = "(!(" + helper.getAttrCryptoKeyCompromisedTime() + "=*))";
    final Filter searchFilter = Filter.valueOf("(&" + FILTER_OC_INSTANCE_KEY + FILTER_NOT_COMPROMISED + ")");
 
    String instanceKeyId = ADSContext.ServerProperty.INSTANCE_KEY_ID.getAttributeName();
    String instanceKeyCertificate =
        ADSContext.ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE.getAttributeName() + ";binary";
    SearchRequest request =
        newSearchRequest(baseDN, SINGLE_LEVEL, searchFilter, instanceKeyId, instanceKeyCertificate);
 
    final Map<String, byte[]> certificateMap = new HashMap<>();
    try (ConnectionEntryReader entryReader = connectionWrapper.getConnection().search(request))
    {
      while (entryReader.hasNext())
      {
        final SearchResultEntry entry = entryReader.readEntry();
        final Attribute keyIDAttr = entry.getAttribute(instanceKeyId);
        final Attribute keyCertAttr = entry.getAttribute(instanceKeyCertificate);
        if (null == keyIDAttr || null == keyCertAttr)
        {
          continue;// schema viol.
        }
        certificateMap.put(keyIDAttr.firstValueAsString(), keyCertAttr.firstValue().toByteArray());
      }
      return certificateMap;
    }
    catch (IOException x)
    {
      throw new ADSContextException(ErrorType.ERROR_UNEXPECTED, x);
    }
  }
 
  /**
   * Merge the contents of this ADSContext with the contents of the provided
   * ADSContext. Note that only the contents of this ADSContext will be updated.
   *
   * @param adsCtx
   *          the other ADSContext to merge the contents with.
   * @throws ADSContextException
   *           if there was an error during the merge.
   */
  public void mergeWithRegistry(ADSContext adsCtx) throws ADSContextException
  {
    try
    {
      mergeAdministrators(adsCtx);
      mergeServerGroups(adsCtx);
      mergeServers(adsCtx);
    }
    catch (ADSContextException adce)
    {
      LocalizableMessage msg = ERR_ADS_MERGE.get(getHostPort(), adsCtx.getHostPort(), adce.getMessageObject());
      throw new ADSContextException(ErrorType.ERROR_MERGING, msg, adce);
    }
  }
 
  /**
   * Merge the administrator contents of this ADSContext with the contents of
   * the provided ADSContext. Note that only the contents of this ADSContext
   * will be updated.
   *
   * @param adsCtx
   *          the other ADSContext to merge the contents with.
   * @throws ADSContextException
   *           if there was an error during the merge.
   */
  private void mergeAdministrators(ADSContext adsCtx) throws ADSContextException
  {
    Set<Map<AdministratorProperty, Object>> admins2 = adsCtx.readAdministratorRegistry();
    SortedSet<String> notDefinedAdmins = new TreeSet<>();
    for (Map<AdministratorProperty, Object> admin2 : admins2)
    {
      String uid = (String) admin2.get(AdministratorProperty.UID);
      if (!isAdministratorAlreadyRegistered(uid))
      {
        notDefinedAdmins.add(uid);
      }
    }
    if (!notDefinedAdmins.isEmpty())
    {
      LocalizableMessage msg = ERR_ADS_ADMINISTRATOR_MERGE.get(
          adsCtx.getHostPort(), getHostPort(),
          joinAsString(Constants.LINE_SEPARATOR, notDefinedAdmins), getHostPort());
      throw new ADSContextException(ErrorType.ERROR_MERGING, msg, null);
    }
  }
 
  /**
   * Merge the groups contents of this ADSContext with the contents of the
   * provided ADSContext. Note that only the contents of this ADSContext will be
   * updated.
   *
   * @param adsCtx
   *          the other ADSContext to merge the contents with.
   * @throws ADSContextException
   *           if there was an error during the merge.
   */
  private void mergeServerGroups(ADSContext adsCtx) throws ADSContextException
  {
    Set<Map<ServerGroupProperty, Object>> serverGroups1 = readServerGroupRegistry();
    Set<Map<ServerGroupProperty, Object>> serverGroups2 = adsCtx.readServerGroupRegistry();
 
    for (Map<ServerGroupProperty, Object> group2 : serverGroups2)
    {
      Map<ServerGroupProperty, Object> group1 = null;
      String uid2 = (String) group2.get(ServerGroupProperty.UID);
      for (Map<ServerGroupProperty, Object> gr : serverGroups1)
      {
        String uid1 = (String) gr.get(ServerGroupProperty.UID);
        if (uid1.equalsIgnoreCase(uid2))
        {
          group1 = gr;
          break;
        }
      }
 
      if (group1 != null)
      {
        // Merge the members, keep the description on this ADS.
        Set<String> member1List = getServerGroupMemberList(uid2);
        if (member1List == null)
        {
          member1List = new HashSet<>();
        }
        Set<String> member2List = adsCtx.getServerGroupMemberList(uid2);
        if (member2List != null && !member2List.isEmpty())
        {
          member1List.addAll(member2List);
          Map<ServerGroupProperty, Object> newProperties = new HashMap<>();
          newProperties.put(ServerGroupProperty.MEMBERS, member1List);
          updateServerGroup(uid2, newProperties);
        }
      }
      else
      {
        createServerGroup(group2);
      }
    }
  }
 
  /**
   * Merge the server contents of this ADSContext with the contents of the
   * provided ADSContext. Note that only the contents of this ADSContext will be
   * updated.
   *
   * @param adsCtx
   *          the other ADSContext to merge the contents with.
   * @throws ADSContextException
   *           if there was an error during the merge.
   */
  private void mergeServers(ADSContext adsCtx) throws ADSContextException
  {
    for (Map<ServerProperty, Object> server2 : adsCtx.readServerRegistry())
    {
      if (!isServerAlreadyRegistered(server2))
      {
        registerServer(server2);
      }
    }
  }
 
  @Override
  public String toString()
  {
    return getClass().getSimpleName() + "(" + connectionWrapper + ")";
  }
}