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

abobrov
12.26.2009 5f8ac08c1a9c27f4f5ab2d871a109ee206853193
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
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE
 * or https://OpenDS.dev.java.net/OpenDS.LICENSE.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE.  If applicable,
 * add the following below this CDDL HEADER, with the fields enclosed
 * by brackets "[]" replaced with your own identifying information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Copyright 2008-2009 Sun Microsystems, Inc.
 */
package org.opends.server.backends.ndb;
import com.mysql.cluster.ndbj.NdbApiException;
import com.mysql.cluster.ndbj.NdbApiPermanentException;
import com.mysql.cluster.ndbj.NdbApiTemporaryException;
import com.mysql.cluster.ndbj.NdbError;
import com.mysql.cluster.ndbj.NdbOperation;
import org.opends.messages.Message;
 
import org.opends.server.api.Backend;
import org.opends.server.core.AddOperation;
import org.opends.server.core.DeleteOperation;
import org.opends.server.core.ModifyOperation;
import org.opends.server.core.ModifyDNOperation;
import org.opends.server.core.SearchOperation;
import org.opends.server.types.*;
import org.opends.server.util.ServerConstants;
 
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
 
import static org.opends.messages.NdbMessages.*;
 
import org.opends.messages.MessageBuilder;
import static org.opends.server.loggers.debug.DebugLogger.*;
import org.opends.server.loggers.debug.DebugTracer;
import static org.opends.server.util.ServerConstants.*;
import org.opends.server.admin.server.ConfigurationChangeListener;
import org.opends.server.admin.std.server.NdbBackendCfg;
import org.opends.server.backends.ndb.OperationContainer.DN2IDSearchCursor;
import org.opends.server.backends.ndb.OperationContainer.SearchCursorResult;
import org.opends.server.config.ConfigException;
 
/**
 * Storage container for LDAP entries.  Each base DN of a NDB backend is given
 * its own entry container.  The entry container is the object that implements
 * the guts of the backend API methods for LDAP operations.
 */
