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

Nicolas Capponi
12.08.2015 530e312594f469609337996570cf0ea504554a68
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
/*
 * 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 legal-notices/CDDLv1_0.txt
 * or http://forgerock.org/license/CDDLv1.0.html.
 * 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 legal-notices/CDDLv1_0.txt.
 * 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 2006-2010 Sun Microsystems, Inc.
 *      Portions Copyright 2011-2015 ForgeRock AS
 */
package org.opends.server.backends.jeb;
 
import static org.opends.server.util.ServerConstants.*;
import static org.testng.Assert.*;
 
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
 
import org.forgerock.opendj.ldap.ByteString;
import org.opends.server.TestCaseUtils;
import org.opends.server.api.Backend;
import org.opends.server.backends.VerifyConfig;
import org.opends.server.core.DirectoryServer;
import org.opends.server.types.*;
import org.opends.server.util.StaticUtils;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
 
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.Transaction;
 
@SuppressWarnings("javadoc")
public class TestVerifyJob extends JebTestCase
{
  /** Root suffix for verify backend. */
  private static String suffix="dc=verify,dc=jeb";
  private static  String vBranch="ou=verify tests," + suffix;
  private  String backendID = "verifyRoot";
  private  String numUsersLine="define numusers= #numEntries#";
  private  DN[] baseDNs;
  private Backend<?> backend;
  private EntryContainer eContainer;
  private DN2ID dn2id;
  private ID2Entry id2entry;
  private Index id2child;
  private Index id2subtree;
  private Transaction txn;
 
  /** Some DNs needed mostly for DN2ID tests. */
  private  String junkDN="cn=junk," + vBranch;
  private  String junkDN1="cn=junk1," + vBranch;
  private  String junkDN2="cn=junk2," + vBranch;
  private  String junkDN3="cn=junk3," + vBranch;
  /** This DN has no parent. */
  private  String noParentDN="cn=junk1,cn=junk22," + vBranch;
  /** Parent child combo for id2child/subtree type tests. */
  private  String pDN="cn=junk222," + vBranch;
  private  String cDN="cn=junk4,cn=junk222," + vBranch;
  /** Bad DN. */
  private  String badDN="this is a bad DN";
  /** This index file should not exist. */
  private  String badIndexName="badIndexName";
 
  @DataProvider(name = "indexes")
  public Object[][] indexes() {
    return new Object[][] {
         { "telephoneNumber"},
         {"givenName"},
         { "id2subtree"},
         {"id2children"},
         {"dn2id"}
    };
  }
 
  private static String[] template = new String[] {
       "define suffix="+suffix,
       "define maildomain=example.com",
       "define numusers= #numEntries#",
       "",
       "branch: [suffix]",
       "",
       "branch: " + vBranch,
       "subordinateTemplate: person:[numusers]",
       "",
       "template: person",
       "rdnAttr: uid",
       "objectClass: top",
       "objectClass: person",
       "objectClass: organizationalPerson",
       "objectClass: inetOrgPerson",
       "givenName: ABOVE LIMIT",
       "sn: <last>",
       "cn: {givenName} {sn}",
       "initials: {givenName:1}<random:chars:" +
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ:1>{sn:1}",
       "employeeNumber: <sequential:0>",
       "uid: user.{employeeNumber}",
       "mail: {uid}@[maildomain]",
       "userPassword: password",
       "telephoneNumber: <random:telephone>",
       "homePhone: <random:telephone>",
       "pager: <random:telephone>",
       "mobile: <random:telephone>",
       "street: <random:numeric:5> <file:streets> Street",
       "l: <file:cities>",
       "st: <file:states>",
       "postalCode: <random:numeric:5>",
       "postalAddress: {cn}${street}${l}, {st}  {postalCode}",
       "description: This is the description for {cn}.",
       ""};
 
  @BeforeClass
  public void setup() throws Exception {
    TestCaseUtils.startServer();
    TestCaseUtils.enableBackend(backendID);
    baseDNs = new DN[] {
         DN.valueOf(suffix)
    };
  }
 
