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

Jean-Noel Rouvignac
09.01.2015 5cd7bdbbda0fa9f1aa6e12d9171c3811b73feb07
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
/*
 * 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-2008 Sun Microsystems, Inc.
 *      Portions Copyright 2014-2015 ForgeRock AS
 */
package org.opends.server.backends;
 
import static org.forgerock.util.Reject.*;
import static org.opends.messages.BackendMessages.*;
import static org.opends.server.config.ConfigConstants.*;
import static org.opends.server.schema.BooleanSyntax.*;
import static org.opends.server.util.ServerConstants.*;
import static org.opends.server.util.StaticUtils.*;
 
import java.io.File;
import java.io.IOException;
import java.util.*;
 
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.forgerock.opendj.config.server.ConfigChangeResult;
import org.forgerock.opendj.config.server.ConfigException;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ConditionResult;
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.SearchScope;
import org.opends.server.admin.server.ConfigurationChangeListener;
import org.opends.server.admin.std.server.BackupBackendCfg;
import org.opends.server.api.Backend;
import org.opends.server.core.AddOperation;
import org.opends.server.core.DeleteOperation;
import org.opends.server.core.DirectoryServer;
import org.opends.server.core.ModifyDNOperation;
import org.opends.server.core.ModifyOperation;
import org.opends.server.core.SearchOperation;
import org.opends.server.core.ServerContext;
import org.opends.server.schema.GeneralizedTimeSyntax;
import org.opends.server.types.*;
 
/**
 * This class defines a backend used to present information about Directory
 * Server backups.  It will not actually store anything, but upon request will
 * retrieve information about the backups that it knows about.  The backups will
 * be arranged in a hierarchy based on the directory that contains them, and
 * it may be possible to dynamically discover new backups if a previously
 * unknown backup directory is included in the base DN.
 */
