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

Nicolas Capponi
05.58.2016 ed0ae491be5928897b1e8bd5b41d0426dbd08081
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
/*
 * The contents of this file are subject to the terms of the Common Development and
 * Distribution License (the License). You may not use this file except in compliance with the
 * License.
 *
 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
 * specific language governing permission and limitations under the License.
 *
 * When distributing Covered Software, include this CDDL Header Notice in each file and include
 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
 * Header, with the fields enclosed by brackets [] replaced by your own identifying
 * information: "Portions Copyright [year] [name of copyright owner]".
 *
 * Copyright 2006-2008 Sun Microsystems, Inc.
 * Portions Copyright 2013-2016 ForgeRock AS.
 */
package org.opends.server.tools;
 
import static com.forgerock.opendj.cli.ArgumentConstants.*;
import static com.forgerock.opendj.cli.Utils.*;
import static com.forgerock.opendj.cli.CommonArguments.*;
 
import static org.opends.messages.ToolMessages.*;
import static org.opends.server.util.CollectionUtils.*;
import static org.opends.server.protocols.ldap.LDAPResultCode.*;
import static org.opends.server.util.StaticUtils.*;
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
 
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.SearchScope;
import org.opends.server.core.DirectoryServer;
import org.opends.server.core.DirectoryServer.DirectoryServerVersionHandler;
import org.opends.server.loggers.JDKLogging;
import org.opends.server.protocols.ldap.LDAPResultCode;
import org.forgerock.opendj.ldap.schema.AttributeType;
import org.forgerock.opendj.ldap.schema.ObjectClass;
import org.opends.server.types.*;
import org.opends.server.util.BuildVersion;
import org.opends.server.util.LDIFException;
import org.opends.server.util.LDIFReader;
import org.opends.server.util.LDIFWriter;
 
import com.forgerock.opendj.cli.*;
 
/**
 * This class provides a program that may be used to search LDIF files.  It is
 * modeled after the LDAPSearch tool, with the primary differencing being that
 * all of its data comes from LDIF rather than communicating over LDAP.
 * However, it does have a number of differences that allow it to perform
 * multiple operations in a single pass rather than requiring multiple passes
 * through the LDIF.
 */
public class LDIFSearch
{
  /** The fully-qualified name of this class. */
  private static final String CLASS_NAME = "org.opends.server.tools.LDIFSearch";
 
  /** The search scope string that will be used for baseObject searches. */
  private static final String SCOPE_STRING_BASE = "base";
  /** The search scope string that will be used for singleLevel searches. */
  private static final String SCOPE_STRING_ONE = "one";
  /** The search scope string that will be used for wholeSubtree searches. */
  private static final String SCOPE_STRING_SUB = "sub";
  /** The search scope string that will be used for subordinateSubtree searches. */
  private static final String SCOPE_STRING_SUBORDINATE = "subordinate";
 
  /**
   * Provides the command line arguments to the <CODE>mainSearch</CODE> method
   * so that they can be processed.
   *
   * @param  args  The command line arguments provided to this program.
   */
  public static void main(String[] args)
  {
    int exitCode = mainSearch(args, true, System.out, System.err);
    if (exitCode != 0)
    {
      System.exit(filterExitCode(exitCode));
    }
  }
 
 
 