  @AfterClass
  public void cleanUp() throws Exception {
    TestCaseUtils.clearJEBackend(backendID);
    TestCaseUtils.disableBackend(backendID);
  }
 
  /**
   * Performs a complete verify against a backend using the entries loaded in
   * the setup initializer.
   *
   * @throws Exception
   *           if error count is not equal to 0.
   */
  @Test
  public void testCompleteVerifyJob()  throws Exception {
    cleanAndLoad(9);
    VerifyConfig verifyConfig = new VerifyConfig();
    verifyConfig.setBaseDN(baseDNs[0]);
    backend = DirectoryServer.getBackend(backendID);
    assertEquals(backend.verifyBackend(verifyConfig), 0);
  }
 
  /**
   * Adds more than "entry limit" number of entries and runs clean
   * verify against two indexes.
   *
   * @throws Exception if error count is not equal to 0.
   */
  @Test
  public void testEntryLimitVerifyJob()  throws Exception {
    cleanAndLoad(25);
    VerifyConfig verifyConfig = new VerifyConfig();
    verifyConfig.setBaseDN(baseDNs[0]);
    verifyConfig.addCleanIndex("telephoneNumber");
    verifyConfig.addCleanIndex("givenName");
    backend = DirectoryServer.getBackend(backendID);
    assertEquals(backend.verifyBackend(verifyConfig), 0);
  }
 
  /**
   * Runs clean verify jobs against a set of indexes (defined in
   * indexes array).
   * @param index An element of the indexes array.
   * @throws Exception if the error count is not equal to 0.
   */
 
  @Test(dataProvider = "indexes")
  public void testCleanVerifyJob(String index)  throws Exception {
    cleanAndLoad(9);
    VerifyConfig verifyConfig = new VerifyConfig();
    verifyConfig.setBaseDN(baseDNs[0]);
    verifyConfig.addCleanIndex(index);
    backend = DirectoryServer.getBackend(backendID);
    assertEquals(backend.verifyBackend(verifyConfig), 0);
  }
 
  /*
     * Begin Clean index tests. These are tests that cursor through an index
     * file and validate it's keys and idlists against the id2entry database entries.
     * The complete index tests go the other way. They cursor the id2entry database
     * and validate each entry against the various index files.
     */
 
  /**
   * Runs clean verify against the dn2id index after adding
   * various errors in that index file.
   *
   * @throws Exception if the error count is not equal to 5.
   */
  @Test
  public void testCleanDN2ID() throws Exception {
    preTest(3);
    eContainer.sharedLock.lock();
    try
    {
      //Add a junk DN and non-existent entry id to DN2ID index
      DN testDN=DN.valueOf(junkDN);
      EntryID id=new EntryID(45);
      assertTrue(dn2id.insert(txn, testDN, id));
      //Make two DN keys point at same entry.
      testDN=DN.valueOf(junkDN1);
      id=new EntryID(3);
      assertTrue(dn2id.insert(txn, testDN, id));
      //Add badDN key with bad entry id
      DatabaseEntry key = new DatabaseEntry(StaticUtils.getBytes(badDN));
      DatabaseEntry data = new EntryID(37).getDatabaseEntry();
      assertEquals(dn2id.put(txn, key, data), OperationStatus.SUCCESS);
      //Add DN key with malformed entryID
      key=new DatabaseEntry(StaticUtils.getBytes(junkDN2));
      data= new DatabaseEntry(new byte[3]);
      assertEquals(dn2id.put(txn, key, data), OperationStatus.SUCCESS);
      //Try to break JebFormat version
      addID2EntryReturnKey(junkDN3, 20, true);
      id=new EntryID(20);
      assertTrue(dn2id.insert(txn, DN.valueOf(junkDN3), id));
      performBECleanVerify("dn2id", 5);
    }
    finally
    {
      eContainer.sharedLock.unlock();
    }
  }
 