public class EntryContainer
    implements ConfigurationChangeListener<NdbBackendCfg>
{
  /**
   * The tracer object for the debug logger.
   */
  private static final DebugTracer TRACER = getTracer();
 
  /**
   * The backend to which this entry entryContainer belongs.
   */
  private Backend backend;
 
  /**
   * The root container in which this entryContainer belongs.
   */
  private RootContainer rootContainer;
 
  /**
   * The baseDN this entry container is responsible for.
   */
  private DN baseDN;
 
  /**
   * The backend configuration.
   */
  private NdbBackendCfg config;
 
  /**
   * The operation container.
   */
  private OperationContainer dn2id;
 
  /**
   * Cached values from config so they don't have to be retrieved per operation.
   */
  private int deadlockRetryLimit;
 
  private int subtreeDeleteSizeLimit;
 
  private int subtreeDeleteBatchSize;
 
  private String databasePrefix;
 
  /**
   * A read write lock to handle schema changes and bulk changes.
   */
  private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
  final Lock sharedLock = lock.readLock();
  final Lock exclusiveLock = lock.writeLock();
 
  /**
   * Create a new entry entryContainer object.
   *
   * @param baseDN  The baseDN this entry container will be responsible for
   *                storing on disk.
   * @param databasePrefix The prefix to use in the database names used by
   *                       this entry container.
   * @param backend A reference to the NDB backend that is creating this entry
   *                container.
   * @param config The configuration of the NDB backend.
   * @param rootContainer The root container this entry container is in.
   * @throws ConfigException if a configuration related error occurs.
   */
  public EntryContainer(DN baseDN, String databasePrefix, Backend backend,
                        NdbBackendCfg config, RootContainer rootContainer)
      throws ConfigException
  {
    this.backend = backend;
    this.baseDN = baseDN;
    this.config = config;
    this.rootContainer = rootContainer;
 
    StringBuilder builder = new StringBuilder(databasePrefix.length());
    for (int i = 0; i < databasePrefix.length(); i++)
    {
      char ch = databasePrefix.charAt(i);
      if (Character.isLetterOrDigit(ch))
      {
        builder.append(ch);
      }
      else
      {
        builder.append('_');
      }
    }
    this.databasePrefix = builder.toString();
 
    this.deadlockRetryLimit = config.getDeadlockRetryLimit();
 
    config.addNdbChangeListener(this);
  }
 
  /**
   * Opens the entryContainer for reading and writing.
   *
   * @throws NdbApiException If an error occurs in the NDB database.
   * @throws ConfigException if a configuration related error occurs.
   */
  public void open()
      throws NdbApiException, ConfigException
  {
    try
    {
      dn2id = new OperationContainer(BackendImpl.DN2ID_TABLE, this);
    }
    catch (NdbApiException de)
    {
      if (debugEnabled())
      {
        TRACER.debugCaught(DebugLogLevel.ERROR, de);
      }
      close();
      throw de;
    }
  }
 
  /**
   * Closes the entry entryContainer.
   *
   * @throws NdbApiException If an error occurs in the NDB database.
   */
  public void close()
      throws NdbApiException
  {
    config.removeNdbChangeListener(this);
 
    rootContainer = null;
    backend = null;
    config = null;
    dn2id = null;
  }
 
  /**
   * Retrieves a reference to the root container in which this entry container
   * exists.
   *
   * @return  A reference to the root container in which this entry container
   *          exists.
   */
  public RootContainer getRootContainer()
  {
    return rootContainer;
  }
 
  /**
   * Get the DN database used by this entry entryContainer. The entryContainer
   * must have been opened.
   *
   * @return The DN database.
   */
  public OperationContainer getDN2ID()
  {
    return dn2id;
  }
 
  /**
   * Processes the specified search in this entryContainer.
   * Matching entries should be provided back to the core server using the
   * <CODE>SearchOperation.returnEntry</CODE> method.
   *
   * @param searchOperation The search operation to be processed.
   * @throws DirectoryException If a problem occurs while processing
   *         the search.
   * @throws CanceledOperationException If operation is canceled
   *         while in progress.
   * @throws NdbApiException If an error occurs in the NDB database.
   * @throws NDBException If an error occurs in the NDB backend.
   */
  public void search(SearchOperation searchOperation)
       throws CanceledOperationException, DirectoryException,
       NdbApiException, NDBException
  {
    DN baseDN = searchOperation.getBaseDN();
    SearchScope searchScope = searchOperation.getScope();
 
    AbstractTransaction txn = new AbstractTransaction(rootContainer);
 
    int txnRetries = 0;
    boolean completed = false;
    while (!completed) {
      try {
        // Handle base-object search first.
        if (searchScope == SearchScope.BASE_OBJECT) {
          // Fetch the base entry.
          Entry baseEntry = dn2id.get(txn, baseDN,
            NdbOperation.LockMode.LM_CommittedRead);
 
          // The base entry must exist for a successful result.
          if (baseEntry == null) {
            // Check for referral entries above the base entry.
            targetEntryReferrals(txn, baseDN, searchScope);
 
            Message message =
              ERR_NDB_SEARCH_NO_SUCH_OBJECT.get(baseDN.toString());
            DN matchedDN = getMatchedDN(txn, baseDN);
            throw new DirectoryException(ResultCode.NO_SUCH_OBJECT,
              message, matchedDN, null);
          }
 
          if (!isManageDsaITOperation(searchOperation)) {
            checkTargetForReferral(baseEntry, searchOperation.getScope());
          }
 
          if (searchOperation.getFilter().matchesEntry(baseEntry)) {
            searchOperation.returnEntry(baseEntry, null);
          }
 
          completed = true;
          return;
        }
 
        IndexFilter indexFilter = new IndexFilter(txn, this, searchOperation);
        if (indexFilter.evaluate()) {
          searchIndexed(searchOperation, indexFilter);
          completed = true;
        } else {
          DN2IDSearchCursor cursor = dn2id.getSearchCursor(txn, baseDN);
          searchNotIndexed(searchOperation, cursor);
          completed = true;
        }
      } catch (NdbApiTemporaryException databaseException) {
        if (txnRetries < BackendImpl.TXN_RETRY_LIMIT) {
          txnRetries++;
          continue;
        }
        throw databaseException;
      } finally {
        if (txn != null) {
          txn.close();
        }
      }
    }
  }
 
  /**
   * We were able to obtain a set of candidate entries for the
   * search from the indexes.
   */
  private void searchIndexed(SearchOperation searchOperation,
    IndexFilter indexFilter)
       throws CanceledOperationException, NdbApiException,
       DirectoryException, NDBException
  {
    DN baseDN = searchOperation.getBaseDN();
    SearchScope searchScope = searchOperation.getScope();
    boolean manageDsaIT = isManageDsaITOperation(searchOperation);
 
    AbstractTransaction txn = new AbstractTransaction(rootContainer);
    try {
      // Fetch the base entry.
      Entry baseEntry = null;
      baseEntry = dn2id.get(txn, baseDN, NdbOperation.LockMode.LM_Read);
 
      // The base entry must exist for a successful result.
      if (baseEntry == null) {
        // Check for referral entries above the base entry.
        targetEntryReferrals(txn, baseDN, searchScope);
 
        Message message = ERR_NDB_SEARCH_NO_SUCH_OBJECT.get(baseDN.toString());
        DN matchedDN = getMatchedDN(txn, baseDN);
        throw new DirectoryException(ResultCode.NO_SUCH_OBJECT,
          message, matchedDN, null);
      }
 
      if (!manageDsaIT) {
        checkTargetForReferral(baseEntry, searchScope);
      }
 
      /*
       * The base entry is only included for whole subtree search.
       */
      if (searchScope == SearchScope.WHOLE_SUBTREE) {
        if (searchOperation.getFilter().matchesEntry(baseEntry)) {
          searchOperation.returnEntry(baseEntry, null);
        }
      }
 
      int lookthroughCount = 0;
      int lookthroughLimit =
        searchOperation.getClientConnection().getLookthroughLimit();
 
      indexFilter.scan();
      try {
        long eid = indexFilter.getNext();
 
        while (eid != 0) {
          if (lookthroughLimit > 0 && lookthroughCount > lookthroughLimit) {
            //Lookthrough limit exceeded
            searchOperation.setResultCode(ResultCode.ADMIN_LIMIT_EXCEEDED);
            searchOperation.appendErrorMessage(
              NOTE_NDB_LOOKTHROUGH_LIMIT_EXCEEDED.get(lookthroughLimit));
            return;
          }
 
          // Fetch the candidate entry from the database.
          Entry entry = null;
          AbstractTransaction subTxn = new AbstractTransaction(rootContainer);
          try {
            entry = dn2id.get(subTxn, eid, NdbOperation.LockMode.LM_Read);
          } finally {
            if (subTxn != null) {
              subTxn.close();
            }
          }
 
          // We have found a subordinate entry.
          DN dn = entry.getDN();
 
          boolean isInScope = false;
          if (searchScope == SearchScope.SINGLE_LEVEL) {
            // Check if this entry is an immediate child.
            if ((dn.getNumComponents() ==
              baseDN.getNumComponents() + 1) &&
              dn.isDescendantOf(baseDN)) {
              isInScope = true;
            }
          } else if (searchScope == SearchScope.WHOLE_SUBTREE) {
            if (dn.isDescendantOf(baseDN)) {
              isInScope = true;
            }
          } else if (searchScope == SearchScope.SUBORDINATE_SUBTREE) {
            if ((dn.getNumComponents() >
              baseDN.getNumComponents()) &&
              dn.isDescendantOf(baseDN)) {
              isInScope = true;
            }
          }
 
          if (isInScope) {
            // Process the candidate entry.
            if (entry != null) {
              lookthroughCount++;
              if (manageDsaIT || !entry.isReferral()) {
                // Filter the entry.
                if (searchOperation.getFilter().matchesEntry(entry)) {
                  if (!searchOperation.returnEntry(entry, null)) {
                    // We have been told to discontinue processing of the
                    // search. This could be due to size limit exceeded or
                    // operation cancelled.
                    return;
                  }
                }
              } else {
                if (entry.isReferral()) {
                  try {
                    checkTargetForReferral(entry, searchScope);
                  } catch (DirectoryException refException) {
                    if (refException.getResultCode() == ResultCode.REFERRAL) {
                      SearchResultReference reference =
                        new SearchResultReference(
                        refException.getReferralURLs());
                      if (!searchOperation.returnReference(dn, reference)) {
                        // We have been told to discontinue processing of the
                        // search. This could be due to size limit exceeded or
                        // operation cancelled.
                        return;
                      }
                    } else {
                      throw refException;
                    }
                  }
                }
              }
            }
          }
 
          searchOperation.checkIfCanceled(false);
 
          // Move to the next record.
          eid = indexFilter.getNext();
        }
      } finally {
        indexFilter.close();
      }
    } finally {
      if (txn != null) {
        txn.close();
      }
    }
  }
 
  /**
   * We were not able to obtain a set of candidate entries for the
   * search from the indexes.
   */
  private void searchNotIndexed(SearchOperation searchOperation,
    DN2IDSearchCursor cursor)
       throws CanceledOperationException, NdbApiException,
       DirectoryException, NDBException
  {
    DN baseDN = searchOperation.getBaseDN();
    SearchScope searchScope = searchOperation.getScope();
    boolean manageDsaIT = isManageDsaITOperation(searchOperation);
 
    AbstractTransaction txn = new AbstractTransaction(rootContainer);
    try {
      // Fetch the base entry.
      Entry baseEntry = null;
      baseEntry = dn2id.get(txn, baseDN, NdbOperation.LockMode.LM_Read);
 
      // The base entry must exist for a successful result.
      if (baseEntry == null) {
        // Check for referral entries above the base entry.
        targetEntryReferrals(txn, baseDN, searchScope);
 
        Message message = ERR_NDB_SEARCH_NO_SUCH_OBJECT.get(baseDN.toString());
        DN matchedDN = getMatchedDN(txn, baseDN);
        throw new DirectoryException(ResultCode.NO_SUCH_OBJECT,
          message, matchedDN, null);
      }
 
      if (!manageDsaIT) {
        checkTargetForReferral(baseEntry, searchScope);
      }
 
      /*
       * The base entry is only included for whole subtree search.
       */
      if (searchScope == SearchScope.WHOLE_SUBTREE) {
        if (searchOperation.getFilter().matchesEntry(baseEntry)) {
          searchOperation.returnEntry(baseEntry, null);
        }
      }
 
      int lookthroughCount = 0;
      int lookthroughLimit =
        searchOperation.getClientConnection().getLookthroughLimit();
 
      cursor.open();
      try {
        SearchCursorResult result = cursor.getNext();
 
        while (result != null) {
          if (lookthroughLimit > 0 && lookthroughCount > lookthroughLimit) {
            //Lookthrough limit exceeded
            searchOperation.setResultCode(ResultCode.ADMIN_LIMIT_EXCEEDED);
            searchOperation.appendErrorMessage(
              NOTE_NDB_LOOKTHROUGH_LIMIT_EXCEEDED.get(lookthroughLimit));
            return;
          }
 
          // We have found a subordinate entry.
          DN dn = DN.decode(result.dn);
 
          boolean isInScope = true;
          if (searchScope == SearchScope.SINGLE_LEVEL) {
            // Check if this entry is an immediate child.
            if ((dn.getNumComponents() !=
              baseDN.getNumComponents() + 1)) {
              isInScope = false;
            }
          }
 
          if (isInScope) {
            // Fetch the candidate entry from the database.
            Entry entry = null;
            AbstractTransaction subTxn = new AbstractTransaction(rootContainer);
            try {
              entry = dn2id.get(subTxn, dn, NdbOperation.LockMode.LM_Read);
            } finally {
              if (subTxn != null) {
                subTxn.close();
              }
            }
            // Process the candidate entry.
            if (entry != null) {
              lookthroughCount++;
              if (manageDsaIT || !entry.isReferral()) {
                // Filter the entry.
                if (searchOperation.getFilter().matchesEntry(entry)) {
                  if (!searchOperation.returnEntry(entry, null)) {
                    // We have been told to discontinue processing of the
                    // search. This could be due to size limit exceeded or
                    // operation cancelled.
                    return;
                  }
                }
              } else {
                if (entry.isReferral()) {
                  try {
                    checkTargetForReferral(entry, searchScope);
                  } catch (DirectoryException refException) {
                    if (refException.getResultCode() == ResultCode.REFERRAL) {
                      SearchResultReference reference =
                        new SearchResultReference(
                        refException.getReferralURLs());
                      if (!searchOperation.returnReference(dn, reference)) {
                        // We have been told to discontinue processing of the
                        // search. This could be due to size limit exceeded or
                        // operation cancelled.
                        return;
                      }
                    } else {
                      throw refException;
                    }
                  }
                }
              }
            }
          }
 
          searchOperation.checkIfCanceled(false);
 
          // Move to the next record.
          result = cursor.getNext();
        }
      } finally {
        cursor.close();
      }
    } finally {
      if (txn != null) {
        txn.close();
      }
    }
  }
 
  /**
   * Adds the provided entry to this database.  This method must ensure that the
   * entry is appropriate for the database and that no entry already exists with
   * the same DN.  The caller must hold a write lock on the DN of the provided
   * entry.
   *
   * @param entry        The entry to add to this database.
   * @param addOperation The add operation with which the new entry is
   *                     associated.  This may be <CODE>null</CODE> for adds
   *                     performed internally.
   * @param txn          Abstract transaction for this operation.
   * @throws DirectoryException If a problem occurs while trying to add the
   *                            entry.
   * @throws CanceledOperationException If operation is canceled
   *         while in progress.
   * @throws NdbApiException If an error occurs in the NDB database.
   * @throws NDBException If an error occurs in the NDB backend.
   */
  public void addEntry(Entry entry, AddOperation addOperation,
    AbstractTransaction txn)
      throws CanceledOperationException, NdbApiException,
      DirectoryException, NDBException
  {
    TransactedOperation operation = new AddEntryTransaction(entry);
    invokeTransactedOperation(txn, operation, addOperation, true, false);
  }
 
  /**
   * Adds the provided entry to this database.  This method must ensure that the
   * entry is appropriate for the database and that no entry already exists with
   * the same DN.  The caller must hold a write lock on the DN of the provided
   * entry.
   *
   * @param entry        The entry to add to this database.
   * @param addOperation The add operation with which the new entry is
   *                     associated.  This may be <CODE>null</CODE> for adds
   *                     performed internally.
   * @param txn          Abstract transaction for this operation.
   * @throws DirectoryException If a problem occurs while trying to add the
   *                            entry.
   * @throws CanceledOperationException If operation is canceled
   *         while in progress.
   * @throws NdbApiException If an error occurs in the NDB database.
   * @throws NDBException If an error occurs in the NDB backend.
   */
  public void addEntryNoCommit(Entry entry, AddOperation addOperation,
    AbstractTransaction txn)
      throws CanceledOperationException, NdbApiException,
      DirectoryException, NDBException
  {
    TransactedOperation operation = new AddEntryTransaction(entry);
    invokeTransactedOperation(txn, operation, addOperation, false, false);
  }
 
  /**
   * This method is common to all operations invoked under a database
   * transaction. It retries the operation if the transaction is
   * aborted due to a deadlock condition, up to a configured maximum
   * number of retries.
   *
   * @param operation An object implementing the TransactedOperation interface.
   * @throws NdbApiException If an error occurs in the NDB database.
   * @throws DirectoryException If a Directory Server error occurs.
   * @throws NDBException If an error occurs in the NDB backend.
   */
  private void invokeTransactedOperation(AbstractTransaction txn,
    TransactedOperation operation, Operation ldapOperation,
    boolean commit, boolean locked)
      throws CanceledOperationException, NdbApiException,
      DirectoryException, NDBException
  {
    // Attempt the operation under a transaction until it fails or completes.
    int txnRetries = 0;
    boolean completed = false;
 
    while (!completed)
    {
      try
      {
        // Invoke the operation.
        operation.invokeOperation(txn);
 
        // One last check before committing.
        if (ldapOperation != null) {
          ldapOperation.checkIfCanceled(true);
        }
 
        // Commit the transaction.
        if (commit) {
          txn.commit();
        }
        completed = true;
      }
      catch (NdbApiTemporaryException databaseException)
      {
        if (!locked) {
          if (txnRetries < BackendImpl.TXN_RETRY_LIMIT) {
            if (txn != null) {
              txn.close();
            }
            txnRetries++;
            continue;
          }
        }
        if (debugEnabled()) {
          TRACER.debugCaught(DebugLogLevel.ERROR,
            databaseException);
        }
        throw databaseException;
      }
      catch (NdbApiPermanentException databaseException)
      {
        throw databaseException;
      }
      catch (DirectoryException directoryException)
      {
        throw directoryException;
      }
      catch (NDBException NDBException)
      {
        throw NDBException;
      }
      catch (Exception e)
      {
        Message message = ERR_NDB_UNCHECKED_EXCEPTION.get();
        throw new NDBException(message, e);
      }
      finally {
        if (commit) {
          if (txn != null) {
            txn.close();
          }
        }
      }
    }
 
    // Do any actions necessary after successful commit,
    // usually to update the entry cache.
    operation.postCommitAction();
  }
 
  /**
   * This interface represents any kind of operation on the database
   * that must be performed under a transaction. A class which implements
   * this interface does not need to be concerned with creating the
   * transaction nor retrying the transaction after deadlock.
   */
  private interface TransactedOperation
  {
    /**
     * Invoke the operation under the given transaction.
     *
     * @param txn The transaction to be used to perform the operation.
     * @throws NdbApiException If an error occurs in the NDB database.
     * @throws DirectoryException If a Directory Server error occurs.
     * @throws NDBException If an error occurs in the NDB backend.
     */
    public abstract void invokeOperation(AbstractTransaction txn)
        throws NdbApiException, DirectoryException,
        CanceledOperationException, NDBException;
 
    /**
     * This method is called after the transaction has successfully
     * committed.
     */
    public abstract void postCommitAction();
  }
 
  /**
   * This inner class implements the Add Entry operation through
   * the TransactedOperation interface.
   */
  private class AddEntryTransaction implements TransactedOperation
  {
    /**
     * The entry to be added.
     */
    private Entry entry;
 
    /**
     * The DN of the superior entry of the entry to be added.  This can be
     * null if the entry to be added is a base entry.
     */
    DN parentDN;
 
    /**
     * The ID of the entry once it has been assigned.
     */
    long entryID;
 
    /**
     * Create a new Add Entry NdbTransaction.
     * @param entry The entry to be added.
     */
    public AddEntryTransaction(Entry entry)
    {
      this.entry = entry;
      this.parentDN = getParentWithinBase(entry.getDN());
    }
 
    /**
     * Invoke the operation under the given transaction.
     *
     * @param txn The transaction to be used to perform the operation.
     * @throws NdbApiException If an error occurs in the NDB database.
     * @throws DirectoryException If a Directory Server error occurs.
     * @throws NDBException If an error occurs in the NDB backend.
     */
    public void invokeOperation(AbstractTransaction txn)
        throws NdbApiException, DirectoryException, NDBException
    {
      // Check that the parent entry exists.
      if (parentDN != null) {
        // Check for referral entries above the target.
        targetEntryReferrals(txn, entry.getDN(), null);
        long parentID = dn2id.getID(txn, parentDN,
          NdbOperation.LockMode.LM_Read);
        if (parentID == 0) {
          Message message = ERR_NDB_ADD_NO_SUCH_OBJECT.get(
                  entry.getDN().toString());
          DN matchedDN = getMatchedDN(txn, baseDN);
          throw new DirectoryException(ResultCode.NO_SUCH_OBJECT,
              message, matchedDN, null);
        }
      }
 
      // First time through, assign the next entryID.
      if (entryID == 0)
      {
        entryID = rootContainer.getNextEntryID(txn.getNdb());
      }
 
      // Insert.
      try {
        dn2id.insert(txn, entry.getDN(), entryID, entry);
        txn.execute();
      } catch (NdbApiException ne) {
        if (ne.getErrorObj().getClassification() ==
          NdbError.Classification.ConstraintViolation)
        {
          Message message =
            ERR_NDB_ADD_ENTRY_ALREADY_EXISTS.get(entry.getDN().toString());
          throw new DirectoryException(ResultCode.ENTRY_ALREADY_EXISTS,
            message);
        } else {
          throw ne;
        }
      }
    }
 
    /**
     * This method is called after the transaction has successfully
     * committed.
     */
    public void postCommitAction()
    {
 
    }
  }
 
  /**
   * Removes the specified entry from this database.  This method must ensure
   * that the entry exists and that it does not have any subordinate entries
   * (unless the database supports a subtree delete operation and the client
   * included the appropriate information in the request).
   * The caller must hold a write lock on the provided entry DN.
   *
   * @param entryDN         The DN of the entry to remove from this database.
   * @param entry           The entry to delete.
   * @param deleteOperation The delete operation with which this action is
   *                        associated.  This may be <CODE>null</CODE> for
   *                        deletes performed internally.
   * @param txn             Abstract transaction for this operation.
   * @throws DirectoryException If a problem occurs while trying to remove the
   *                            entry.
   * @throws CanceledOperationException If operation is canceled
   *         while in progress.
   * @throws NdbApiException If an error occurs in the NDB database.
   * @throws NDBException If an error occurs in the NDB backend.
   */
  public void deleteEntry(DN entryDN, Entry entry,
    DeleteOperation deleteOperation, AbstractTransaction txn)
    throws CanceledOperationException, DirectoryException,
    NdbApiException, NDBException
  {
    DeleteEntryTransaction operation =
        new DeleteEntryTransaction(entryDN, entry, deleteOperation);
 
    boolean isComplete = false;
 
    while(!isComplete)
    {
      invokeTransactedOperation(txn, operation, deleteOperation, true, true);
 
      if (operation.adminSizeLimitExceeded())
      {
        Message message = NOTE_NDB_SUBTREE_DELETE_SIZE_LIMIT_EXCEEDED.get(
                operation.getDeletedEntryCount());
        throw new DirectoryException(
          ResultCode.ADMIN_LIMIT_EXCEEDED,
          message);
      }
      if(operation.batchSizeExceeded())
      {
        operation.resetBatchSize();
        continue;
      }
      isComplete = true;
      Message message =
          NOTE_NDB_DELETED_ENTRY_COUNT.get(operation.getDeletedEntryCount());
      MessageBuilder errorMessage = new MessageBuilder();
      errorMessage.append(message);
      deleteOperation.setErrorMessage(errorMessage);
    }
  }
 
  /**
   * Removes the specified entry from this database.  This method must ensure
   * that the entry exists and that it does not have any subordinate entries
   * (unless the database supports a subtree delete operation and the client
   * included the appropriate information in the request).
   * The caller must hold a write lock on the provided entry DN.
   *
   * @param entryDN         The DN of the entry to remove from this database.
   * @param entry           The entry to delete.
   * @param deleteOperation The delete operation with which this action is
   *                        associated.  This may be <CODE>null</CODE> for
   *                        deletes performed internally.
   * @param txn             Abstract transaction for this operation.
   * @throws DirectoryException If a problem occurs while trying to remove the
   *                            entry.
   * @throws CanceledOperationException If operation is canceled
   *         while in progress.
   * @throws NdbApiException If an error occurs in the NDB database.
   * @throws NDBException If an error occurs in the NDB backend.
   */
  public void deleteEntryNoCommit(DN entryDN, Entry entry,
    DeleteOperation deleteOperation, AbstractTransaction txn)
    throws CanceledOperationException, DirectoryException,
    NdbApiException, NDBException
  {
    DeleteEntryTransaction operation =
        new DeleteEntryTransaction(entryDN, entry, deleteOperation);
 
    boolean isComplete = false;
 
    while(!isComplete)
    {
      invokeTransactedOperation(txn, operation, deleteOperation, false, true);
 
      if (operation.adminSizeLimitExceeded())
      {
        Message message = NOTE_NDB_SUBTREE_DELETE_SIZE_LIMIT_EXCEEDED.get(
                operation.getDeletedEntryCount());
        throw new DirectoryException(
          ResultCode.ADMIN_LIMIT_EXCEEDED,
          message);
      }
      if(operation.batchSizeExceeded())
      {
        operation.resetBatchSize();
        continue;
      }
      isComplete = true;
      Message message =
          NOTE_NDB_DELETED_ENTRY_COUNT.get(operation.getDeletedEntryCount());
      MessageBuilder errorMessage = new MessageBuilder();
      errorMessage.append(message);
      deleteOperation.setErrorMessage(errorMessage);
    }
  }
 
  /**
   * Delete a leaf entry.
   * The caller must be sure that the entry is indeed a leaf.
   *
   * @param txn    The abstract transaction.
   * @param leafDN The DN of the leaf entry to be deleted.
   * @param leafID The ID of the leaf entry.
   * @throws NdbApiException If an error occurs in the NDB database.
   * @throws DirectoryException If a Directory Server error occurs.
   * @throws NDBException If an error occurs in the NDB backend.
   */
  private void deleteLeaf(AbstractTransaction txn,
                          DN leafDN,
                          long leafID,
                          DeleteOperation operation)
      throws NdbApiException, DirectoryException, NDBException
  {
    Entry entry = dn2id.get(txn, leafDN, NdbOperation.LockMode.LM_Exclusive);
 
    // Check that the entry exists.
    if (entry == null)
    {
      Message msg = ERR_NDB_MISSING_ID2ENTRY_RECORD.get(Long.toString(leafID));
      throw new NDBException(msg);
    }
 
    if (!isManageDsaITOperation(operation))
    {
      checkTargetForReferral(entry, null);
    }
 
    // Remove from dn2id.
    if (!dn2id.remove(txn, entry))
    {
      Message msg = ERR_NDB_MISSING_ID2ENTRY_RECORD.get(Long.toString(leafID));
      throw new NDBException(msg);
    }
  }
 
  /**
   * Delete the target entry of a delete operation, with appropriate handling
   * of referral entries. The caller must be sure that the entry is indeed a
   * leaf.
   *
   * @param txn    The abstract transaction.
   * @param leafDN The DN of the target entry to be deleted.
   * @throws NdbApiException If an error occurs in the NDB database.
   * @throws DirectoryException If a Directory Server error occurs.
   * @throws NDBException If an error occurs in the NDB backend.
   */
  private void deleteTarget(AbstractTransaction txn,
                            DN leafDN, Entry entry,
                            DeleteOperation operation)
      throws NdbApiException, DirectoryException, NDBException
  {
    // Check that the entry exists.
    if (entry == null)
    {
      Message message = ERR_NDB_DELETE_NO_SUCH_OBJECT.get(leafDN.toString());
      DN matchedDN = getMatchedDN(txn, baseDN);
      throw new DirectoryException(ResultCode.NO_SUCH_OBJECT,
          message, matchedDN, null);
    }
 
    if (!isManageDsaITOperation(operation))
    {
      checkTargetForReferral(entry, null);
    }
 
    // Remove from dn2id.
    if (!dn2id.remove(txn, entry))
    {
      Message msg = ERR_NDB_MISSING_DN2ID_RECORD.get(leafDN.toString());
      throw new NDBException(msg);
    }
  }
 
  /**
   * This inner class implements the Delete Entry operation through
   * the TransactedOperation interface.
   */
  private class DeleteEntryTransaction implements TransactedOperation
  {
    /**
     * The DN of the entry or subtree to be deleted.
     */
    private DN entryDN;
 
    /**
     * The entry itself.
     */
    private Entry entry;
 
    /**
     * The Delete operation.
     */
    private DeleteOperation deleteOperation;
 
    /**
     * A list of the DNs of all entries deleted by this operation in a batch.
     * The subtree delete control can cause multiple entries to be deleted.
     */
    private ArrayList<DN> deletedDNList;
 
 
    /**
     * Indicates whether the subtree delete size limit has been exceeded.
     */
    private boolean adminSizeLimitExceeded = false;
 
 
    /**
     * Indicates whether the subtree delete batch size has been exceeded.
     */
    private boolean batchSizeExceeded = false;
 
 
    /**
     * Indicates the count of deleted DNs in the Delete Operation.
     */
    private int countDeletedDN;
 
    /**
     * Create a new Delete Entry NdbTransaction.
     * @param entryDN The entry or subtree to be deleted.
     * @param deleteOperation The Delete operation.
     */
    public DeleteEntryTransaction(DN entryDN, Entry entry,
      DeleteOperation deleteOperation)
    {
      this.entryDN = entryDN;
      this.entry = entry;
      this.deleteOperation = deleteOperation;
      deletedDNList = new ArrayList<DN>();
    }
 
    /**
     * Determine whether the subtree delete size limit has been exceeded.
     * @return true if the size limit has been exceeded.
     */
    public boolean adminSizeLimitExceeded()
    {
      return adminSizeLimitExceeded;
    }
 
    /**
     * Determine whether the subtree delete batch size has been exceeded.
     * @return true if the batch size has been exceeded.
     */
    public boolean batchSizeExceeded()
    {
      return batchSizeExceeded;
    }
 
    /**
     * Resets the batchSizeExceeded parameter to reuse the object
     * for multiple batches.
     */
    public void resetBatchSize()
    {
      batchSizeExceeded=false;
      deletedDNList.clear();
    }
 
    /**
     * Get the number of entries deleted during the operation.
     * @return The number of entries deleted.
     */
    public int getDeletedEntryCount()
    {
      return countDeletedDN;
    }
 
    /**
     * Invoke the operation under the given transaction.
     *
     * @param txn The transaction to be used to perform the operation.
     * @throws NdbApiException If an error occurs in the NDB database.
     * @throws DirectoryException If a Directory Server error occurs.
     * @throws NDBException If an error occurs in the NDB backend.
     */
    public void invokeOperation(AbstractTransaction txn)
        throws CanceledOperationException, NdbApiException,
        DirectoryException, NDBException
    {
      // Check for referral entries above the target entry.
      targetEntryReferrals(txn, entryDN, null);
 
      // Determine whether this is a subtree delete.
      int adminSizeLimit = subtreeDeleteSizeLimit;
      int deleteBatchSize = subtreeDeleteBatchSize;
      boolean isSubtreeDelete = false;
      List<Control> controls = deleteOperation.getRequestControls();
      if (controls != null)
      {
        for (Control control : controls)
        {
          if (control.getOID().equals(OID_SUBTREE_DELETE_CONTROL))
          {
            isSubtreeDelete = true;
          }
        }
      }
 
      if (dn2id.hasSubordinates(txn, entryDN) && !isSubtreeDelete) {
        // The subtree delete control was not specified and
        // the target entry is not a leaf.
        Message message =
          ERR_NDB_DELETE_NOT_ALLOWED_ON_NONLEAF.get(entryDN.toString());
        throw new DirectoryException(ResultCode.NOT_ALLOWED_ON_NONLEAF,
          message);
      }
 
      if (isSubtreeDelete) {
        AbstractTransaction cursorTxn =
          new AbstractTransaction(rootContainer);
        DN2IDSearchCursor cursor = dn2id.getSearchCursor(cursorTxn, entryDN);
        cursor.open();
        try {
          SearchCursorResult result = cursor.getNext();
 
          while (result != null) {
            // We have found a subordinate entry.
            if (!isSubtreeDelete) {
              // The subtree delete control was not specified and
              // the target entry is not a leaf.
              Message message =
                ERR_NDB_DELETE_NOT_ALLOWED_ON_NONLEAF.get(entryDN.toString());
              throw new DirectoryException(ResultCode.NOT_ALLOWED_ON_NONLEAF,
                message);
            }
 
            // Enforce any subtree delete size limit.
            if (adminSizeLimit > 0 && countDeletedDN >= adminSizeLimit) {
              adminSizeLimitExceeded = true;
              break;
            }
 
            // Enforce any subtree delete batch size.
            if (deleteBatchSize > 0 &&
              deletedDNList.size() >= deleteBatchSize) {
              batchSizeExceeded = true;
              break;
            }
 
            /*
             * Delete this entry which by now must be a leaf because
             * we have been deleting from the bottom of the tree upwards.
             */
            long entryID = result.id;
            DN subordinateDN = DN.decode(result.dn);
 
            AbstractTransaction subTxn = new AbstractTransaction(rootContainer);
            try {
              deleteLeaf(subTxn, subordinateDN, entryID, deleteOperation);
            } finally {
              if (subTxn != null) {
                subTxn.commit();
              }
            }
 
            deletedDNList.add(subordinateDN);
            countDeletedDN++;
 
            if (deleteOperation != null) {
              deleteOperation.checkIfCanceled(false);
            }
 
            result = cursor.getNext();
          }
        } finally {
          cursor.close();
          cursorTxn.close();
        }
      }
 
      // Finally delete the target entry as it was not included
      // in the dn2id iteration.
      if (!adminSizeLimitExceeded && !batchSizeExceeded)
      {
        // Enforce any subtree delete size limit.
        if (adminSizeLimit > 0 && countDeletedDN >= adminSizeLimit)
        {
          adminSizeLimitExceeded = true;
        }
        else if (deleteBatchSize > 0 &&
                 deletedDNList.size() >= deleteBatchSize)
        {
          batchSizeExceeded = true;
        }
        else
        {
          deleteTarget(txn, entryDN, entry, deleteOperation);
          deletedDNList.add(entryDN);
          countDeletedDN++;
        }
      }
    }
 
    /**
     * This method is called after the transaction has successfully
     * committed.
     */
    public void postCommitAction()
    {
 
    }
  }
 
  /**
   * Indicates whether an entry with the specified DN exists.
   *
   * @param  txn      Abstract transaction for this operation.
   * @param  entryDN  The DN of the entry for which to determine existence.
   *
   * @return  <CODE>true</CODE> if the specified entry exists,
   *          or <CODE>false</CODE> if it does not.
   *
   * @throws  DirectoryException  If a problem occurs while trying to make the
   *                              determination.
   * @throws  NdbApiException     An error occurred during a database operation.
   */
  public boolean entryExists(AbstractTransaction txn, DN entryDN)
      throws DirectoryException, NdbApiException
  {
    // Read the ID from dn2id.
    long id = 0;
 
    try
    {
      id = dn2id.getID(txn, entryDN, NdbOperation.LockMode.LM_CommittedRead);
    }
    catch (NdbApiException e)
    {
      if (debugEnabled())
      {
        TRACER.debugCaught(DebugLogLevel.ERROR, e);
      }
    }
 
    return id != 0;
  }
 
  /**
   * Fetch an entry by DN retrieves the requested entry.
   * Note that the caller must hold a read or write lock
   * on the specified DN.
   *
   * @param entryDN  The distinguished name of the entry to retrieve.
   * @param txn      Abstract transaction for this operation.
   * @param lockMode Operation lock mode.
   * @return The requested entry, or <CODE>null</CODE> if the entry does not
   *         exist.
   * @throws DirectoryException If a problem occurs while trying to retrieve
   *                            the entry.
   * @throws NDBException If an error occurs in the NDB backend.
   * @throws NdbApiException An error occurred during a database operation.
   */
  public Entry getEntryNoCommit(DN entryDN, AbstractTransaction txn,
    NdbOperation.LockMode lockMode)
      throws NDBException, NdbApiException, DirectoryException
  {
    Entry entry = null;
 
    GetEntryByDNOperation operation =
      new GetEntryByDNOperation(entryDN, lockMode);
 
    try {
      // Fetch the entry from the database.
      invokeTransactedOperation(txn, operation, null, false, false);
    } catch (CanceledOperationException ex) {
      // No LDAP operation, ignore.
    }
 
    entry = operation.getEntry();
 
    return entry;
  }
 
  /**
   * Fetch an entry by DN retrieves the requested entry.
   * Note that the caller must hold a read or write lock
   * on the specified DN.
   *
   * @param entryDN The distinguished name of the entry to retrieve.
   * @return The requested entry, or <CODE>null</CODE> if the entry does not
   *         exist.
   * @throws DirectoryException If a problem occurs while trying to retrieve
   *                            the entry.
   * @throws NDBException If an error occurs in the NDB backend.
   * @throws NdbApiException An error occurred during a database operation.
   */
  public Entry getEntry(DN entryDN)
      throws NDBException, NdbApiException, DirectoryException
  {
    Entry entry = null;
 
    GetEntryByDNOperation operation = new GetEntryByDNOperation(entryDN,
      NdbOperation.LockMode.LM_CommittedRead);
    AbstractTransaction txn = new AbstractTransaction(rootContainer);
 
    try {
      // Fetch the entry from the database.
      invokeTransactedOperation(txn, operation, null, true, false);
    } catch (CanceledOperationException ex) {
      // No LDAP operation, ignore.
    }
 
    entry = operation.getEntry();
 
    return entry;
  }
 
  /**
   * This inner class gets an entry by DN through
   * the TransactedOperation interface.
   */
  private class GetEntryByDNOperation implements TransactedOperation
  {
    /**
     * The retrieved entry.
     */
    private Entry entry = null;
 
    /**
     * The ID of the retrieved entry.
     */
    private long entryID = 0;
 
    /**
     * Operation lock mode.
     */
    private NdbOperation.LockMode lockMode;
 
    /**
     * The DN of the entry to be retrieved.
     */
    DN entryDN;
 
    /**
     * Create a new transacted operation to retrieve an entry by DN.
     * @param entryDN The DN of the entry to be retrieved.
     */
    public GetEntryByDNOperation(DN entryDN, NdbOperation.LockMode lockMode)
    {
      this.entryDN = entryDN;
      this.lockMode = lockMode;
    }
 
    /**
     * Get the retrieved entry.
     * @return The retrieved entry.
     */
    public Entry getEntry()
    {
      return entry;
    }
 
    /**
     * Get the ID of the retrieved entry.
     * @return The ID of the retrieved entry.
     */
    public long getEntryID()
    {
      return entryID;
    }
 
    /**
     * Invoke the operation under the given transaction.
     *
     * @param txn The transaction to be used to perform the operation
     * @throws NdbApiException If an error occurs in the NDB database.
     * @throws DirectoryException If a Directory Server error occurs.
     * @throws NDBException If an error occurs in the NDB backend.
     */
    public void invokeOperation(AbstractTransaction txn)
      throws NdbApiException, DirectoryException, NDBException
    {
      entry = dn2id.get(txn, entryDN, lockMode);
 
      if (entry == null) {
        // Check for referral entries above the target entry.
        targetEntryReferrals(txn, entryDN, null);
      }
    }
 
    /**
     * This method is called after the transaction has successfully
     * committed.
     */
    public void postCommitAction()
    {
      // No implementation required.
    }
  }
 
  /**
   * The simplest case of replacing an entry in which the entry DN has
   * not changed.
   *
   * @param oldEntry           The old contents of the entry.
   * @param newEntry           The new contents of the entry
   * @param modifyOperation The modify operation with which this action is
   *                        associated.  This may be <CODE>null</CODE> for
   *                        modifications performed internally.
   * @param txn             Abstract transaction for this operation.
   * @throws NdbApiException If an error occurs in the NDB database.
   * @throws DirectoryException If a Directory Server error occurs.
   * @throws CanceledOperationException If operation is canceled
   *         while in progress.
   * @throws NDBException If an error occurs in the NDB backend.
   */
  public void replaceEntry(Entry oldEntry, Entry newEntry,
    ModifyOperation modifyOperation, AbstractTransaction txn)
       throws CanceledOperationException, NdbApiException,
       DirectoryException, NDBException
  {
    TransactedOperation operation =
         new ReplaceEntryTransaction(oldEntry, newEntry, modifyOperation);
 
    invokeTransactedOperation(txn, operation, modifyOperation, true, true);
  }
 
  /**
   * This inner class implements the Replace Entry operation through
   * the TransactedOperation interface.
   */
  private class ReplaceEntryTransaction implements TransactedOperation
  {
    /**
     * The new contents of the entry.
     */
    private Entry newEntry;
 
    /**
     * The old contents of the entry.
     */
    private Entry oldEntry;
 
    /**
     * The Modify operation, or null if the replace is not due to a Modify
     * operation.
     */
    private ModifyOperation modifyOperation;
 
    /**
     * The ID of the entry that was replaced.
     */
    private Long entryID;
 
    /**
     * Create a new transacted operation to replace an entry.
     * @param entry The new contents of the entry.
     * @param modifyOperation The Modify operation, or null if the replace is
     * not due to a Modify operation.
     */
    public ReplaceEntryTransaction(Entry oldEntry, Entry newEntry,
                                   ModifyOperation modifyOperation)
    {
      this.oldEntry = oldEntry;
      this.newEntry = newEntry;
      this.modifyOperation = modifyOperation;
    }
 
    /**
     * Invoke the operation under the given transaction.
     *
     * @param txn The transaction to be used to perform the operation.
     * @throws NdbApiException If an error occurs in the NDB database.
     * @throws DirectoryException If a Directory Server error occurs.
     * @throws NDBException If an error occurs in the NDB backend.
     */
    public void invokeOperation(AbstractTransaction txn) throws NdbApiException,
                                                        DirectoryException,
                                                        NDBException
    {
      DN entryDN = newEntry.getDN();
      entryID = (Long) oldEntry.getAttachment();
      if (entryID == 0)
      {
        // The entry does not exist.
        Message message =
                ERR_NDB_MODIFY_NO_SUCH_OBJECT.get(entryDN.toString());
        DN matchedDN = getMatchedDN(txn, baseDN);
        throw new DirectoryException(ResultCode.NO_SUCH_OBJECT,
            message, matchedDN, null);
      }
 
      if (!isManageDsaITOperation(modifyOperation))
      {
        // Check if the entry is a referral entry.
        checkTargetForReferral(oldEntry, null);
      }
 
      // List<Modification> modsList = modifyOperation.getModifications();
 
      // Replace.
      if (!dn2id.put(txn, entryDN, entryID, newEntry, oldEntry))
      {
        // The entry does not exist.
        Message msg = ERR_NDB_MISSING_ID2ENTRY_RECORD.get(
          Long.toString(entryID));
        throw new NDBException(msg);
      }
    }
 
    /**
     * This method is called after the transaction has successfully
     * committed.
     */
    public void postCommitAction()
    {
 
    }
  }
 
  /**
   * Moves and/or renames the provided entry in this backend, altering any
   * subordinate entries as necessary.  This must ensure that an entry already
   * exists with the provided current DN, and that no entry exists with the
   * target DN of the provided entry.  The caller must hold write locks on both
   * the current DN and the new DN for the entry.
   *
   * @param currentDN         The current DN of the entry to be replaced.
   * @param entry             The new content to use for the entry.
   * @param modifyDNOperation The modify DN operation with which this action
   *                          is associated.  This may be <CODE>null</CODE>
   *                          for modify DN operations performed internally.
   * @param txn               Abstract transaction for this operation.
   * @throws org.opends.server.types.DirectoryException
   *          If a problem occurs while trying to perform
   *          the rename.
   * @throws org.opends.server.types.CanceledOperationException
   *          If this backend noticed and reacted
   *          to a request to cancel or abandon the
   *          modify DN operation.
   * @throws NdbApiException If an error occurs in the NDB database.
   * @throws NDBException If an error occurs in the NDB backend.
   */
  public void renameEntry(DN currentDN, Entry entry,
                          ModifyDNOperation modifyDNOperation,
                          AbstractTransaction txn)
      throws NdbApiException, NDBException, DirectoryException,
      CanceledOperationException {
    TransactedOperation operation =
        new RenameEntryTransaction(currentDN, entry, modifyDNOperation);
 
    invokeTransactedOperation(txn, operation, modifyDNOperation, true, true);
  }
 
  /**
   * This inner class implements the Modify DN operation through
   * the TransactedOperation interface.
   */
  private class RenameEntryTransaction implements TransactedOperation
  {
    /**
     * The DN of the entry to be renamed.
     */
    private DN oldApexDN;
 
    /**
     * The DN of the superior entry of the entry to be renamed.
     * This is null if the entry to be renamed is a base entry.
     */
    private DN oldSuperiorDN;
 
    /**
     * The DN of the new superior entry, which can be the same
     * as the current superior entry.
     */
    private DN newSuperiorDN;
 
    /**
     * The new contents of the entry to be renamed.
     */
    private Entry newApexEntry;
 
    /**
     * The Modify DN operation.
     */
    private ModifyDNOperation modifyDNOperation;
 
    /**
     * Create a new transacted operation for a Modify DN operation.
     * @param currentDN The DN of the entry to be renamed.
     * @param entry The new contents of the entry.
     * @param modifyDNOperation The Modify DN operation to be performed.
     */
    public RenameEntryTransaction(DN currentDN, Entry entry,
                                  ModifyDNOperation modifyDNOperation)
    {
      this.oldApexDN = currentDN;
      this.oldSuperiorDN = getParentWithinBase(currentDN);
      this.newSuperiorDN = getParentWithinBase(entry.getDN());
      this.newApexEntry = entry;
      this.modifyDNOperation = modifyDNOperation;
    }
 
    /**
     * Invoke the operation under the given transaction.
     *
     * @param txn The transaction to be used to perform the operation.
     * @throws NdbApiException If an error occurs in the NDB database.
     * @throws DirectoryException If a Directory Server error occurs.
     * @throws NDBException If an error occurs in the NDB backend.
     */
    public void invokeOperation(AbstractTransaction txn)
      throws NdbApiException, DirectoryException,
      CanceledOperationException, NDBException
    {
      DN requestedNewSuperiorDN = null;
 
      if (modifyDNOperation != null)
      {
        requestedNewSuperiorDN = modifyDNOperation.getNewSuperior();
      }
 
      // Check whether the renamed entry already exists.
      if (dn2id.getID(txn, newApexEntry.getDN(),
        NdbOperation.LockMode.LM_Exclusive) != 0)
      {
        Message message = ERR_NDB_MODIFYDN_ALREADY_EXISTS.get(
            newApexEntry.getDN().toString());
        throw new DirectoryException(ResultCode.ENTRY_ALREADY_EXISTS,
                                     message);
      }
 
      Entry oldApexEntry = dn2id.get(txn, oldApexDN,
        NdbOperation.LockMode.LM_Exclusive);
      if (oldApexEntry == null)
      {
        // Check for referral entries above the target entry.
        targetEntryReferrals(txn, oldApexDN, null);
 
        Message message =
                ERR_NDB_MODIFYDN_NO_SUCH_OBJECT.get(oldApexDN.toString());
        DN matchedDN = getMatchedDN(txn, baseDN);
        throw new DirectoryException(ResultCode.NO_SUCH_OBJECT,
            message, matchedDN, null);
      }
 
      if (!isManageDsaITOperation(modifyDNOperation))
      {
        checkTargetForReferral(oldApexEntry, null);
      }
 
      long oldApexID = (Long) oldApexEntry.getAttachment();
      long newApexID = oldApexID;
 
      if (newSuperiorDN != null)
      {
        long newSuperiorID = dn2id.getID(txn, newSuperiorDN,
          NdbOperation.LockMode.LM_Exclusive);
        if (newSuperiorID == 0)
        {
          Message msg =
                  ERR_NDB_NEW_SUPERIOR_NO_SUCH_OBJECT.get(
                          newSuperiorDN.toString());
          DN matchedDN = getMatchedDN(txn, baseDN);
          throw new DirectoryException(ResultCode.NO_SUCH_OBJECT,
              msg, matchedDN, null);
        }
        newApexID = rootContainer.getNextEntryID(txn.getNdb());
      }
 
      // Move or rename the apex entry.
      if (requestedNewSuperiorDN != null)
      {
        moveApexEntry(txn, newApexID, oldApexEntry, newApexEntry);
      }
      else
      {
        long newID = rootContainer.getNextEntryID(txn.getNdb());
        renameApexEntry(txn, newID, oldApexEntry, newApexEntry);
      }
 
      AbstractTransaction cursorTxn =
          new AbstractTransaction(rootContainer);
      DN2IDSearchCursor cursor = dn2id.getSearchCursor(cursorTxn, oldApexDN);
      cursor.open();
 
      try {
        SearchCursorResult result = cursor.getNext();
        // Step forward until we pass the ending value.
        while (result != null) {
          // We have found a subordinate entry.
          long oldID = result.id;
          String oldDN = result.dn;
          Entry oldEntry = null;
          AbstractTransaction subTxn = new AbstractTransaction(rootContainer);
          try {
            oldEntry = dn2id.get(subTxn, DN.decode(oldDN),
              NdbOperation.LockMode.LM_Exclusive);
 
            if (!isManageDsaITOperation(modifyDNOperation)) {
              checkTargetForReferral(oldEntry, null);
            }
 
            // Construct the new DN of the entry.
            DN newDN = modDN(oldEntry.getDN(),
              oldApexDN.getNumComponents(),
              newApexEntry.getDN());
 
            if (requestedNewSuperiorDN != null) {
              // Assign a new entry ID if we are renumbering.
              long newID = oldID;
              if (newApexID != oldApexID) {
                newID = rootContainer.getNextEntryID(subTxn.getNdb());
              }
 
              // Move this entry.
              moveSubordinateEntry(subTxn, newID, oldEntry, newDN);
            } else {
              // Rename this entry.
              renameSubordinateEntry(subTxn, oldID, oldEntry, newDN);
            }
          } finally {
            if (subTxn != null) {
              subTxn.commit();
            }
          }
 
          if (modifyDNOperation != null) {
            modifyDNOperation.checkIfCanceled(false);
          }
 
          result = cursor.getNext();
        }
      } finally {
        cursor.close();
        cursorTxn.close();
      }
    }
 
    /**
     * Update the database for the target entry of a ModDN operation
     * specifying a new superior.
     *
     * @param txn The abstract transaction to be used for the updates.
     * @param newID The new ID of the target entry, or the original ID if
     *              the ID has not changed.
     * @param oldEntry The original contents of the target entry.
     * @param newEntry The new contents of the target entry.
     * @throws NDBException If an error occurs in the NDB backend.
     * @throws DirectoryException If a Directory Server error occurs.
     * @throws NdbApiException If an error occurs in the NDB database.
     */
    private void moveApexEntry(AbstractTransaction txn,
                               long newID, Entry oldEntry, Entry newEntry)
        throws NDBException, DirectoryException, NdbApiException
    {
      // DN oldDN = oldEntry.getDN();
      DN newDN = newEntry.getDN();
 
      // Remove the old DN from dn2id.
      dn2id.remove(txn, oldEntry);
 
      // Insert the new DN in dn2id.
      if (!dn2id.insert(txn, newDN, newID, newEntry))
      {
        Message message = ERR_NDB_MODIFYDN_ALREADY_EXISTS.get(newDN.toString());
        throw new DirectoryException(ResultCode.ENTRY_ALREADY_EXISTS,
                                     message);
      }
    }
 
    /**
     * Update the database for the target entry of a Modify DN operation
     * not specifying a new superior.
     *
     * @param txn The abstract transaction to be used for the updates.
     * @param newID The new ID of the target entry.
     * @param oldEntry The original contents of the target entry.
     * @param newEntry The new contents of the target entry.
     * @throws DirectoryException If a Directory Server error occurs.
     * @throws NdbApiException If an error occurs in the NDB database.
     * @throws NDBException if an error occurs in the NDB Backend.
     */
    private void renameApexEntry(AbstractTransaction txn, long newID,
                                 Entry oldEntry, Entry newEntry)
        throws DirectoryException, NdbApiException, NDBException
    {
      // DN oldDN = oldEntry.getDN();
      DN newDN = newEntry.getDN();
 
      // Remove the old DN from dn2id.
      dn2id.remove(txn, oldEntry);
 
      // Insert the new DN in dn2id.
      if (!dn2id.insert(txn, newDN, newID, newEntry))
      {
        Message message = ERR_NDB_MODIFYDN_ALREADY_EXISTS.get(newDN.toString());
        throw new DirectoryException(ResultCode.ENTRY_ALREADY_EXISTS,
                                     message);
      }
    }
 
    /**
     * Update the database for a subordinate entry of the target entry
     * of a Modify DN operation specifying a new superior.
     *
     * @param txn The abstract transaction to be used for the updates.
     * @param newID The new ID of the subordinate entry, or the original ID if
     *              the ID has not changed.
     * @param oldEntry The original contents of the subordinate entry.
     * @param newDN The new DN of the subordinate entry.
     * @throws NDBException If an error occurs in the NDB backend.
     * @throws DirectoryException If a Directory Server error occurs.
     * @throws NdbApiException If an error occurs in the NDB database.
     */
    private void moveSubordinateEntry(AbstractTransaction txn,
                                      long newID,
                                      Entry oldEntry, DN newDN)
        throws NDBException, DirectoryException, NdbApiException
    {
      // Remove the old DN from dn2id.
      dn2id.remove(txn, oldEntry);
 
      // Create a new entry that is a copy of the old entry but with the new DN.
      Entry newEntry = oldEntry.duplicate(false);
      newEntry.setDN(newDN);
 
      // Put the new DN in dn2id.
      if (!dn2id.insert(txn, newDN, newID, newEntry))
      {
        Message message = ERR_NDB_MODIFYDN_ALREADY_EXISTS.get(newDN.toString());
        throw new DirectoryException(ResultCode.ENTRY_ALREADY_EXISTS,
                                     message);
      }
    }
 
    /**
     * Update the database for a subordinate entry of the target entry
     * of a Modify DN operation not specifying a new superior.
     *
     * @param txn The abstract transaction to be used for the updates.
     * @param entryID The ID of the subordinate entry.
     * @param oldEntry The original contents of the subordinate entry.
     * @param newDN The new DN of the subordinate entry.
     * @throws DirectoryException If a Directory Server error occurs.
     * @throws NdbApiException If an error occurs in the NDB database.
     */
    private void renameSubordinateEntry(AbstractTransaction txn, long entryID,
                                        Entry oldEntry, DN newDN)
        throws DirectoryException, NDBException, NdbApiException
    {
      // Remove the old DN from dn2id.
      dn2id.remove(txn, oldEntry);
 
      // Create a new entry that is a copy of the old entry but with the new DN.
      Entry newEntry = oldEntry.duplicate(false);
      newEntry.setDN(newDN);
 
      // Insert the new DN in dn2id.
      if (!dn2id.insert(txn, newDN, entryID, newEntry))
      {
        Message message = ERR_NDB_MODIFYDN_ALREADY_EXISTS.get(newDN.toString());
        throw new DirectoryException(ResultCode.ENTRY_ALREADY_EXISTS,
                                     message);
      }
    }
 
    /**
     * This method is called after the transaction has successfully
     * committed.
     */
    public void postCommitAction()
    {
      // No implementation needed.
    }
  }
 
  /**
   * Make a new DN for a subordinate entry of a renamed or moved entry.
   *
   * @param oldDN The current DN of the subordinate entry.
   * @param oldSuffixLen The current DN length of the renamed or moved entry.
   * @param newSuffixDN The new DN of the renamed or moved entry.
   * @return The new DN of the subordinate entry.
   */
  public static DN modDN(DN oldDN, int oldSuffixLen, DN newSuffixDN)
  {
    int oldDNNumComponents    = oldDN.getNumComponents();
    int oldDNKeepComponents   = oldDNNumComponents - oldSuffixLen;
    int newSuffixDNComponents = newSuffixDN.getNumComponents();
 
    RDN[] newDNComponents = new RDN[oldDNKeepComponents+newSuffixDNComponents];
    for (int i=0; i < oldDNKeepComponents; i++)
    {
      newDNComponents[i] = oldDN.getRDN(i);
    }
 
    for (int i=oldDNKeepComponents, j=0; j < newSuffixDNComponents; i++,j++)
    {
      newDNComponents[i] = newSuffixDN.getRDN(j);
    }
 
    return new DN(newDNComponents);
  }
 
  /**
   * Get a count of the number of entries stored in this entry entryContainer.
   *
   * @return The number of entries stored in this entry entryContainer.
   * @throws NdbApiException If an error occurs in the NDB database.
   */
  public long getEntryCount() throws NdbApiException
  {
    return dn2id.getRecordCount();
  }
 
  /**
   * Get the number of values for which the entry limit has been exceeded
   * since the entry entryContainer was opened.
   * @return The number of values for which the entry limit has been exceeded.
   */
  public int getEntryLimitExceededCount()
  {
    int count = 0;
    return count;
  }
 
  /**
   * Get a list of the databases opened by this entryContainer.
   * @param dbList A list of database containers.
   */
  public void listDatabases(List<DatabaseContainer> dbList)
  {
    dbList.add(dn2id);
  }
 
  /**
   * Determine whether the provided operation has the ManageDsaIT request
   * control.
   * @param operation The operation for which the determination is to be made.
   * @return true if the operation has the ManageDsaIT request control, or false
   * if not.
   */
  public static boolean isManageDsaITOperation(Operation operation)
  {
    if(operation != null)
    {
      List<Control> controls = operation.getRequestControls();
      if (controls != null)
      {
        for (Control control : controls)
        {
          if (control.getOID().equals(ServerConstants.OID_MANAGE_DSAIT_CONTROL))
          {
            return true;
          }
        }
      }
    }
    return false;
  }
 
  /**
   * This method constructs a container name from a base DN. Only alphanumeric
   * characters are preserved, all other characters are replaced with an
   * underscore.
   *
   * @return The container name for the base DN.
   */
  public String getDatabasePrefix()
  {
    return databasePrefix;
  }
 
  /**
   * Get the baseDN this entry container is responsible for.
   *
   * @return The Base DN for this entry container.
   */
  public DN getBaseDN()
  {
    return baseDN;
  }
 
  /**
   * Get the parent of a DN in the scope of the base DN.
   *
   * @param dn A DN which is in the scope of the base DN.
   * @return The parent DN, or null if the given DN is the base DN.
   */
  public DN getParentWithinBase(DN dn)
  {
    if (dn.equals(baseDN))
    {
      return null;
    }
    return dn.getParent();
  }
 
  /**
   * {@inheritDoc}
   */
  public synchronized boolean isConfigurationChangeAcceptable(
      NdbBackendCfg cfg, List<Message> unacceptableReasons)
  {
    // This is always true because only all config attributes used
    // by the entry container should be validated by the admin framework.
    return true;
  }
 
  /**
   * {@inheritDoc}
   */
  public synchronized ConfigChangeResult applyConfigurationChange(
      NdbBackendCfg cfg)
  {
    boolean adminActionRequired = false;
    ArrayList<Message> messages = new ArrayList<Message>();
 
    this.config = cfg;
    this.deadlockRetryLimit = config.getDeadlockRetryLimit();
 
    return new ConfigChangeResult(ResultCode.SUCCESS,
                                  adminActionRequired, messages);
  }
 
  /**
   * Checks whether the target of an operation is a referral entry and throws
   * a Directory referral exception if it is.
   * @param entry The target entry of the operation, or the base entry of a
   * search operation.
   * @param searchScope The scope of the search operation, or null if the
   * operation is not a search operation.
   * @throws DirectoryException If a referral is found at or above the target
   * DN.  The referral URLs will be set appropriately for the references found
   * in the referral entry.
   */
  public void checkTargetForReferral(Entry entry, SearchScope searchScope)
       throws DirectoryException
  {
    Set<String> referralURLs = entry.getReferralURLs();
    if (referralURLs != null)
    {
      throwReferralException(entry.getDN(), entry.getDN(), referralURLs,
                             searchScope);
    }
  }
 
  /**
   * Throws a Directory referral exception for the case where a referral entry
   * exists at or above the target DN of an operation.
   * @param targetDN The target DN of the operation, or the base object of a
   * search operation.
   * @param referralDN The DN of the referral entry.
   * @param labeledURIs The set of labeled URIs in the referral entry.
   * @param searchScope The scope of the search operation, or null if the
   * operation is not a search operation.
   * @throws DirectoryException If a referral is found at or above the target
   * DN.  The referral URLs will be set appropriately for the references found
   * in the referral entry.
   */
  public void throwReferralException(DN targetDN, DN referralDN,
                                     Set<String> labeledURIs,
                                     SearchScope searchScope)
       throws DirectoryException
  {
    ArrayList<String> URIList = new ArrayList<String>(labeledURIs.size());
    for (String labeledURI : labeledURIs)
    {
      // Remove the label part of the labeled URI if there is a label.
      String uri = labeledURI;
      int i = labeledURI.indexOf(' ');
      if (i != -1)
      {
        uri = labeledURI.substring(0, i);
      }
 
      try
      {
        LDAPURL ldapurl = LDAPURL.decode(uri, false);
 
        if (ldapurl.getScheme().equalsIgnoreCase("ldap"))
        {
          DN urlBaseDN = targetDN;
          if (!referralDN.equals(ldapurl.getBaseDN()))
          {
            urlBaseDN =
                 EntryContainer.modDN(targetDN,
                                      referralDN.getNumComponents(),
                                      ldapurl.getBaseDN());
          }
          ldapurl.setBaseDN(urlBaseDN);
          if (searchScope == null)
          {
            // RFC 3296, 5.2.  Target Object Considerations:
            // In cases where the URI to be returned is a LDAP URL, the server
            // SHOULD trim any present scope, filter, or attribute list from the
            // URI before returning it.  Critical extensions MUST NOT be trimmed
            // or modified.
            StringBuilder builder = new StringBuilder(uri.length());
            ldapurl.toString(builder, true);
            uri = builder.toString();
          }
          else
          {
            // RFC 3296, 5.3.  Base Object Considerations:
            // In cases where the URI to be returned is a LDAP URL, the server
            // MUST provide an explicit scope specifier from the LDAP URL prior
            // to returning it.
            ldapurl.getAttributes().clear();
            ldapurl.setScope(searchScope);
            ldapurl.setFilter(null);
            uri = ldapurl.toString();
          }
        }
      }
      catch (DirectoryException e)
      {
        if (debugEnabled())
        {
          TRACER.debugCaught(DebugLogLevel.ERROR, e);
        }
        // Return the non-LDAP URI as is.
      }
 
      URIList.add(uri);
    }
 
    // Throw a directory referral exception containing the URIs.
    Message msg =
        NOTE_NDB_REFERRAL_RESULT_MESSAGE.get(String.valueOf(referralDN));
    throw new DirectoryException(
            ResultCode.REFERRAL, msg, referralDN, URIList, null);
  }
 
  /**
   * Process referral entries that are above the target DN of an operation.
   * @param txn      Abstract transaction for this operation.
   * @param targetDN The target DN of the operation, or the base object of a
   * search operation.
   * @param searchScope The scope of the search operation, or null if the
   * operation is not a search operation.
   * @throws DirectoryException If a referral is found at or above the target
   * DN.  The referral URLs will be set appropriately for the references found
   * in the referral entry.
   * @throws NdbApiException An error occurred during a database operation.
   */
  public void targetEntryReferrals(AbstractTransaction txn,
    DN targetDN, SearchScope searchScope)
       throws DirectoryException, NdbApiException
  {
    try {
      // Go up through the DIT hierarchy until we find a referral.
      for (DN dn = getParentWithinBase(targetDN); dn != null;
        dn = getParentWithinBase(dn)) {
        // Construct a set of all the labeled URIs in the referral.
        long id = dn2id.getID(txn, dn, NdbOperation.LockMode.LM_Read);
        Set<String> labeledURIs = dn2id.getReferrals(txn, id);
        if (!labeledURIs.isEmpty()) {
          throwReferralException(targetDN, dn, labeledURIs, searchScope);
        }
      }
    }
    catch (NdbApiException e)
    {
      if (debugEnabled())
      {
        TRACER.debugCaught(DebugLogLevel.ERROR, e);
      }
    }
  }
 
 
  /**
   * Finds an existing entry whose DN is the closest ancestor of a given baseDN.
   *
   * @param baseDN  the DN for which we are searching a matched DN
   * @return the DN of the closest ancestor of the baseDN
   * @throws DirectoryException If an error prevented the check of an
   * existing entry from being performed
   */
  private DN getMatchedDN(AbstractTransaction txn, DN baseDN)
    throws DirectoryException, NdbApiException
  {
    DN matchedDN = null;
    DN parentDN  = baseDN.getParentDNInSuffix();
    while ((parentDN != null) && parentDN.isDescendantOf(getBaseDN()))
    {
      if (entryExists(txn, parentDN))
      {
        matchedDN = parentDN;
        break;
      }
      parentDN = parentDN.getParentDNInSuffix();
    }
    return matchedDN;
  }
}