  /**
   * Parses the provided command line arguments and performs the appropriate
   * search operation.
   *
   * @param  args              The command line arguments provided to this
   *                           program.
   * @param  initializeServer  True if server initialization should be done.
   * @param  outStream         The output stream to use for standard output, or
   *                           {@code null} if standard output is not needed.
   * @param  errStream         The output stream to use for standard error, or
   *                           {@code null} if standard error is not needed.
   *
   * @return  The return code for this operation.  A value of zero indicates
   *          that all processing completed successfully.  A nonzero value
   *          indicates that some problem occurred during processing.
   */
  public static int mainSearch(String[] args, boolean initializeServer,
                               OutputStream outStream, OutputStream errStream)
  {
    PrintStream out = NullOutputStream.wrapOrNullStream(outStream);
    PrintStream err = NullOutputStream.wrapOrNullStream(errStream);
    JDKLogging.disableLogging();
 
    LinkedHashSet<String> scopeStrings = new LinkedHashSet<>(4);
    scopeStrings.add(SCOPE_STRING_BASE);
    scopeStrings.add(SCOPE_STRING_ONE);
    scopeStrings.add(SCOPE_STRING_SUB);
    scopeStrings.add(SCOPE_STRING_SUBORDINATE);
 
 
    BooleanArgument     dontWrap;
    BooleanArgument     overwriteExisting;
    BooleanArgument     showUsage;
    StringArgument      filterFile;
    IntegerArgument     sizeLimit;
    IntegerArgument     timeLimit;
    MultiChoiceArgument<String> scopeString;
    StringArgument      baseDNString;
    StringArgument      configFile;
    StringArgument      ldifFile;
    StringArgument      outputFile;
 
 
    LocalizableMessage toolDescription = INFO_LDIFSEARCH_TOOL_DESCRIPTION.get();
    ArgumentParser argParser = new ArgumentParser(CLASS_NAME, toolDescription,
                                                  false, true, 0, 0,
                                                  "[filter] [attributes ...]");
    argParser.setShortToolDescription(REF_SHORT_DESC_LDIFSEARCH.get());
    argParser.setVersionHandler(new DirectoryServerVersionHandler());
 
    try
    {
      ldifFile =
              StringArgument.builder("ldifFile")
                      .shortIdentifier('l')
                      .description(INFO_LDIFSEARCH_DESCRIPTION_LDIF_FILE.get())
                      .multiValued()
                      .valuePlaceholder(INFO_LDIFFILE_PLACEHOLDER.get())
                      .buildAndAddToParser(argParser);
      baseDNString =
              StringArgument.builder(OPTION_LONG_BASEDN)
                      .shortIdentifier(OPTION_SHORT_BASEDN)
                      .description(INFO_LDIFSEARCH_DESCRIPTION_BASEDN.get())
                      .multiValued()
                      .defaultValue("")
                      .valuePlaceholder(INFO_BASEDN_PLACEHOLDER.get())
                      .buildAndAddToParser(argParser);
      scopeString =
              MultiChoiceArgument.<String>builder("searchScope")
                      .shortIdentifier('s')
                      .description(INFO_LDIFSEARCH_DESCRIPTION_SCOPE.get())
                      .allowedValues(scopeStrings)
                      .defaultValue(SCOPE_STRING_SUB)
                      .valuePlaceholder(INFO_SCOPE_PLACEHOLDER.get())
                      .buildAndAddToParser(argParser);
      configFile =
              StringArgument.builder("configFile")
                      .shortIdentifier('c')
                      .description(INFO_DESCRIPTION_CONFIG_FILE.get())
                      .hidden()
                      .valuePlaceholder(INFO_CONFIGFILE_PLACEHOLDER.get())
                      .buildAndAddToParser(argParser);
      filterFile =
              StringArgument.builder("filterFile")
                      .shortIdentifier('f')
                      .description(INFO_LDIFSEARCH_DESCRIPTION_FILTER_FILE.get())
                      .valuePlaceholder(INFO_FILTER_FILE_PLACEHOLDER.get())
                      .buildAndAddToParser(argParser);
      outputFile =
              StringArgument.builder("outputFile")
                      .shortIdentifier('o')
                      .description(INFO_LDIFSEARCH_DESCRIPTION_OUTPUT_FILE.get())
                      .valuePlaceholder(INFO_OUTPUT_FILE_PLACEHOLDER.get())
                      .buildAndAddToParser(argParser);
      overwriteExisting =
              BooleanArgument.builder("overwriteExisting")
                      .shortIdentifier('O')
                      .description(INFO_LDIFSEARCH_DESCRIPTION_OVERWRITE_EXISTING.get())
                      .buildAndAddToParser(argParser);
      dontWrap =
              BooleanArgument.builder("dontWrap")
                      .shortIdentifier('T')
                      .description(INFO_LDIFSEARCH_DESCRIPTION_DONT_WRAP.get())
                      .buildAndAddToParser(argParser);
      sizeLimit =
              IntegerArgument.builder("sizeLimit")
                      .shortIdentifier('z')
                      .description(INFO_LDIFSEARCH_DESCRIPTION_SIZE_LIMIT.get())
                      .lowerBound(0)
                      .defaultValue(0)
                      .valuePlaceholder(INFO_SIZE_LIMIT_PLACEHOLDER.get())
                      .buildAndAddToParser(argParser);
      timeLimit =
              IntegerArgument.builder("timeLimit")
                      .shortIdentifier('t')
                      .description(INFO_LDIFSEARCH_DESCRIPTION_TIME_LIMIT.get())
                      .lowerBound(0)
                      .defaultValue(0)
                      .valuePlaceholder(INFO_TIME_LIMIT_PLACEHOLDER.get())
                      .buildAndAddToParser(argParser);
 
      showUsage = showUsageArgument();
      argParser.addArgument(showUsage);
      argParser.setUsageArgument(showUsage);
    }
    catch (ArgumentException ae)
    {
      printWrappedText(err, ERR_CANNOT_INITIALIZE_ARGS.get(ae.getMessage()));
      return 1;
    }
 
 
    // Parse the command-line arguments provided to the program.
    try
    {
      argParser.parseArguments(args);
    }
    catch (ArgumentException ae)
    {
      argParser.displayMessageAndUsageReference(err, ERR_ERROR_PARSING_ARGS.get(ae.getMessage()));
      return CLIENT_SIDE_PARAM_ERROR;
    }
 
 
    // If we should just display usage or version information,
    // then print it and exit.
    if (argParser.usageOrVersionDisplayed())
    {
      return 0;
    }
 
    // Checks the version - if upgrade required, the tool is unusable
    try
    {
      BuildVersion.checkVersionMismatch();
    }
    catch (InitializationException e)
    {
      printWrappedText(err, e.getMessage());
      return 1;
    }
 
    // Make sure that at least one filter was provided.  Also get the attribute
    // list at the same time because it may need to be specified in the same
    // way.
    boolean            allUserAttrs        = false;
    boolean            allOperationalAttrs = false;
    //Return objectclass attribute unless analysis of the arguments determines
    //otherwise.
    boolean            includeObjectclassAttrs = true;
    final LinkedList<String> attributeNames = new LinkedList<>();
    LinkedList<String> objectClassNames = new LinkedList<>();
    LinkedList<String> filterStrings = new LinkedList<>();
    if (filterFile.isPresent())
    {
      BufferedReader in = null;
      try
      {
        String fileNameValue = filterFile.getValue();
        in = new BufferedReader(new FileReader(fileNameValue));
        String line = null;
 
        while ((line = in.readLine()) != null)
        {
          if(line.trim().equals(""))
          {
            // ignore empty lines.
            continue;
          }
          filterStrings.add(line);
        }
      } catch(Exception e)
      {
        printWrappedText(err, e.getMessage());
        return 1;
      }
      finally
      {
        close(in);
      }
 
      ArrayList<String> trailingArguments = argParser.getTrailingArguments();
      if (trailingArguments != null && !trailingArguments.isEmpty())
      {
        for (String attributeName : trailingArguments)
        {
          String lowerName = toLowerCase(attributeName);
          if (lowerName.equals("*"))
          {
            allUserAttrs = true;
          }
          else if (lowerName.equals("+"))
          {
            allOperationalAttrs = true;
          }
          else if (lowerName.startsWith("@"))
          {
            objectClassNames.add(lowerName.substring(1));
          }
          else
          {
            attributeNames.add(lowerName);
          }
        }
      }
    }
    else
    {
      ArrayList<String> trailingArguments = argParser.getTrailingArguments();
      if (trailingArguments == null || trailingArguments.isEmpty())
      {
        argParser.displayMessageAndUsageReference(err, ERR_LDIFSEARCH_NO_FILTER.get());
        return 1;
      }
 
      Iterator<String> iterator = trailingArguments.iterator();
      filterStrings = newLinkedList(iterator.next());
 
      while (iterator.hasNext())
      {
        String lowerName = toLowerCase(iterator.next());
        if (lowerName.equals("*"))
        {
          allUserAttrs = true;
        }
        else if (lowerName.equals("+"))
        {
          allOperationalAttrs = true;
        }
        else if (lowerName.startsWith("@"))
        {
          objectClassNames.add(lowerName.substring(1));
        }
        else
        {
          attributeNames.add(lowerName);
        }
      }
    }
 
    if (attributeNames.isEmpty()
        && objectClassNames.isEmpty()
        && !allOperationalAttrs)
    {
      // This will be true if no attributes were requested, which is effectively
      // all user attributes.  It will also be true if just "*" was included,
      // but the net result will be the same.
      allUserAttrs = true;
    }
 
    //Determine if objectclass attribute should be returned.
    if(!allUserAttrs) {
      //Single '+', never return objectclass.
      if(allOperationalAttrs && objectClassNames.isEmpty() &&
         attributeNames.isEmpty())
      {
        includeObjectclassAttrs=false;
      }
      //If "objectclass" isn't specified in the attributes to return, then
      //don't include objectclass attribute.
      if(!attributeNames.isEmpty() && objectClassNames.isEmpty() &&
         !attributeNames.contains("objectclass"))
      {
        includeObjectclassAttrs=false;
      }
    }
 
 
    // Bootstrap the Directory Server configuration for use as a client.
    DirectoryServer directoryServer = DirectoryServer.getInstance();
 
    // If we're to use the configuration then initialize it, along with the
    // schema.
    boolean checkSchema = configFile.isPresent();
 
    if (initializeServer)
    {
      DirectoryServer.bootstrapClient();
 
      if (checkSchema)
      {
        try
        {
          DirectoryServer.initializeJMX();
        }
        catch (Exception e)
        {
          printWrappedText(err, ERR_LDIFSEARCH_CANNOT_INITIALIZE_JMX.get(configFile.getValue(), e.getMessage()));
          return 1;
        }
 
        try
        {
          directoryServer.initializeConfiguration(configFile.getValue());
        }
        catch (Exception e)
        {
          printWrappedText(err, ERR_LDIFSEARCH_CANNOT_INITIALIZE_CONFIG.get(configFile.getValue(), e.getMessage()));
          return 1;
        }
 
        try
        {
          directoryServer.initializeSchema();
        }
        catch (Exception e)
        {
          printWrappedText(err, ERR_LDIFSEARCH_CANNOT_INITIALIZE_SCHEMA.get(configFile.getValue(), e.getMessage()));
          return 1;
        }
      }
    }
 
    // Choose the desired search scope.
    SearchScope searchScope;
    if (scopeString.isPresent())
    {
      String scopeStr = toLowerCase(scopeString.getValue());
      if (scopeStr.equals(SCOPE_STRING_BASE))
      {
        searchScope = SearchScope.BASE_OBJECT;
      }
      else if (scopeStr.equals(SCOPE_STRING_ONE))
      {
        searchScope = SearchScope.SINGLE_LEVEL;
      }
      else if (scopeStr.equals(SCOPE_STRING_SUBORDINATE))
      {
        searchScope = SearchScope.SUBORDINATES;
      }
      else
      {
        searchScope = SearchScope.WHOLE_SUBTREE;
      }
    }
    else
    {
      searchScope = SearchScope.WHOLE_SUBTREE;
    }
 
 
    // Create the list of filters that will be used to process the searches.
    LinkedList<SearchFilter> searchFilters = new LinkedList<>();
    for (String filterString : filterStrings)
    {
      try
      {
        searchFilters.add(SearchFilter.createFilterFromString(filterString));
      }
      catch (Exception e)
      {
        printWrappedText(err, ERR_LDIFSEARCH_CANNOT_PARSE_FILTER.get(filterString, e.getMessage()));
        return 1;
      }
    }
 
 
    // Transform the attributes to return from strings to attribute types.
    LinkedHashSet<AttributeType> userAttributeTypes = new LinkedHashSet<>();
    LinkedHashSet<AttributeType> operationalAttributeTypes = new LinkedHashSet<>();
    for (String attributeName : attributeNames)
    {
      AttributeType t = DirectoryServer.getSchema().getAttributeType(attributeName);
      if (t.isOperational())
      {
        operationalAttributeTypes.add(t);
      }
      else
      {
        userAttributeTypes.add(t);
      }
    }
 
    for (String objectClassName : objectClassNames)
    {
      ObjectClass c = DirectoryServer.getSchema().getObjectClass(objectClassName);
      for (AttributeType t : c.getRequiredAttributes())
      {
        if (t.isOperational())
        {
          operationalAttributeTypes.add(t);
        }
        else
        {
          userAttributeTypes.add(t);
        }
      }
 
      for (AttributeType t : c.getOptionalAttributes())
      {
        if (t.isOperational())
        {
          operationalAttributeTypes.add(t);
        }
        else
        {
          userAttributeTypes.add(t);
        }
      }
    }
 
 
    // Set the base DNs for the import config.
    LinkedList<DN> baseDNs = new LinkedList<>();
    if (baseDNString.isPresent())
    {
      for (String dnString : baseDNString.getValues())
      {
        try
        {
          baseDNs.add(DN.valueOf(dnString));
        }
        catch (Exception e)
        {
          printWrappedText(err, ERR_LDIFSEARCH_CANNOT_PARSE_BASE_DN.get(dnString, e.getMessage()));
          return 1;
        }
      }
    }
    else
    {
      baseDNs.add(DN.rootDN());
    }
 
 
    // Get the time limit in milliseconds.
    long timeLimitMillis;
    try
    {
      if (timeLimit.isPresent())
      {
        timeLimitMillis = 1000L * timeLimit.getIntValue();
      }
      else
      {
        timeLimitMillis = 0;
      }
    }
    catch (Exception e)
    {
      printWrappedText(err, ERR_LDIFSEARCH_CANNOT_PARSE_TIME_LIMIT.get(e));
      return 1;
    }
 
 
    // Convert the size limit to an integer.
    int sizeLimitValue;
    try
    {
      if (sizeLimit.isPresent())
      {
        sizeLimitValue = sizeLimit.getIntValue();
      }
      else
      {
        sizeLimitValue =0;
      }
    }
    catch (Exception e)
    {
      printWrappedText(err, ERR_LDIFSEARCH_CANNOT_PARSE_SIZE_LIMIT.get(e));
      return 1;
    }
 
 
    // Create the LDIF import configuration that will be used to read the source
    // data.
    LDIFImportConfig importConfig;
    if (ldifFile.isPresent())
    {
      importConfig = new LDIFImportConfig(ldifFile.getValues());
    }
    else
    {
      importConfig = new LDIFImportConfig(System.in);
    }
 
 
    // Create the LDIF export configuration that will be used to write the
    // matching entries.
    LDIFExportConfig exportConfig;
    if (outputFile.isPresent())
    {
      if (overwriteExisting.isPresent())
      {
        exportConfig = new LDIFExportConfig(outputFile.getValue(),
                                            ExistingFileBehavior.OVERWRITE);
      }
      else
      {
        exportConfig = new LDIFExportConfig(outputFile.getValue(),
                                            ExistingFileBehavior.APPEND);
      }
    }
    else
    {
      exportConfig = new LDIFExportConfig(out);
    }
 
    exportConfig.setIncludeObjectClasses(includeObjectclassAttrs);
    if (dontWrap.isPresent())
    {
      exportConfig.setWrapColumn(0);
    }
    else
    {
      exportConfig.setWrapColumn(75);
    }
 
 
    // Create the LDIF reader/writer from the import/export config.
    LDIFReader reader;
    LDIFWriter writer;
    try
    {
      reader = new LDIFReader(importConfig);
    }
    catch (Exception e)
    {
      printWrappedText(err, ERR_LDIFSEARCH_CANNOT_CREATE_READER.get(e));
      return 1;
    }
 
    try
    {
      writer = new LDIFWriter(exportConfig);
    }
    catch (Exception e)
    {
      close(reader);
      printWrappedText(err, ERR_LDIFSEARCH_CANNOT_CREATE_WRITER.get(e));
      return 1;
    }
 
 
    // Start reading data from the LDIF reader.
    long startTime  = System.currentTimeMillis();
    long stopTime   = startTime + timeLimitMillis;
    long matchCount = 0;
    int  resultCode = LDAPResultCode.SUCCESS;
    while (true)
    {
      // If the time limit has been reached, then stop now.
      if (timeLimitMillis > 0 && System.currentTimeMillis() > stopTime)
      {
        resultCode = LDAPResultCode.TIME_LIMIT_EXCEEDED;
 
        LocalizableMessage message = WARN_LDIFSEARCH_TIME_LIMIT_EXCEEDED.get();
        err.println(message);
        break;
      }
 
 
      try
      {
        Entry entry = reader.readEntry(checkSchema);
        if (entry == null)
        {
          break;
        }
 
 
        // Check to see if the entry has an acceptable base and scope.
        boolean matchesBaseAndScope = false;
        for (DN baseDN : baseDNs)
        {
          if (entry.matchesBaseAndScope(baseDN, searchScope))
          {
            matchesBaseAndScope = true;
            break;
          }
        }
 
        if (! matchesBaseAndScope)
        {
          continue;
        }
 
 
        // Check to see if the entry matches any of the filters.
        boolean matchesFilter = false;
        for (SearchFilter filter : searchFilters)
        {
          if (filter.matchesEntry(entry))
          {
            matchesFilter = true;
            break;
          }
        }
 
        if (! matchesFilter)
        {
          continue;
        }
 
 
        // Prepare the entry to return to the client.
        if (! allUserAttrs)
        {
          Iterator<AttributeType> iterator =
               entry.getUserAttributes().keySet().iterator();
          while (iterator.hasNext())
          {
            if (! userAttributeTypes.contains(iterator.next()))
            {
              iterator.remove();
            }
          }
        }
 
        if (! allOperationalAttrs)
        {
          Iterator<AttributeType> iterator =
               entry.getOperationalAttributes().keySet().iterator();
          while (iterator.hasNext())
          {
            if (! operationalAttributeTypes.contains(iterator.next()))
            {
              iterator.remove();
            }
          }
        }
 
 
        // Write the entry to the client and increase the count.
        // FIXME -- Should we include a comment about which base+filter matched?
        writer.writeEntry(entry);
        writer.flush();
 
        matchCount++;
        if (sizeLimitValue > 0 && matchCount >= sizeLimitValue)
        {
          resultCode = LDAPResultCode.SIZE_LIMIT_EXCEEDED;
 
          LocalizableMessage message = WARN_LDIFSEARCH_SIZE_LIMIT_EXCEEDED.get();
          err.println(message);
          break;
        }
      }
      catch (LDIFException le)
      {
        if (le.canContinueReading())
        {
          LocalizableMessage message = ERR_LDIFSEARCH_CANNOT_READ_ENTRY_RECOVERABLE.get(
                  le.getMessage());
          err.println(message);
        }
        else
        {
          LocalizableMessage message = ERR_LDIFSEARCH_CANNOT_READ_ENTRY_FATAL.get(
                  le.getMessage());
          err.println(message);
          resultCode = LDAPResultCode.CLIENT_SIDE_LOCAL_ERROR;
          break;
        }
      }
      catch (Exception e)
      {
        err.println(ERR_LDIFSEARCH_ERROR_DURING_PROCESSING.get(e));
        resultCode = LDAPResultCode.CLIENT_SIDE_LOCAL_ERROR;
        break;
      }
    }
 
    close(reader, writer);
 
    return resultCode;
  }
}