  /**
   * Runs clean verify against the id2children index after adding
   * various errors in that index file.
   *
   * @throws Exception if the error count is not equal to 6.
   */
  @Test
  public void testCleanID2Children() throws Exception {
    preTest(3);
    eContainer.sharedLock.lock();
    try
    {
      //Add malformed key
      byte[] shortBytes = new byte[3];
      DatabaseEntry key= new DatabaseEntry(shortBytes);
      EntryIDSet idSet=new EntryIDSet();
      id2child.writeKey(txn, key, idSet);
      //Try to break JebFormat version of key entry
      key=addID2EntryReturnKey(junkDN, 4, true);
      idSet=new EntryIDSet(new byte[16], new byte[16]);
      id2child.writeKey(txn, key, idSet);
      //put invalid key -- no EntryID matches
      key= new EntryID(45).getDatabaseEntry();
      id2child.writeKey(txn, key, idSet);
      //invalid ids in id list
      key=addID2EntryReturnKey(junkDN1, 5, false);
      byte[] idBytes=new byte[24];
      //doesn't exist
      idBytes[3] = (byte)0xff;
      //not a child
      idBytes[15] = (byte)1;
      //bad jeb format
      idBytes[23] = (byte) 0x04;
      idSet = new EntryIDSet(null, idBytes);
      id2child.writeKey(txn, key, idSet);
      performBECleanVerify("id2children", 6);
    }
    finally
    {
      eContainer.sharedLock.unlock();
    }
  }
 
  /**
   * Runs clean verify against the id2subtree index after adding
   * various errors in that index file.
   *
   * @throws Exception if the error count is not equal to 7.
   */
  @Test
  public void testCleanID2Subtree() throws Exception {
    preTest(4);
    eContainer.sharedLock.lock();
    try
    {
      //break key
      byte[] shortBytes = new byte[3];
      DatabaseEntry key= new DatabaseEntry(shortBytes);
      EntryIDSet idSet=new EntryIDSet();
      id2subtree.writeKey(txn, key, idSet);
      //put invalid ids into entry 3 idlist
      key= new EntryID(3).getDatabaseEntry();
      byte[] idBytes=new byte[16];
      //invalid id
      idBytes[3] = (byte)0xff;
      //non-subordinate
      idBytes[15] = (byte)1;
      idSet = new EntryIDSet(null, idBytes);
      id2subtree.writeKey(txn, key, idSet);
      //Try to break JebFormat version of key entry
      key=addID2EntryReturnKey(junkDN, 4, true);
      idBytes[3]=(byte) 0x04;
      idBytes[15]=(byte)0x00;
      EntryIDSet idSet1 = new EntryIDSet(null, idBytes);
      id2subtree.writeKey(txn, key, idSet1);
      //put invalid key -- no EntryID matches
      key= new EntryID(45).getDatabaseEntry();
      idSet = new EntryIDSet(null, idBytes);
      id2subtree.writeKey(txn, key, idSet);
      performBECleanVerify("id2subtree", 7);
    }
    finally
    {
      eContainer.sharedLock.unlock();
    }
  }
 
  /**
   * Runs clean verify against the telephoneNumber.equality index
   * after adding various errors in that index file.
   *
   * @throws Exception if the error count is not equal to 4.
   */
  @Test
  public void testCleanAttrIndex() throws Exception {
    String phoneType="telephonenumber";
    preTest(3);
    eContainer.sharedLock.lock();
    try
    {
      AttributeType attributeType = DirectoryServer.getAttributeType(phoneType);
      Index index = eContainer.getAttributeIndex(attributeType).getEqualityIndex();
      //Add entry with bad JEB format Version
      addID2EntryReturnKey(junkDN, 4, true);
      //Add phone number with various bad id list entryIDs
      byte[] subBytes = StaticUtils.getBytes("0009999999");
      DatabaseEntry key= new DatabaseEntry(subBytes);
      byte[] dataBytes=new byte[32];
      //put duplicate ids in list
      dataBytes[7] = (byte)1;
      dataBytes[15] = (byte)1;
      //put id that doesn't exist
      dataBytes[23] = (byte)0xff;
      //point to bad entry added above
      dataBytes[31] = (byte) 0x04;
      DatabaseEntry data= new DatabaseEntry(dataBytes);
      OperationStatus status = index.put(txn, key, data);
      assertEquals(status, OperationStatus.SUCCESS);
      //really 5 errors, but duplicate reference doesn't increment error
      //count for some reason
      performBECleanVerify(phoneType, 4);
    }
    finally
    {
      eContainer.sharedLock.unlock();
    }
  }
 