public class BackupBackend
       extends Backend<BackupBackendCfg>
       implements ConfigurationChangeListener<BackupBackendCfg>
{
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
 
 
  /** The current configuration state. */
  private BackupBackendCfg currentConfig;
 
  /** The DN for the base backup entry. */
  private DN backupBaseDN;
 
  /** The set of base DNs for this backend. */
  private DN[] baseDNs;
 
  /** The backup base entry. */
  private Entry backupBaseEntry;
 
  /** A cache of BackupDirectories. */
  private HashMap<File,CachedBackupDirectory> backupDirectories;
 
  /**
   * To avoid parsing and reparsing the contents of backup.info files, we
   * cache the BackupDirectory for each directory using this class.
   */
  private class CachedBackupDirectory
  {
    /** The path to the 'bak' directory. */
    private final String directoryPath;
 
    /** The 'backup.info' file. */
    private final File backupInfo;
 
    /** The last modify time of the backupInfo file. */
    private long lastModified;
 
    /** The BackupDirectory parsed at lastModified time. */
    private BackupDirectory backupDirectory;
 
    /**
     * A BackupDirectory that is cached based on the backup descriptor file.
     *
     * @param directory Path to the backup directory itself.
     */
    public CachedBackupDirectory(File directory)
    {
      directoryPath = directory.getPath();
      backupInfo = new File(directoryPath + File.separator + BACKUP_DIRECTORY_DESCRIPTOR_FILE);
      lastModified = -1;
      backupDirectory = null;
    }
 
    /**
     * Return a BackupDirectory. This will be recomputed every time the underlying descriptor (backup.info) file
     * changes.
     *
     * @return An up-to-date BackupDirectory
     * @throws IOException If a problem occurs while trying to read the contents of the descriptor file.
     * @throws ConfigException If the contents of the descriptor file cannot be parsed to create a backup directory
     *                         structure.
     */
    public synchronized BackupDirectory getBackupDirectory()
            throws IOException, ConfigException
    {
      long currentModified = backupInfo.lastModified();
      if (backupDirectory == null || currentModified != lastModified)
      {
        backupDirectory = BackupDirectory.readBackupDirectoryDescriptor(directoryPath);
        lastModified = currentModified;
      }
      return backupDirectory;
    }
  }
 
 
  /**
   * Creates a new backend with the provided information.  All backend
   * implementations must implement a default constructor that use
   * <CODE>super()</CODE> to invoke this constructor.
   */
  public BackupBackend()
  {
    super();
 
    // Perform all initialization in initializeBackend.
  }
 
 
 
  /** {@inheritDoc} */
  @Override
  public void configureBackend(BackupBackendCfg config, ServerContext serverContext) throws ConfigException
  {
    // Make sure that a configuration entry was provided.  If not, then we will
    // not be able to complete initialization.
    if (config == null)
    {
      throw new ConfigException(ERR_BACKEND_CONFIG_ENTRY_NULL.get(getBackendID()));
    }
    currentConfig = config;
  }
 
 
 
  /** {@inheritDoc} */
  @Override
  public void openBackend()
         throws ConfigException, InitializationException
  {
    // Create the set of base DNs that we will handle.  In this case, it's just
    // the DN of the base backup entry.
    try
    {
      backupBaseDN = DN.valueOf(DN_BACKUP_ROOT);
    }
    catch (Exception e)
    {
      logger.traceException(e);
 
      LocalizableMessage message =
          ERR_BACKEND_CANNOT_DECODE_BACKEND_ROOT_DN.get(getExceptionMessage(e), getBackendID());
      throw new InitializationException(message, e);
    }
 
    // FIXME -- Deal with this more correctly.
    this.baseDNs = new DN[] { backupBaseDN };
 
 
    // Determine the set of backup directories that we will use by default.
    Set<String> values = currentConfig.getBackupDirectory();
    backupDirectories = new LinkedHashMap<>(values.size());
    for (String s : values)
    {
      File dir = getFileForPath(s);
      backupDirectories.put(dir, new CachedBackupDirectory(dir));
    }
 
 
    // Construct the backup base entry.
    LinkedHashMap<ObjectClass,String> objectClasses = new LinkedHashMap<>(2);
    objectClasses.put(DirectoryServer.getTopObjectClass(), OC_TOP);
 
    ObjectClass untypedOC =
         DirectoryServer.getObjectClass(OC_UNTYPED_OBJECT_LC, true);
    objectClasses.put(untypedOC, OC_UNTYPED_OBJECT);
 
    LinkedHashMap<AttributeType,List<Attribute>> opAttrs = new LinkedHashMap<>(0);
    LinkedHashMap<AttributeType,List<Attribute>> userAttrs = new LinkedHashMap<>(1);
 
    RDN rdn = backupBaseDN.rdn();
    int numAVAs = rdn.getNumValues();
    for (int i=0; i < numAVAs; i++)
    {
      AttributeType attrType = rdn.getAttributeType(i);
      userAttrs.put(attrType, Attributes.createAsList(attrType, rdn.getAttributeValue(i)));
    }
 
    backupBaseEntry = new Entry(backupBaseDN, objectClasses, userAttrs, opAttrs);
 
    currentConfig.addBackupChangeListener(this);
 
    // Register the backup base as a private suffix.
    try
    {
      DirectoryServer.registerBaseDN(backupBaseDN, this, true);
    }
    catch (Exception e)
    {
      logger.traceException(e);
 
      LocalizableMessage message = ERR_BACKEND_CANNOT_REGISTER_BASEDN.get(
          backupBaseDN, getExceptionMessage(e));
      throw new InitializationException(message, e);
    }
  }
 
 
 
  /** {@inheritDoc} */
  @Override
  public void closeBackend()
  {
    currentConfig.removeBackupChangeListener(this);
 
    try
    {
      DirectoryServer.deregisterBaseDN(backupBaseDN);
    }
    catch (Exception e)
    {
      logger.traceException(e);
    }
  }
 
 
 
  /** {@inheritDoc} */
  @Override
  public DN[] getBaseDNs()
  {
    return baseDNs;
  }
 
 
 
  /** {@inheritDoc} */
  @Override
  public long getEntryCount()
  {
    int numEntries = 1;
 
    AttributeType backupPathType =
         DirectoryServer.getAttributeType(ATTR_BACKUP_DIRECTORY_PATH, true);
 
    for (File dir : backupDirectories.keySet())
    {
      try
      {
        // Check to see if the descriptor file exists.  If not, then skip this
        // backup directory.
        File descriptorFile = new File(dir, BACKUP_DIRECTORY_DESCRIPTOR_FILE);
        if (! descriptorFile.exists())
        {
          continue;
        }
 
        DN backupDirDN = makeChildDN(backupBaseDN, backupPathType,
                                     dir.getAbsolutePath());
        getBackupDirectoryEntry(backupDirDN);
        numEntries++;
      }
      catch (Exception e) {}
    }
 
    return numEntries;
  }
 
 
 
  /** {@inheritDoc} */
  @Override
  public boolean isIndexed(AttributeType attributeType, IndexType indexType)
  {
    // All searches in this backend will always be considered indexed.
    return true;
  }
 
 
 
  /** {@inheritDoc} */
  @Override
  public ConditionResult hasSubordinates(DN entryDN) throws DirectoryException
  {
    long ret = getNumberOfSubordinates(entryDN, false);
    if(ret < 0)
    {
      return ConditionResult.UNDEFINED;
    }
    return ConditionResult.valueOf(ret != 0);
  }
 
  /** {@inheritDoc} */
  @Override
  public long getNumberOfEntriesInBaseDN(DN baseDN) throws DirectoryException {
    checkNotNull(baseDN, "baseDN must not be null");
    return getNumberOfSubordinates(baseDN, true) + 1;
  }
 
  /** {@inheritDoc} */
  @Override
  public long getNumberOfChildren(DN parentDN) throws DirectoryException {
    checkNotNull(parentDN, "parentDN must not be null");
    return getNumberOfSubordinates(parentDN, false);
  }
 
  private long getNumberOfSubordinates(DN entryDN, boolean includeSubtree) throws DirectoryException
  {
    // If the requested entry was the backend base entry, then return
    // the number of backup directories.
    if (backupBaseDN.equals(entryDN))
    {
      long count = 0;
      for (File dir : backupDirectories.keySet())
      {
        // Check to see if the descriptor file exists.  If not, then skip this
        // backup directory.
        File descriptorFile = new File(dir, BACKUP_DIRECTORY_DESCRIPTOR_FILE);
        if (! descriptorFile.exists())
        {
          continue;
        }
 
        // If subtree is included, count the number of entries for each
        // backup directory.
        if (includeSubtree)
        {
          count++;
          try
          {
            BackupDirectory backupDirectory = backupDirectories.get(dir).getBackupDirectory();
            count += backupDirectory.getBackups().keySet().size();
          }
          catch (Exception e)
          {
            throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM, ERR_BACKUP_INVALID_BACKUP_DIRECTORY.get(
                entryDN, e.getMessage()));
          }
        }
 
        count ++;
      }
      return count;
    }
 
    // See if the requested entry was one level below the backend base entry.
    // If so, then it must point to a backup directory.  Otherwise, it must be
    // two levels below the backup base entry and must point to a specific
    // backup.
    DN parentDN = entryDN.getParentDNInSuffix();
    if (parentDN == null)
    {
      return -1;
    }
    else if (backupBaseDN.equals(parentDN))
    {
      long count = 0;
      Entry backupDirEntry = getBackupDirectoryEntry(entryDN);
 
      AttributeType t =
          DirectoryServer.getAttributeType(ATTR_BACKUP_DIRECTORY_PATH, true);
      List<Attribute> attrList = backupDirEntry.getAttribute(t);
      if (attrList != null && !attrList.isEmpty())
      {
        for (ByteString v : attrList.get(0))
        {
          try
          {
            File dir = new File(v.toString());
            BackupDirectory backupDirectory = backupDirectories.get(dir).getBackupDirectory();
            count += backupDirectory.getBackups().keySet().size();
          }
          catch (Exception e)
          {
            return -1;
          }
        }
      }
      return count;
    }
    else if (backupBaseDN.equals(parentDN.getParentDNInSuffix()))
    {
      return 0;
    }
    else
    {
      return -1;
    }
  }
 
  /** {@inheritDoc} */
  @Override
  public Entry getEntry(DN entryDN)
         throws DirectoryException
  {
    // If the requested entry was null, then throw an exception.
    if (entryDN == null)
    {
      throw new DirectoryException(DirectoryServer.getServerErrorResultCode(),
          ERR_BACKEND_GET_ENTRY_NULL.get(getBackendID()));
    }
 
 
    // If the requested entry was the backend base entry, then retrieve it.
    if (entryDN.equals(backupBaseDN))
    {
      return backupBaseEntry.duplicate(true);
    }
 
 
    // See if the requested entry was one level below the backend base entry.
    // If so, then it must point to a backup directory.  Otherwise, it must be
    // two levels below the backup base entry and must point to a specific
    // backup.
    DN parentDN = entryDN.getParentDNInSuffix();
    if (parentDN == null)
    {
      throw new DirectoryException(ResultCode.NO_SUCH_OBJECT,
          ERR_BACKUP_INVALID_BASE.get(entryDN));
    }
    else if (parentDN.equals(backupBaseDN))
    {
      return getBackupDirectoryEntry(entryDN);
    }
    else if (backupBaseDN.equals(parentDN.getParentDNInSuffix()))
    {
      return getBackupEntry(entryDN);
    }
    else
    {
      LocalizableMessage message = ERR_BACKUP_INVALID_BASE.get(entryDN);
      throw new DirectoryException(ResultCode.NO_SUCH_OBJECT,
              message, backupBaseDN, null);
    }
  }
 
 
 
  /**
   * Generates an entry for a backup directory based on the provided DN.  The
   * DN must contain an RDN component that specifies the path to the backup
   * directory, and that directory must exist and be a valid backup directory.
   *
   * @param  entryDN  The DN of the backup directory entry to retrieve.
   *
   * @return  The requested backup directory entry.
   *
   * @throws  DirectoryException  If the specified directory does not exist or
   *                              is not a valid backup directory, or if the DN
   *                              does not specify any backup directory.
   */
  private Entry getBackupDirectoryEntry(DN entryDN)
         throws DirectoryException
  {
    // Make sure that the DN specifies a backup directory.
    AttributeType t =
         DirectoryServer.getAttributeType(ATTR_BACKUP_DIRECTORY_PATH, true);
    ByteString v = entryDN.rdn().getAttributeValue(t);
    if (v == null)
    {
      LocalizableMessage message =
          ERR_BACKUP_DN_DOES_NOT_SPECIFY_DIRECTORY.get(entryDN);
      throw new DirectoryException(ResultCode.CONSTRAINT_VIOLATION, message,
                                   backupBaseDN, null);
    }
 
 
    // Get a handle to the backup directory and the information that it
    // contains.
    BackupDirectory backupDirectory;
    try
    {
      File dir = new File(v.toString());
      backupDirectory = backupDirectories.get(dir).getBackupDirectory();
    }
    catch (ConfigException ce)
    {
      logger.traceException(ce);
 
      throw new DirectoryException(ResultCode.CONSTRAINT_VIOLATION,
          ERR_BACKUP_INVALID_BACKUP_DIRECTORY.get(entryDN, ce.getMessage()));
    }
    catch (Exception e)
    {
      logger.traceException(e);
 
      LocalizableMessage message =
          ERR_BACKUP_ERROR_GETTING_BACKUP_DIRECTORY.get(getExceptionMessage(e));
      throw new DirectoryException(DirectoryServer.getServerErrorResultCode(),
                                   message);
    }
 
 
    // Construct the backup directory entry to return.
    LinkedHashMap<ObjectClass,String> ocMap = new LinkedHashMap<>(2);
    ocMap.put(DirectoryServer.getTopObjectClass(), OC_TOP);
 
    ObjectClass backupDirOC =
         DirectoryServer.getObjectClass(OC_BACKUP_DIRECTORY, true);
    ocMap.put(backupDirOC, OC_BACKUP_DIRECTORY);
 
    LinkedHashMap<AttributeType,List<Attribute>> opAttrs = new LinkedHashMap<>(0);
    LinkedHashMap<AttributeType,List<Attribute>> userAttrs = new LinkedHashMap<>(3);
    userAttrs.put(t, asList(t, v));
 
    t = DirectoryServer.getAttributeType(ATTR_BACKUP_BACKEND_DN, true);
    userAttrs.put(t, asList(t, ByteString.valueOf(backupDirectory.getConfigEntryDN().toString())));
 
    Entry e = new Entry(entryDN, ocMap, userAttrs, opAttrs);
    e.processVirtualAttributes();
    return e;
  }
 
 
 
  /**
   * Generates an entry for a backup based on the provided DN.  The DN must
   * have an RDN component that specifies the backup ID, and the parent DN must
   * have an RDN component that specifies the backup directory.
   *
   * @param  entryDN  The DN of the backup entry to retrieve.
   *
   * @return  The requested backup entry.
   *
   * @throws  DirectoryException  If the specified backup does not exist or is
   *                              invalid.
   */
  private Entry getBackupEntry(DN entryDN)
          throws DirectoryException
  {
    // First, get the backup ID from the entry DN.
    AttributeType idType = DirectoryServer.getAttributeType(ATTR_BACKUP_ID, true);
    ByteString idValue = entryDN.rdn().getAttributeValue(idType);
    if (idValue == null) {
      throw newConstraintViolation(ERR_BACKUP_NO_BACKUP_ID_IN_DN.get(entryDN));
    }
    String backupID = idValue.toString();
 
    // Next, get the backup directory from the parent DN.
    DN parentDN = entryDN.getParentDNInSuffix();
    if (parentDN == null) {
      throw newConstraintViolation(ERR_BACKUP_NO_BACKUP_PARENT_DN.get(entryDN));
    }
 
    AttributeType t = DirectoryServer.getAttributeType(
        ATTR_BACKUP_DIRECTORY_PATH, true);
    ByteString v = parentDN.rdn().getAttributeValue(t);
    if (v == null) {
      throw newConstraintViolation(ERR_BACKUP_NO_BACKUP_DIR_IN_DN.get(entryDN));
    }
 
    BackupDirectory backupDirectory;
    try {
      backupDirectory = backupDirectories.get(new File(v.toString())).getBackupDirectory();
    } catch (ConfigException ce) {
      logger.traceException(ce);
 
      throw newConstraintViolation(ERR_BACKUP_INVALID_BACKUP_DIRECTORY.get(entryDN, ce.getMessageObject()));
    } catch (Exception e) {
      logger.traceException(e);
 
      LocalizableMessage message = ERR_BACKUP_ERROR_GETTING_BACKUP_DIRECTORY
          .get(getExceptionMessage(e));
      throw new DirectoryException(DirectoryServer.getServerErrorResultCode(),
          message);
    }
 
    BackupInfo backupInfo = backupDirectory.getBackupInfo(backupID);
    if (backupInfo == null) {
      LocalizableMessage message = ERR_BACKUP_NO_SUCH_BACKUP.get(backupID, backupDirectory
          .getPath());
      throw new DirectoryException(ResultCode.NO_SUCH_OBJECT, message,
          parentDN, null);
    }
 
    // Construct the backup entry to return.
    LinkedHashMap<ObjectClass, String> ocMap = new LinkedHashMap<>(3);
    ocMap.put(DirectoryServer.getTopObjectClass(), OC_TOP);
 
    ObjectClass oc = DirectoryServer.getObjectClass(OC_BACKUP_INFO, true);
    ocMap.put(oc, OC_BACKUP_INFO);
 
    oc = DirectoryServer.getObjectClass(OC_EXTENSIBLE_OBJECT_LC, true);
    ocMap.put(oc, OC_EXTENSIBLE_OBJECT);
 
    LinkedHashMap<AttributeType, List<Attribute>> opAttrs = new LinkedHashMap<>(0);
    LinkedHashMap<AttributeType, List<Attribute>> userAttrs = new LinkedHashMap<>();
    userAttrs.put(idType, asList(idType, idValue));
 
    backupInfo.getBackupDirectory();
    userAttrs.put(t, asList(t, v));
 
    Date backupDate = backupInfo.getBackupDate();
    if (backupDate != null) {
      t = DirectoryServer.getAttributeType(ATTR_BACKUP_DATE, true);
      userAttrs.put(t,
          asList(t, ByteString.valueOf(GeneralizedTimeSyntax.format(backupDate))));
    }
 
    putBoolean(userAttrs, ATTR_BACKUP_COMPRESSED, backupInfo.isCompressed());
    putBoolean(userAttrs, ATTR_BACKUP_ENCRYPTED, backupInfo.isEncrypted());
    putBoolean(userAttrs, ATTR_BACKUP_INCREMENTAL, backupInfo.isIncremental());
 
    HashSet<String> dependencies = backupInfo.getDependencies();
    if (dependencies != null && !dependencies.isEmpty()) {
      t = DirectoryServer.getAttributeType(ATTR_BACKUP_DEPENDENCY, true);
      AttributeBuilder builder = new AttributeBuilder(t);
      for (String s : dependencies) {
        builder.add(s);
      }
      userAttrs.put(t, builder.toAttributeList());
    }
 
    byte[] signedHash = backupInfo.getSignedHash();
    if (signedHash != null) {
      putByteString(userAttrs, ATTR_BACKUP_SIGNED_HASH, signedHash);
    }
 
    byte[] unsignedHash = backupInfo.getUnsignedHash();
    if (unsignedHash != null) {
      putByteString(userAttrs, ATTR_BACKUP_UNSIGNED_HASH, unsignedHash);
    }
 
    HashMap<String, String> properties = backupInfo.getBackupProperties();
    if (properties != null && !properties.isEmpty()) {
      for (Map.Entry<String, String> e : properties.entrySet()) {
        t = DirectoryServer.getAttributeType(toLowerCase(e.getKey()), true);
        userAttrs.put(t, asList(t, ByteString.valueOf(e.getValue())));
      }
    }
 
    Entry e = new Entry(entryDN, ocMap, userAttrs, opAttrs);
    e.processVirtualAttributes();
    return e;
  }
 
  private void putByteString(LinkedHashMap<AttributeType, List<Attribute>> userAttrs, String attrName, byte[] value)
  {
    AttributeType t = DirectoryServer.getAttributeType(attrName, true);
    userAttrs.put(t, asList(t, ByteString.wrap(value)));
  }
 
  private void putBoolean(LinkedHashMap<AttributeType, List<Attribute>> attrsMap, String attrName, boolean value)
  {
    AttributeType t = DirectoryServer.getAttributeType(attrName, true);
    attrsMap.put(t, asList(t, createBooleanValue(value)));
  }
 
  private List<Attribute> asList(AttributeType attrType, ByteString value)
  {
    return Attributes.createAsList(attrType, value);
  }
 
  private DirectoryException newConstraintViolation(LocalizableMessage message)
  {
    return new DirectoryException(ResultCode.CONSTRAINT_VIOLATION, message);
  }
 
  /** {@inheritDoc} */
  @Override
  public void addEntry(Entry entry, AddOperation addOperation)
         throws DirectoryException
  {
    throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM,
        ERR_BACKEND_ADD_NOT_SUPPORTED.get(entry.getName(), getBackendID()));
  }
 
 
 
  /** {@inheritDoc} */
  @Override
  public void deleteEntry(DN entryDN, DeleteOperation deleteOperation)
         throws DirectoryException
  {
    throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM,
        ERR_BACKEND_DELETE_NOT_SUPPORTED.get(entryDN, getBackendID()));
  }
 
 
 
  /** {@inheritDoc} */
  @Override
  public void replaceEntry(Entry oldEntry, Entry newEntry,
      ModifyOperation modifyOperation) throws DirectoryException
  {
    throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM,
        ERR_BACKEND_MODIFY_NOT_SUPPORTED.get(oldEntry.getName(), getBackendID()));
  }
 
 
 
  /** {@inheritDoc} */
  @Override
  public void renameEntry(DN currentDN, Entry entry,
                                   ModifyDNOperation modifyDNOperation)
         throws DirectoryException
  {
    throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM,
        ERR_BACKEND_MODIFY_DN_NOT_SUPPORTED.get(currentDN, getBackendID()));
  }
 
 
 
  /** {@inheritDoc} */
  @Override
  public void search(SearchOperation searchOperation)
         throws DirectoryException
  {
    // Get the base entry for the search, if possible.  If it doesn't exist,
    // then this will throw an exception.
    DN    baseDN    = searchOperation.getBaseDN();
    Entry baseEntry = getEntry(baseDN);
 
 
    // Look at the base DN and see if it's the backup base DN, a backup
    // directory entry DN, or a backup entry DN.
    DN parentDN;
    SearchScope  scope  = searchOperation.getScope();
    SearchFilter filter = searchOperation.getFilter();
    if (backupBaseDN.equals(baseDN))
    {
      if ((scope == SearchScope.BASE_OBJECT || scope == SearchScope.WHOLE_SUBTREE)
          && filter.matchesEntry(baseEntry))
      {
        searchOperation.returnEntry(baseEntry, null);
      }
 
      if (scope != SearchScope.BASE_OBJECT && !backupDirectories.isEmpty())
      {
        AttributeType backupPathType =
             DirectoryServer.getAttributeType(ATTR_BACKUP_DIRECTORY_PATH, true);
        for (File dir : backupDirectories.keySet())
        {
          // Check to see if the descriptor file exists.  If not, then skip this
          // backup directory.
          File descriptorFile = new File(dir, BACKUP_DIRECTORY_DESCRIPTOR_FILE);
          if (! descriptorFile.exists())
          {
            continue;
          }
 
 
          DN backupDirDN = makeChildDN(backupBaseDN, backupPathType,
                                       dir.getAbsolutePath());
 
          Entry backupDirEntry;
          try
          {
            backupDirEntry = getBackupDirectoryEntry(backupDirDN);
          }
          catch (Exception e)
          {
            logger.traceException(e);
 
            continue;
          }
 
          if (filter.matchesEntry(backupDirEntry))
          {
            searchOperation.returnEntry(backupDirEntry, null);
          }
 
          if (scope != SearchScope.SINGLE_LEVEL)
          {
            List<Attribute> attrList = backupDirEntry.getAttribute(backupPathType);
            returnEntries(searchOperation, backupDirDN, filter, attrList);
          }
        }
      }
    }
    else if (backupBaseDN.equals(parentDN = baseDN.getParentDNInSuffix()))
    {
      Entry backupDirEntry = getBackupDirectoryEntry(baseDN);
 
      if ((scope == SearchScope.BASE_OBJECT || scope == SearchScope.WHOLE_SUBTREE)
          && filter.matchesEntry(backupDirEntry))
      {
        searchOperation.returnEntry(backupDirEntry, null);
      }
 
 
      if (scope != SearchScope.BASE_OBJECT)
      {
        AttributeType t =
             DirectoryServer.getAttributeType(ATTR_BACKUP_DIRECTORY_PATH, true);
        List<Attribute> attrList = backupDirEntry.getAttribute(t);
        returnEntries(searchOperation, baseDN, filter, attrList);
      }
    }
    else
    {
      if (parentDN == null
          || !backupBaseDN.equals(parentDN.getParentDNInSuffix()))
      {
        LocalizableMessage message = ERR_BACKUP_NO_SUCH_ENTRY.get(backupBaseDN);
        throw new DirectoryException(ResultCode.NO_SUCH_OBJECT, message);
      }
 
      if (scope == SearchScope.BASE_OBJECT ||
          scope == SearchScope.WHOLE_SUBTREE)
      {
        Entry backupEntry = getBackupEntry(baseDN);
        if (backupEntry == null)
        {
          LocalizableMessage message = ERR_BACKUP_NO_SUCH_ENTRY.get(backupBaseDN);
          throw new DirectoryException(ResultCode.NO_SUCH_OBJECT, message);
        }
 
        if (filter.matchesEntry(backupEntry))
        {
          searchOperation.returnEntry(backupEntry, null);
        }
      }
    }
  }
 
  private void returnEntries(SearchOperation searchOperation, DN baseDN, SearchFilter filter, List<Attribute> attrList)
  {
    if (attrList != null && !attrList.isEmpty())
    {
      for (ByteString v : attrList.get(0))
      {
        try
        {
          File dir = new File(v.toString());
          BackupDirectory backupDirectory = backupDirectories.get(dir).getBackupDirectory();
          AttributeType idType = DirectoryServer.getAttributeType(ATTR_BACKUP_ID, true);
 
          for (String backupID : backupDirectory.getBackups().keySet())
          {
            DN backupEntryDN = makeChildDN(baseDN, idType, backupID);
            Entry backupEntry = getBackupEntry(backupEntryDN);
            if (filter.matchesEntry(backupEntry))
            {
              searchOperation.returnEntry(backupEntry, null);
            }
          }
        }
        catch (Exception e)
        {
          logger.traceException(e);
 
          continue;
        }
      }
    }
  }
 
  /** {@inheritDoc} */
  @Override
  public Set<String> getSupportedControls()
  {
    return Collections.emptySet();
  }
 
  /** {@inheritDoc} */
  @Override
  public Set<String> getSupportedFeatures()
  {
    return Collections.emptySet();
  }
 
  /** {@inheritDoc} */
  @Override
  public boolean supports(BackendOperation backendOperation)
  {
    return false;
  }
 
  /** {@inheritDoc} */
  @Override
  public void exportLDIF(LDIFExportConfig exportConfig)
         throws DirectoryException
  {
    throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM,
        ERR_BACKEND_IMPORT_AND_EXPORT_NOT_SUPPORTED.get(getBackendID()));
  }
 
  /** {@inheritDoc} */
  @Override
  public LDIFImportResult importLDIF(LDIFImportConfig importConfig, ServerContext serverContext)
      throws DirectoryException
  {
    throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM,
        ERR_BACKEND_IMPORT_AND_EXPORT_NOT_SUPPORTED.get(getBackendID()));
  }
 
  /** {@inheritDoc} */
  @Override
  public void createBackup(BackupConfig backupConfig)
  throws DirectoryException
  {
    throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM,
        ERR_BACKEND_BACKUP_AND_RESTORE_NOT_SUPPORTED.get(getBackendID()));
  }
 
  /** {@inheritDoc} */
  @Override
  public void removeBackup(BackupDirectory backupDirectory,
                           String backupID)
         throws DirectoryException
  {
    throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM,
        ERR_BACKEND_BACKUP_AND_RESTORE_NOT_SUPPORTED.get(getBackendID()));
  }
 
  /** {@inheritDoc} */
  @Override
  public void restoreBackup(RestoreConfig restoreConfig)
         throws DirectoryException
  {
    throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM,
        ERR_BACKEND_BACKUP_AND_RESTORE_NOT_SUPPORTED.get(getBackendID()));
  }
 
  /** {@inheritDoc} */
  @Override
  public boolean isConfigurationChangeAcceptable(
       BackupBackendCfg cfg, List<LocalizableMessage> unacceptableReasons)
  {
    // We'll accept anything here.  The only configurable attribute is the
    // default set of backup directories, but that doesn't require any
    // validation at this point.
    return true;
  }
 
  /** {@inheritDoc} */
  @Override
  public ConfigChangeResult applyConfigurationChange(BackupBackendCfg cfg)
  {
    final ConfigChangeResult ccr = new ConfigChangeResult();
 
    Set<String> values = cfg.getBackupDirectory();
    backupDirectories = new LinkedHashMap<>(values.size());
    for (String s : values)
    {
      File dir = getFileForPath(s);
      backupDirectories.put(dir, new CachedBackupDirectory(dir));
    }
 
    currentConfig = cfg;
    return ccr;
  }
 
  /**
   * Create a new child DN from a given parent DN.  The child RDN is formed
   * from a given attribute type and string value.
   * @param parentDN The DN of the parent.
   * @param rdnAttrType The attribute type of the RDN.
   * @param rdnStringValue The string value of the RDN.
   * @return A new child DN.
   */
  public static DN makeChildDN(DN parentDN, AttributeType rdnAttrType,
                               String rdnStringValue)
  {
    ByteString attrValue = ByteString.valueOf(rdnStringValue);
    return parentDN.child(RDN.create(rdnAttrType, attrValue));
  }
}