  /**
   * Runs clean verify against the testvlvindex VLV index
   * after adding various errors to each of these index files.
   * @throws Exception if the error count is not equal to 6.
   */
  @Test
  public void testCleanVLV() throws Exception {
    String indexName = "testvlvindex";
    preTest(4);
    eContainer.sharedLock.lock();
    try
    {
      VLVIndex vlvIndex = eContainer.getVLVIndex(indexName);
      AttributeType[] types = vlvIndex.getSortTypes();
 
      // Add an incorrectly ordered values.
      SortValuesSet svs =
          vlvIndex.getSortValuesSet(null, 0, new ByteString[3], new AttributeType[3]);
      long id = svs.getEntryIDs()[0];
      Entry entry = eContainer.getID2Entry().get(null, new EntryID(id), LockMode.DEFAULT);
 
      SortValuesSet svs2 = svs.split(2);
      svs2.add(id, vlvIndex.getSortValues(entry), types);
 
      // Add an invalid ID
      svs2.add(1000, vlvIndex.getSortValues(entry), types);
 
      // Muck up the values of another ID
      id = svs.getEntryIDs()[0];
      entry = eContainer.getID2Entry().get(null, new EntryID(id), LockMode.DEFAULT);
      ByteString[] values = vlvIndex.getSortValues(entry);
      ByteString[] badValues = new ByteString[values.length];
      System.arraycopy(values, 1, badValues, 0, values.length - 1);
      badValues[badValues.length-1] = values[0];
      remove(svs, id, values);
      svs.add(id, badValues, types);
 
      putSortValuesSet(vlvIndex, svs);
      putSortValuesSet(vlvIndex, svs2);
      performBECleanVerify("vlv." + indexName, 3);
    }
    finally
    {
      eContainer.sharedLock.unlock();
    }
 
  }
 
 
  /*
     * Begin complete verify index tests. As described above, these are
     * tests that cursor through the id2entry database and validate
     * each entry against the various index files.
     *
     */
 
  /**
   * Runs complete verify against the telephoneNumber index
   * after adding various errors in the id2entry file.
   *
   * @throws Exception if the error count is not equal to 3.
   */
  @Test
  public void testVerifyID2Entry() throws Exception {
    preTest(3);
    eContainer.sharedLock.lock();
    try
    {
      //Add entry with short id
      byte[] shortBytes = new byte[3];
      DatabaseEntry key= new DatabaseEntry(shortBytes);
      Entry testEntry = buildEntry(junkDN);
      DataConfig dataConfig = new DataConfig(false, false, null);
      ByteString entryBytes = ID2Entry.entryToDatabase(testEntry, dataConfig);
      DatabaseEntry data= new DatabaseEntry(entryBytes.toByteArray());
      assertEquals(id2entry.put(txn, key, data), OperationStatus.SUCCESS);
 
      // add entry with random bytes
      DatabaseEntry key1= new EntryID(4).getDatabaseEntry();
      byte []eBytes = new byte[459];
      for(int i=0;i<459;i++) {
        eBytes[i]=(byte) (i*2);
      }
      //set version correctly
      eBytes[0]=0x01;
      DatabaseEntry data1= new DatabaseEntry(eBytes);
      assertEquals(id2entry.put(txn, key1, data1), OperationStatus.SUCCESS);
      performBECompleteVerify("telephoneNumber", 3);
    }
    finally
    {
      eContainer.sharedLock.unlock();
    }
  }
 
  /**
   *
   * Runs complete verify against the dn2id index
   * after adding various errors in the dn2id file.
   *
   * @throws Exception if the error count is not equal to 3.
   */
  @Test
  public void testVerifyDN2ID() throws Exception {
    preTest(9);
    eContainer.sharedLock.lock();
    try
    {
      //add entry but no corresponding dn2id key
      addID2EntryReturnKey(junkDN, 10, false);
      //entry has dn2id key but its entryID -- don't need key
      addID2EntryReturnKey(junkDN1, 11, false);
      //insert key with bad entry id (45 instead of 10)
      DN testDN=DN.valueOf(junkDN1);
      EntryID id=new EntryID(45);
      assertTrue(dn2id.insert(txn, testDN, id));
      //entry has no parent in dn2id
      addID2EntryReturnKey(noParentDN, 12, false);
      //add the key/id
      testDN=DN.valueOf(noParentDN);
      id=new EntryID(12);
      assertTrue(dn2id.insert(txn, testDN, id));
      performBECompleteVerify("dn2id", 3);
    }
    finally
    {
      eContainer.sharedLock.unlock();
    }
  }
 
  /**
   *
   * Runs complete verify against the id2children index
   * after adding various errors in the id2children file.
   *
   * @throws Exception if the error count is not equal to 3.
   */
  @Test
  public void testVerifyID2Children() throws Exception {
    preTest(9);
    eContainer.sharedLock.lock();
    try
    {
      //Add dn with no parent
      DatabaseEntry key=addID2EntryReturnKey(noParentDN, 10, false);
      byte[] idBytes=new byte[16];
      idBytes[7]=(byte) 0x0A;
      EntryIDSet idSet = new EntryIDSet(null, idBytes);
      id2child.writeKey(txn, key, idSet);
      //Add child entry - don't worry about key
      addID2EntryReturnKey(cDN, 11, false);
      //Add its parent entry -- need the key
      DatabaseEntry keyp=addID2EntryReturnKey(pDN, 12, false);
      //add parent key/IDSet with bad IDset id
      byte[] idBytesp=new byte[16];
      idBytesp[7]=(byte) 0xFF;
      EntryIDSet idSetp = new EntryIDSet(null, idBytesp);
      id2child.writeKey(txn, keyp, idSetp);
      performBECompleteVerify("id2children", 3);
    }
    finally
    {
      eContainer.sharedLock.unlock();
    }
  }
 
  /**
   *
   * Runs complete verify against the id2children index
   * after adding various errors in the id2children file.
   * This is a second test because the key needed to have
   * null idlist. This test is really just for coverage and
   * should have a 0 error count.
   *
   * @throws Exception if the error count is not equal to 0.
   */
  @Test
  public void testVerifyID2Children1() throws Exception {
    preTest(2);
    eContainer.sharedLock.lock();
    try
    {
      //Add child entry - don't worry about key
      addID2EntryReturnKey(pDN, 10, false);
      //add parent key/IDSet with null keyset
      EntryIDSet idSetp=new EntryIDSet();
      DatabaseEntry key= new EntryID(2).getDatabaseEntry();
      id2child.writeKey(txn, key, idSetp);
      performBECompleteVerify("id2children", 0);
    }
    finally
    {
      eContainer.sharedLock.unlock();
    }
  }
 
  /**
   *
   * Runs complete verify against the id2subtree index
   * after adding various errors in the id2subtree file.
   *
   * @throws Exception if the error count is not equal to 3.
   */
  @Test
  public void testVerifyID2Subtree() throws Exception {
    preTest(2);
    eContainer.sharedLock.lock();
    try
    {
      //Add entry with no parent
      addID2EntryReturnKey(noParentDN, 3, false);
      performBECompleteVerify("id2subtree", 3);
    }
    finally
    {
      eContainer.sharedLock.unlock();
    }
  }
 
  /**
   *
   * Runs complete verify against the id2subtree index
   * after adding various errors in the id2subtree file.
   * This is a second test because the key needed to have
   * null idlist.
   *
   * @throws Exception if the error count is not equal to 1.
   */
  @Test
  public void testVerifyID2Subtree1() throws Exception {
    preTest(2);
    eContainer.sharedLock.lock();
    try
    {
      //Add child entry - don't worry about key
      addID2EntryReturnKey(pDN, 3, false);
      //add parent key/IDSet with null keyset
      EntryIDSet idSet=new EntryIDSet();
      DatabaseEntry key= new EntryID(2).getDatabaseEntry();
      id2subtree.writeKey(txn, key, idSet);
      performBECompleteVerify("id2subtree", 1);
    }
    finally
    {
      eContainer.sharedLock.unlock();
    }
  }
 
  /**
   * Runs complete verify against the mail indexes
   * (equality, presence, substring, ordering)
   * after adding various errors to each of these index files.
   * @throws Exception if the error count is not equal to 6.
   */
  @Test
  public void testVerifyAttribute() throws Exception {
    String mailType="mail";
    preTest(4);
    eContainer.sharedLock.lock();
    try
    {
      AttributeType attributeType =
          DirectoryServer.getAttributeType(mailType);
      //Get db handles to each index.
      AttributeIndex attributeIndex = eContainer.getAttributeIndex(attributeType);
      Index eqIndex = attributeIndex.getEqualityIndex();
      Index presIndex = attributeIndex.getPresenceIndex();
      Index subIndex = attributeIndex.getSubstringIndex();
      Index ordIndex = attributeIndex.getOrderingIndex();
      //Add invalid idlist ids to both equality and ordering indexes.
      DatabaseEntry key=
           new DatabaseEntry(StaticUtils.getBytes("user.0@example.com"));
      byte[] dataBytes=new byte[16];
      //put duplicate ids in list
      dataBytes[7] = (byte)0xff;
      dataBytes[15] = (byte)0xfe;
      DatabaseEntry data= new DatabaseEntry(dataBytes);
      OperationStatus status = eqIndex.put(txn, key, data);
      assertEquals(status, OperationStatus.SUCCESS);
      status = ordIndex.put(txn, key, data);
      assertEquals(status, OperationStatus.SUCCESS);
      //Add null idlist to both equality and ordering indexes.
      key = new DatabaseEntry(StaticUtils.getBytes("user.1@example.com"));
      data= new DatabaseEntry(new EntryIDSet().toDatabase());
      status = eqIndex.put(txn, key, data);
      assertEquals(status, OperationStatus.SUCCESS);
      status = ordIndex.put(txn, key, data);
      assertEquals(status, OperationStatus.SUCCESS);
      //Add invalid idlist ids to presence index.
      key = new DatabaseEntry(StaticUtils.getBytes("+"));
      data = new DatabaseEntry(dataBytes);
      status = presIndex.put(txn, key, data);
      assertEquals(status, OperationStatus.SUCCESS);
      //Add invalid idlist ids to substring index.
      key = new DatabaseEntry(StaticUtils.getBytes("@examp"));
      data = new DatabaseEntry(dataBytes);
      status = subIndex.put(txn, key, data);
      assertEquals(status, OperationStatus.SUCCESS);
      performBECompleteVerify(mailType, 6);
    }
    finally
    {
      eContainer.sharedLock.unlock();
    }
  }
 
  /**
   * Runs complete verify against the testvlvindex VLV index
   * after adding various errors to each of these index files.
   * @throws Exception if the error count is not equal to 6.
   */
  @Test
  public void testVerifyVLV() throws Exception {
    String indexName = "testvlvindex";
    preTest(4);
    eContainer.sharedLock.lock();
    try
    {
      VLVIndex vlvIndex = eContainer.getVLVIndex(indexName);
      AttributeType[] types = vlvIndex.getSortTypes();
 
      // Remove an ID
      SortValuesSet svs = vlvIndex.getSortValuesSet(null, 0, new ByteString[3], types);
      long id = svs.getEntryIDs()[0];
      Entry entry = eContainer.getID2Entry().get(null, new EntryID(id), LockMode.DEFAULT);
      remove(svs, id, vlvIndex.getSortValues(entry));
 
      // Add an incorrectly ordered values.
      SortValuesSet svs2 = svs.split(2);
      svs2.add(1000, vlvIndex.getSortValues(entry), types);
 
      // Muck up the values of another ID
      id = svs.getEntryIDs()[0];
      entry = eContainer.getID2Entry().get(null, new EntryID(id), LockMode.DEFAULT);
      ByteString[] values = vlvIndex.getSortValues(entry);
      ByteString[] badValues = new ByteString[values.length];
      System.arraycopy(values, 1, badValues, 0, values.length - 1);
      badValues[badValues.length-1] = values[0];
      remove(svs, id, values);
      svs.add(id, badValues, types);
 
      putSortValuesSet(vlvIndex, svs);
      putSortValuesSet(vlvIndex, svs2);
      performBECompleteVerify("vlv." + indexName, 3);
    }
    finally
    {
      eContainer.sharedLock.unlock();
    }
  }
 
  private void remove(SortValuesSet svs, long id, ByteString[] values) throws DirectoryException
  {
    svs.remove(new SortValues(new EntryID(id), values, new SortOrder()));
  }
 
  /**
   * Put a sort values set in this VLV index.
   *
   * @param txn
   *          The transaction to use when retrieving the set or NULL if it is
   *          not required.
   * @param sortValuesSet
   *          The SortValuesSet to put.
   * @return True if the sortValuesSet was put successfully or False otherwise.
   * @throws JebException
   *           If an error occurs during an operation on a JE database.
   * @throws DatabaseException
   *           If an error occurs during an operation on a JE database.
   * @throws DirectoryException
   *           If a Directory Server error occurs.
   */
  private void putSortValuesSet(VLVIndex vlvIndex, SortValuesSet sortValuesSet) throws JebException, DirectoryException
  {
    DatabaseEntry key = new DatabaseEntry(sortValuesSet.getKeyBytes());
    DatabaseEntry data = new DatabaseEntry(sortValuesSet.toDatabase());
    vlvIndex.put(null, key, data);
  }
 
  /* Various tests not either clean or complete */
 
 
  /**
   * Try to verify a non-indexed attribute.
   * @throws Exception if error count is not equal to 0.
   */
  @Test(expectedExceptions=Exception.class)
  public void testVerifyNotIndexed()  throws Exception {
    cleanAndLoad(2);
    VerifyConfig verifyConfig = new VerifyConfig();
    verifyConfig.setBaseDN(baseDNs[0]);
    verifyConfig.addCleanIndex("userPassword");
    backend = DirectoryServer.getBackend(backendID);
    assertEquals(backend.verifyBackend(verifyConfig), 0);
  }
 
  /**
   * Try to verify an nonexistent attribute.
   * @throws Exception if verify backend fails.
   */
  @Test(expectedExceptions=Exception.class)
  public void testInvalidIndex()  throws Exception {
    cleanAndLoad(2);
    VerifyConfig verifyConfig = new VerifyConfig();
    verifyConfig.setBaseDN(baseDNs[0]);
    verifyConfig.addCleanIndex(badIndexName);
    backend = DirectoryServer.getBackend(backendID);
    backend.verifyBackend(verifyConfig);
  }
 
  /* end tests */
 
  /**
   * Adds an entry to the id2entry database with a dn and id passed into the
   * method. Optional flag to set the Jeb version byte for those types of tests.
   * @param dn the dn string to put in the entry.
   * @param id to use as the id2entry key,
   * @param trashFormat true if first byte should be changed to invalid value.
   * @return Database entry key of the entry.
   * @throws Exception if the entry is not added to the id2entry database.
   */
  private DatabaseEntry addID2EntryReturnKey(String dn, long id, boolean trashFormat)
       throws Exception {
    DatabaseEntry key= new EntryID(id).getDatabaseEntry();
    Entry testEntry = buildEntry(dn);
    DataConfig dataConfig = new DataConfig(false, false, null);
    byte []entryBytes = ID2Entry.entryToDatabase(testEntry, dataConfig).toByteArray();
    if(trashFormat)
    {
      entryBytes[0] = 0x67;
    }
    DatabaseEntry data= new DatabaseEntry(entryBytes);
    assertEquals(id2entry.put(txn, key, data), OperationStatus.SUCCESS);
    return key;
  }
 
  /**
   * Wrapper to do a clean verify.
   * @param indexToDo index file to run verify against.
   * @param expectedErrors number of errors expected for this test.
   * @throws Exception if the verify fails.
   */
  private void performBECleanVerify(String indexToDo,
                                    int expectedErrors) throws Exception {
    performBEVerify(indexToDo, expectedErrors, true);
  }
 
  /**
   * Wrapper to do a complete verify.
   * @param indexToDo index file to run verify against.
   * @param expectedErrors number of errors expected for this test.
   * @throws Exception if the verify fails.
   */
  private void performBECompleteVerify(String indexToDo,
                                       int expectedErrors) throws Exception {
    performBEVerify(indexToDo, expectedErrors, false);
  }
 
  /**
   * Performs either a clean or complete verify depending on
   * flag passed in.
   *
   * @param indexToDo index file to run verify against.
   * @param expectedErrors number of errors expected for this test.
   * @param clean do clean verify if true.
   * @throws Exception if the verify fails.
   */
  private void performBEVerify(String indexToDo,
                               int expectedErrors, boolean clean) throws Exception {
    EntryContainer.transactionCommit(txn);
    VerifyConfig verifyConfig = new VerifyConfig();
    verifyConfig.setBaseDN(baseDNs[0]);
    if(!clean)
    {
      verifyConfig.addCompleteIndex(indexToDo);
    }
    else
    {
      verifyConfig.addCleanIndex(indexToDo);
    }
    assertEquals(backend.verifyBackend(verifyConfig), expectedErrors);
  }
 
 
  /**
   * Does a pretest setup. Creates some number of entries, gets
   * backend, rootcontainer, entryContainer objects, as well as
   * various index objects.
   * Also starts a transaction.
   * @param numEntries number of entries to add to the verify backend.
   * @throws Exception if entries cannot be loaded.
   */
  private void preTest(int numEntries) throws Exception {
    cleanAndLoad(numEntries);
    backend = DirectoryServer.getBackend(backendID);
    RootContainer rContainer = ((BackendImpl) backend).getRootContainer();
    eContainer= rContainer.getEntryContainer(DN.valueOf(suffix));
    id2child=eContainer.getID2Children();
    id2entry=eContainer.getID2Entry();
    id2subtree=eContainer.getID2Subtree();
    dn2id=eContainer.getDN2ID();
    txn = eContainer.beginTransaction();
  }
 
  /**
   * Cleans verify backend and loads some number of entries.
   * @param numEntries number of entries to load into the backend.
   * @throws Exception if the entries are not loaded or created.
   */
  private void cleanAndLoad(int numEntries) throws Exception {
    TestCaseUtils.clearJEBackend(backendID);
    template[2]=numUsersLine;
    template[2]=
         template[2].replaceAll("#numEntries#", String.valueOf(numEntries));
    createLoadEntries(template, numEntries);
  }
 
  /**
   * Builds an entry.
   *
   * @param dn to put into the entry.
   * @return a new entry.
   * @throws DirectoryException if the entry cannot be created.
   */
  private Entry buildEntry(String dn) throws DirectoryException {
    DN entryDN = DN.valueOf(dn);
    HashMap<ObjectClass, String> ocs = new HashMap<ObjectClass, String>(2);
    ObjectClass topOC = DirectoryServer.getObjectClass(OC_TOP);
    if (topOC == null) {
      topOC = DirectoryServer.getDefaultObjectClass(OC_TOP);
    }
    ocs.put(topOC, OC_TOP);
    ObjectClass extensibleObjectOC = DirectoryServer
         .getObjectClass(OC_EXTENSIBLE_OBJECT);
    if (extensibleObjectOC == null) {
      extensibleObjectOC = DirectoryServer
           .getDefaultObjectClass(OC_EXTENSIBLE_OBJECT);
    }
    ocs.put(extensibleObjectOC, OC_EXTENSIBLE_OBJECT);
    return new Entry(entryDN, ocs,
                     new LinkedHashMap<AttributeType, List<Attribute>>(0),
                     new HashMap<AttributeType, List<Attribute>>(0));
  }
}