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

Jean-Noel Rouvignac
03.21.2014 5ae40296386ae7b3465f2bc23cf41ce227a40bbc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
/*
 * 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 2012-2014 ForgeRock AS.
 */
package org.opends.server.backends;
 
 
 
import static org.opends.messages.BackendMessages.*;
import static org.opends.messages.ConfigMessages.*;
import static org.opends.server.config.ConfigConstants.*;
import static org.opends.server.util.ServerConstants.*;
import static org.opends.server.util.StaticUtils.getExceptionMessage;
import static org.opends.server.util.StaticUtils.stackTraceToSingleLineString;
 
import java.util.*;
 
import org.forgerock.i18n.LocalizableMessage;
import org.opends.server.admin.Configuration;
import org.opends.server.admin.server.ConfigurationChangeListener;
import org.opends.server.admin.std.server.MonitorBackendCfg;
import org.opends.server.api.Backend;
import org.opends.server.api.MonitorProvider;
import org.opends.server.config.ConfigEntry;
import org.opends.server.config.ConfigException;
import org.opends.server.core.*;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.opends.server.types.*;
import org.opends.server.util.DynamicConstants;
import org.opends.server.util.LDIFWriter;
import org.opends.server.util.TimeThread;
import org.forgerock.util.Reject;
 
 
 
/**
 * This class defines a backend to hold Directory Server monitor entries. It
 * will not actually store anything, but upon request will retrieve the
 * requested monitor and dynamically generate the associated entry. It will also
 * construct a base monitor entry with some useful server-wide data.
 */
public class MonitorBackend extends Backend implements
    ConfigurationChangeListener<MonitorBackendCfg>
{
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
  // The set of user-defined attributes that will be included in the base
  // monitor entry.
  private ArrayList<Attribute> userDefinedAttributes;
 
  // The set of objectclasses that will be used in monitor entries.
  private HashMap<ObjectClass, String> monitorObjectClasses;
 
  // The DN of the configuration entry for this backend.
  private DN configEntryDN;
 
  // The current configuration state.
  private MonitorBackendCfg currentConfig;
 
  // The DN for the base monitor entry.
  private DN baseMonitorDN;
 
  // The set of base DNs for this backend.
  private DN[] baseDNs;
 
  // The set of supported controls for this backend.
  private HashSet<String> supportedControls;
 
  // The set of supported features for this backend.
  private HashSet<String> supportedFeatures;
 
 
 
  /**
   * 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 MonitorBackend()
  {
    super();
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public void addEntry(final Entry entry, final AddOperation addOperation)
      throws DirectoryException
  {
    throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM,
        ERR_MONITOR_ADD_NOT_SUPPORTED.get(entry.getName()));
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  public ConfigChangeResult applyConfigurationChange(
      final MonitorBackendCfg backendCfg)
  {
    ResultCode resultCode = ResultCode.SUCCESS;
    final boolean adminActionRequired = false;
    final ArrayList<LocalizableMessage> messages = new ArrayList<LocalizableMessage>();
 
    // Check to see if there is a new set of user-defined attributes.
    final ArrayList<Attribute> userAttrs = new ArrayList<Attribute>();
    try
    {
      final ConfigEntry configEntry = DirectoryServer
          .getConfigEntry(configEntryDN);
      for (final List<Attribute> attrs : configEntry.getEntry()
          .getUserAttributes().values())
      {
        for (final Attribute a : attrs)
        {
          if (!isMonitorConfigAttribute(a))
          {
            userAttrs.add(a);
          }
        }
      }
      for (final List<Attribute> attrs : configEntry.getEntry()
          .getOperationalAttributes().values())
      {
        for (final Attribute a : attrs)
        {
          if (!isMonitorConfigAttribute(a))
          {
            userAttrs.add(a);
          }
        }
      }
    }
    catch (final Exception e)
    {
      logger.traceException(e);
 
      messages.add(ERR_CONFIG_BACKEND_ERROR_INTERACTING_WITH_BACKEND_ENTRY.get(
          configEntryDN, stackTraceToSingleLineString(e)));
      resultCode = DirectoryServer.getServerErrorResultCode();
    }
 
    userDefinedAttributes = userAttrs;
 
    final LocalizableMessage message = INFO_MONITOR_USING_NEW_USER_ATTRS.get();
    messages.add(message);
 
    currentConfig = backendCfg;
    return new ConfigChangeResult(resultCode, adminActionRequired, messages);
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public void configureBackend(final Configuration config)
      throws ConfigException
  {
    Reject.ifNull(config);
    Reject.ifFalse(config instanceof MonitorBackendCfg);
 
    final MonitorBackendCfg cfg = (MonitorBackendCfg) config;
    final ConfigEntry configEntry = DirectoryServer.getConfigEntry(cfg.dn());
 
    // Make sure that a configuration entry was provided. If not, then we will
    // not be able to complete initialization.
    if (configEntry == null)
    {
      final LocalizableMessage message = ERR_MONITOR_CONFIG_ENTRY_NULL.get();
      throw new ConfigException(message);
    }
 
    configEntryDN = configEntry.getDN();
 
    // Get the set of user-defined attributes for the configuration entry. Any
    // attributes that we don't recognize will be included directly in the base
    // monitor entry.
    userDefinedAttributes = new ArrayList<Attribute>();
    for (final List<Attribute> attrs : configEntry.getEntry()
        .getUserAttributes().values())
    {
      for (final Attribute a : attrs)
      {
        if (!isMonitorConfigAttribute(a))
        {
          userDefinedAttributes.add(a);
        }
      }
    }
    for (final List<Attribute> attrs : configEntry.getEntry()
        .getOperationalAttributes().values())
    {
      for (final Attribute a : attrs)
      {
        if (!isMonitorConfigAttribute(a))
        {
          userDefinedAttributes.add(a);
        }
      }
    }
 
    // Construct the set of objectclasses to include in the base monitor entry.
    monitorObjectClasses = new LinkedHashMap<ObjectClass, String>(2);
    final ObjectClass topOC = DirectoryServer.getObjectClass(OC_TOP, true);
    monitorObjectClasses.put(topOC, OC_TOP);
 
    final ObjectClass monitorOC = DirectoryServer.getObjectClass(
        OC_MONITOR_ENTRY, true);
    monitorObjectClasses.put(monitorOC, OC_MONITOR_ENTRY);
 
    // Define an empty sets for the supported controls and features.
    supportedControls = new HashSet<String>(0);
    supportedFeatures = new HashSet<String>(0);
 
    // Create the set of base DNs that we will handle. In this case, it's just
    // the DN of the base monitor entry.
    try
    {
      baseMonitorDN = DN.valueOf(DN_MONITOR_ROOT);
    }
    catch (final Exception e)
    {
      logger.traceException(e);
 
      final LocalizableMessage message = ERR_MONITOR_CANNOT_DECODE_MONITOR_ROOT_DN
          .get(getExceptionMessage(e));
      throw new ConfigException(message, e);
    }
 
    // FIXME -- Deal with this more correctly.
    this.baseDNs = new DN[] { baseMonitorDN };
 
    currentConfig = cfg;
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public void createBackup(final BackupConfig backupConfig)
      throws DirectoryException
  {
    // This backend does not provide a backup/restore mechanism.
    final LocalizableMessage message = ERR_MONITOR_BACKUP_AND_RESTORE_NOT_SUPPORTED.get();
    throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM, message);
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public void deleteEntry(final DN entryDN,
      final DeleteOperation deleteOperation) throws DirectoryException
  {
    throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM,
        ERR_MONITOR_DELETE_NOT_SUPPORTED.get(entryDN));
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public boolean entryExists(final DN entryDN) throws DirectoryException
  {
    return getDIT().containsKey(entryDN);
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public void exportLDIF(final LDIFExportConfig exportConfig)
      throws DirectoryException
  {
    // TODO export-ldif reports nonsense for upTime etc.
 
    // Create the LDIF writer.
    LDIFWriter ldifWriter;
    try
    {
      ldifWriter = new LDIFWriter(exportConfig);
    }
    catch (final Exception e)
    {
      logger.traceException(e);
 
      final LocalizableMessage message = ERR_ROOTDSE_UNABLE_TO_CREATE_LDIF_WRITER
          .get(stackTraceToSingleLineString(e));
      throw new DirectoryException(DirectoryServer.getServerErrorResultCode(),
          message);
    }
 
    // Write the base monitor entry to the LDIF.
    try
    {
      ldifWriter.writeEntry(getBaseMonitorEntry());
    }
    catch (final Exception e)
    {
      logger.traceException(e);
 
      try
      {
        ldifWriter.close();
      }
      catch (final Exception e2)
      {
        logger.traceException(e2);
      }
 
      final LocalizableMessage message = ERR_MONITOR_UNABLE_TO_EXPORT_BASE
          .get(stackTraceToSingleLineString(e));
      throw new DirectoryException(DirectoryServer.getServerErrorResultCode(),
          message);
    }
 
    // Get all the monitor providers, convert them to entries, and write them to
    // LDIF.
    for (final MonitorProvider<?> monitorProvider : DirectoryServer
        .getMonitorProviders().values())
    {
      try
      {
        // TODO implementation of export is incomplete
      }
      catch (final Exception e)
      {
        logger.traceException(e);
 
        try
        {
          ldifWriter.close();
        }
        catch (final Exception e2)
        {
          logger.traceException(e2);
        }
 
        final LocalizableMessage message = ERR_MONITOR_UNABLE_TO_EXPORT_PROVIDER_ENTRY
            .get(monitorProvider.getMonitorInstanceName(),
                stackTraceToSingleLineString(e));
        throw new DirectoryException(
            DirectoryServer.getServerErrorResultCode(), message);
      }
    }
 
    // Close the monitor provider and return.
    try
    {
      ldifWriter.close();
    }
    catch (final Exception e)
    {
      logger.traceException(e);
    }
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public void finalizeBackend()
  {
    currentConfig.removeMonitorChangeListener(this);
    try
    {
      DirectoryServer.deregisterBaseDN(baseMonitorDN);
    }
    catch (final Exception e)
    {
      logger.traceException(e);
    }
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public DN[] getBaseDNs()
  {
    return baseDNs;
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public Entry getEntry(final DN entryDN) throws DirectoryException
  {
    // If the requested entry was null, then throw an exception.
    if (entryDN == null)
    {
      final LocalizableMessage message = ERR_MONITOR_GET_ENTRY_NULL.get();
      throw new DirectoryException(DirectoryServer.getServerErrorResultCode(),
          message);
    }
 
    // If the requested entry was the monitor base entry, then retrieve it
    // without constructing the DIT.
    if (entryDN.equals(baseMonitorDN))
    {
      return getBaseMonitorEntry();
    }
 
    // From now on we'll need the DIT.
    final Map<DN, MonitorProvider<?>> dit = getDIT();
    if (!dit.containsKey(entryDN))
    {
      throw new DirectoryException(ResultCode.NO_SUCH_OBJECT,
          ERR_MONITOR_INVALID_BASE.get(entryDN, baseMonitorDN));
    }
 
    // The DN is associated with a valid monitor/glue entry.
    return getEntry(entryDN, dit);
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public long getEntryCount()
  {
    return getDIT().size();
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public HashSet<String> getSupportedControls()
  {
    return supportedControls;
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public HashSet<String> getSupportedFeatures()
  {
    return supportedFeatures;
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public ConditionResult hasSubordinates(final DN entryDN)
      throws DirectoryException
  {
    final NavigableMap<DN, MonitorProvider<?>> dit = getDIT();
    if (!dit.containsKey(entryDN))
    {
      return ConditionResult.UNDEFINED;
    }
    else
    {
      final DN nextDN = dit.higherKey(entryDN);
      if (nextDN == null || !nextDN.isDescendantOf(entryDN))
      {
        return ConditionResult.FALSE;
      }
      else
      {
        return ConditionResult.TRUE;
      }
    }
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public LDIFImportResult importLDIF(final LDIFImportConfig importConfig)
      throws DirectoryException
  {
    // This backend does not support LDIF imports.
    final LocalizableMessage message = ERR_MONITOR_IMPORT_NOT_SUPPORTED.get();
    throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM, message);
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public void initializeBackend() throws ConfigException,
      InitializationException
  {
    // Register with the Directory Server as a configurable component.
    currentConfig.addMonitorChangeListener(this);
 
    // Register the monitor base as a private suffix.
    try
    {
      DirectoryServer.registerBaseDN(baseMonitorDN, this, true);
    }
    catch (final Exception e)
    {
      logger.traceException(e);
 
      final LocalizableMessage message = ERR_BACKEND_CANNOT_REGISTER_BASEDN.get(
          baseMonitorDN, getExceptionMessage(e));
      throw new InitializationException(message, e);
    }
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  public boolean isConfigurationChangeAcceptable(
      final MonitorBackendCfg backendCfg,
      final List<LocalizableMessage> unacceptableReasons)
  {
    // We'll pretty much accept anything here as long as it isn't one of our
    // private attributes.
    return true;
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public boolean isIndexed(final AttributeType attributeType,
      final IndexType indexType)
  {
    // All searches in this backend will always be considered indexed.
    return true;
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public boolean isLocal()
  {
    // For the purposes of this method, this is a local backend.
    return true;
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public long numSubordinates(final DN entryDN, final boolean subtree)
      throws DirectoryException
  {
    final NavigableMap<DN, MonitorProvider<?>> dit = getDIT();
    if (!dit.containsKey(entryDN))
    {
      return -1L;
    }
    else
    {
      long count = 0;
      final int childDNSize = entryDN.size() + 1;
      for (final DN dn : dit.tailMap(entryDN, false).navigableKeySet())
      {
        if (!dn.isDescendantOf(entryDN))
        {
          break;
        }
        else if (subtree || dn.size() == childDNSize)
        {
          count++;
        }
      }
      return count;
    }
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override
  public void preloadEntryCache() throws UnsupportedOperationException
  {
    throw new UnsupportedOperationException("Operation not supported.");
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public void removeBackup(final BackupDirectory backupDirectory,
      final String backupID) throws DirectoryException
  {
    // This backend does not provide a backup/restore mechanism.
    final LocalizableMessage message = ERR_MONITOR_BACKUP_AND_RESTORE_NOT_SUPPORTED.get();
    throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM, message);
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public void renameEntry(final DN currentDN, final Entry entry,
      final ModifyDNOperation modifyDNOperation) throws DirectoryException
  {
    throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM,
        ERR_MONITOR_MODIFY_DN_NOT_SUPPORTED.get(currentDN));
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public void replaceEntry(final Entry oldEntry, final Entry newEntry,
      final ModifyOperation modifyOperation) throws DirectoryException
  {
    throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM,
        ERR_MONITOR_MODIFY_NOT_SUPPORTED.get(newEntry.getName(), configEntryDN));
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public void restoreBackup(final RestoreConfig restoreConfig)
      throws DirectoryException
  {
    // This backend does not provide a backup/restore mechanism.
    final LocalizableMessage message = ERR_MONITOR_BACKUP_AND_RESTORE_NOT_SUPPORTED.get();
    throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM, message);
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public void search(final SearchOperation searchOperation)
      throws DirectoryException
  {
    // Get the base DN, scope, and filter for the search.
    final DN baseDN = searchOperation.getBaseDN();
    final SearchScope scope = searchOperation.getScope();
    final SearchFilter filter = searchOperation.getFilter();
 
    // Compute the current monitor DIT.
    final NavigableMap<DN, MonitorProvider<?>> dit = getDIT();
 
    // Resolve the base entry and return no such object if it does not exist.
    if (!dit.containsKey(baseDN))
    {
      // Not found, so find the nearest match.
      DN matchedDN = baseDN.parent();
      while (matchedDN != null)
      {
        if (dit.containsKey(matchedDN))
        {
          break;
        }
        matchedDN = matchedDN.parent();
      }
      final LocalizableMessage message = ERR_MEMORYBACKEND_ENTRY_DOESNT_EXIST.get(baseDN);
      throw new DirectoryException(ResultCode.NO_SUCH_OBJECT, message,
          matchedDN, null);
    }
 
    // Walk through all entries and send the ones that match.
    for (final Map.Entry<DN, MonitorProvider<?>> e : dit.tailMap(baseDN)
        .entrySet())
    {
      final DN dn = e.getKey();
      if (dn.matchesBaseAndScope(baseDN, scope))
      {
        final Entry entry = getEntry(dn, dit);
        if (filter.matchesEntry(entry))
        {
          searchOperation.returnEntry(entry, null);
        }
      }
      else if (scope == SearchScope.BASE_OBJECT || !dn.isDescendantOf(baseDN))
      {
        // No more entries will be in scope.
        break;
      }
    }
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public boolean supportsBackup()
  {
    // This backend does not provide a backup/restore mechanism.
    return false;
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public boolean supportsBackup(final BackupConfig backupConfig,
      final StringBuilder unsupportedReason)
  {
    // This backend does not provide a backup/restore mechanism.
    return false;
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public boolean supportsLDIFExport()
  {
    // We can export all the monitor entries as a point-in-time snapshot.
    // TODO implementation of export is incomplete
    // TODO export-ldif reports nonsense for upTime etc.
    return false;
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public boolean supportsLDIFImport()
  {
    // This backend does not support LDIF imports.
    return false;
  }
 
 
 
  /**
   * {@inheritDoc}
   */
  @Override()
  public boolean supportsRestore()
  {
    // This backend does not provide a backup/restore mechanism.
    return false;
  }
 
 
 
  /**
   * Creates an attribute for a monitor entry with the following criteria.
   *
   * @param name
   *          The name for the attribute.
   * @param lowerName
   *          The name for the attribute formatted in all lowercase characters.
   * @param value
   *          The value to use for the attribute.
   * @return The constructed attribute.
   */
  private Attribute createAttribute(final String name, final String lowerName,
      final String value)
  {
    return Attributes.create(name, value);
  }
 
 
 
  /**
   * Retrieves the base monitor entry for the Directory Server.
   *
   * @return The base monitor entry for the Directory Server.
   */
  private Entry getBaseMonitorEntry()
  {
    final HashMap<ObjectClass, String> monitorClasses =
        new LinkedHashMap<ObjectClass, String>(3);
    monitorClasses.putAll(monitorObjectClasses);
 
    final ObjectClass extensibleObjectOC = DirectoryServer.getObjectClass(
        OC_EXTENSIBLE_OBJECT_LC, true);
    monitorClasses.put(extensibleObjectOC, OC_EXTENSIBLE_OBJECT);
 
    final HashMap<AttributeType, List<Attribute>> monitorUserAttrs =
        new LinkedHashMap<AttributeType, List<Attribute>>();
    final HashMap<AttributeType, List<Attribute>> monitorOperationalAttrs =
        new LinkedHashMap<AttributeType, List<Attribute>>();
 
    // Add the "cn" attribute.
    final Attribute cnAttr = createAttribute(ATTR_COMMON_NAME,
        ATTR_COMMON_NAME, "monitor");
    final ArrayList<Attribute> cnList = new ArrayList<Attribute>(1);
    cnList.add(cnAttr);
    monitorUserAttrs.put(cnAttr.getAttributeType(), cnList);
 
    // Add the server product name.
    final Attribute productNameAttr = createAttribute(ATTR_PRODUCT_NAME,
        ATTR_PRODUCT_NAME_LC, DynamicConstants.PRODUCT_NAME);
    final ArrayList<Attribute> productNameList = new ArrayList<Attribute>(1);
    productNameList.add(productNameAttr);
    monitorUserAttrs.put(productNameAttr.getAttributeType(), productNameList);
 
    // Add the vendor name.
    final Attribute vendorNameAttr = createAttribute(ATTR_VENDOR_NAME,
        ATTR_VENDOR_NAME_LC, SERVER_VENDOR_NAME);
    final ArrayList<Attribute> vendorNameList = new ArrayList<Attribute>(1);
    vendorNameList.add(vendorNameAttr);
    monitorUserAttrs.put(vendorNameAttr.getAttributeType(), vendorNameList);
 
    // Add the vendor version.
    final Attribute versionAttr = createAttribute(ATTR_VENDOR_VERSION,
        ATTR_VENDOR_VERSION_LC, DirectoryServer.getVersionString());
    final ArrayList<Attribute> versionList = new ArrayList<Attribute>(1);
    versionList.add(versionAttr);
    monitorUserAttrs.put(versionAttr.getAttributeType(), versionList);
 
    // Add the server startup time.
    final Attribute startTimeAttr = createAttribute(ATTR_START_TIME,
        ATTR_START_TIME_LC, DirectoryServer.getStartTimeUTC());
    final ArrayList<Attribute> startTimeList = new ArrayList<Attribute>(1);
    startTimeList.add(startTimeAttr);
    monitorUserAttrs.put(startTimeAttr.getAttributeType(), startTimeList);
 
    // Add the current time.
    final Attribute currentTimeAttr = createAttribute(ATTR_CURRENT_TIME,
        ATTR_CURRENT_TIME_LC, TimeThread.getGMTTime());
    final ArrayList<Attribute> currentTimeList = new ArrayList<Attribute>(1);
    currentTimeList.add(currentTimeAttr);
    monitorUserAttrs.put(currentTimeAttr.getAttributeType(), currentTimeList);
 
    // Add the uptime as a human-readable string.
    long upSeconds = ((System.currentTimeMillis() - DirectoryServer
        .getStartTime()) / 1000);
    final long upDays = (upSeconds / 86400);
    upSeconds %= 86400;
    final long upHours = (upSeconds / 3600);
    upSeconds %= 3600;
    final long upMinutes = (upSeconds / 60);
    upSeconds %= 60;
    final LocalizableMessage upTimeStr = INFO_MONITOR_UPTIME.get(upDays, upHours,
        upMinutes, upSeconds);
    final Attribute upTimeAttr = createAttribute(ATTR_UP_TIME, ATTR_UP_TIME_LC,
        upTimeStr.toString());
    final ArrayList<Attribute> upTimeList = new ArrayList<Attribute>(1);
    upTimeList.add(upTimeAttr);
    monitorUserAttrs.put(upTimeAttr.getAttributeType(), upTimeList);
 
    // Add the number of connections currently established.
    final long currentConns = DirectoryServer.getCurrentConnections();
    final Attribute currentConnsAttr = createAttribute(ATTR_CURRENT_CONNS,
        ATTR_CURRENT_CONNS_LC, String.valueOf(currentConns));
    final ArrayList<Attribute> currentConnsList = new ArrayList<Attribute>(1);
    currentConnsList.add(currentConnsAttr);
    monitorUserAttrs.put(currentConnsAttr.getAttributeType(), currentConnsList);
 
    // Add the maximum number of connections established at one time.
    final long maxConns = DirectoryServer.getMaxConnections();
    final Attribute maxConnsAttr = createAttribute(ATTR_MAX_CONNS,
        ATTR_MAX_CONNS_LC, String.valueOf(maxConns));
    final ArrayList<Attribute> maxConnsList = new ArrayList<Attribute>(1);
    maxConnsList.add(maxConnsAttr);
    monitorUserAttrs.put(maxConnsAttr.getAttributeType(), maxConnsList);
 
    // Add the total number of connections the server has accepted.
    final long totalConns = DirectoryServer.getTotalConnections();
    final Attribute totalConnsAttr = createAttribute(ATTR_TOTAL_CONNS,
        ATTR_TOTAL_CONNS_LC, String.valueOf(totalConns));
    final ArrayList<Attribute> totalConnsList = new ArrayList<Attribute>(1);
    totalConnsList.add(totalConnsAttr);
    monitorUserAttrs.put(totalConnsAttr.getAttributeType(), totalConnsList);
 
    // Add all the user-defined attributes.
    for (final Attribute a : userDefinedAttributes)
    {
      final AttributeType type = a.getAttributeType();
 
      if (type.isOperational())
      {
        List<Attribute> attrs = monitorOperationalAttrs.get(type);
        if (attrs == null)
        {
          attrs = new ArrayList<Attribute>();
          attrs.add(a);
          monitorOperationalAttrs.put(type, attrs);
        }
        else
        {
          attrs.add(a);
        }
      }
      else
      {
        List<Attribute> attrs = monitorUserAttrs.get(type);
        if (attrs == null)
        {
          attrs = new ArrayList<Attribute>();
          attrs.add(a);
          monitorUserAttrs.put(type, attrs);
        }
        else
        {
          attrs.add(a);
        }
      }
    }
 
    // Construct and return the entry.
    final Entry e = new Entry(baseMonitorDN, monitorClasses, monitorUserAttrs,
        monitorOperationalAttrs);
    e.processVirtualAttributes();
    return e;
  }
 
 
 
  /**
   * Retrieves the branch monitor entry for the Directory Server.
   *
   * @param dn
   *          to get.
   * @return The branch monitor entry for the Directory Server.
   */
  private Entry getBranchMonitorEntry(final DN dn)
  {
 
    final HashMap<ObjectClass, String> monitorClasses =
        new LinkedHashMap<ObjectClass, String>(3);
    monitorClasses.putAll(monitorObjectClasses);
    final ObjectClass monitorOC = DirectoryServer.getObjectClass(
        OC_MONITOR_BRANCH, true);
    monitorClasses.put(monitorOC, OC_MONITOR_BRANCH);
 
    final HashMap<AttributeType, List<Attribute>> monitorUserAttrs =
        new LinkedHashMap<AttributeType, List<Attribute>>();
 
    final RDN rdn = dn.rdn();
    if (rdn != null)
    {
      // Add the RDN values
      for (int i = 0; i < rdn.getNumValues(); i++)
      {
        final AttributeType attributeType = rdn.getAttributeType(i);
        final AttributeValue value = rdn.getAttributeValue(attributeType);
        final Attribute attr = Attributes.create(attributeType, value);
        final List<Attribute> attrList = new ArrayList<Attribute>(1);
        attrList.add(attr);
        monitorUserAttrs.put(attributeType, attrList);
      }
    }
 
    // Construct and return the entry.
    final Entry e = new Entry(dn, monitorClasses, monitorUserAttrs, null);
    e.processVirtualAttributes();
    return e;
  }
 
 
 
  /**
   * Returns a map containing records for each DN in the monitor backend's DIT.
   * Each record maps the entry DN to the associated monitor provider, or
   * {@code null} if the entry is a glue (branch) entry.
   *
   * @return A map containing records for each DN in the monitor backend's DIT.
   */
  private NavigableMap<DN, MonitorProvider<?>> getDIT()
  {
    final NavigableMap<DN, MonitorProvider<?>> dit =
        new TreeMap<DN, MonitorProvider<?>>();
    for (final MonitorProvider<?> monitorProvider : DirectoryServer
        .getMonitorProviders().values())
    {
      DN dn = DirectoryServer.getMonitorProviderDN(monitorProvider);
      dit.put(dn, monitorProvider);
 
      // Added glue records.
      for (dn = dn.parent(); dn != null; dn = dn.parent())
      {
        if (dit.containsKey(dn))
        {
          break;
        }
        else
        {
          dit.put(dn, null);
        }
      }
    }
    return dit;
  }
 
 
 
  /**
   * Creates the monitor entry having the specified DN.
   *
   * @param entryDN
   *          The name of the monitor entry.
   * @param dit
   *          The monitor DIT.
   * @return Returns the monitor entry having the specified DN.
   */
  private Entry getEntry(final DN entryDN,
      final Map<DN, MonitorProvider<?>> dit)
  {
    // Get the monitor provider.
    final MonitorProvider<?> monitorProvider = dit.get(entryDN);
    if (monitorProvider != null)
    {
      return getMonitorEntry(entryDN, monitorProvider);
    }
    else if (entryDN.equals(baseMonitorDN))
    {
      // The monitor base entry needs special treatment.
      return getBaseMonitorEntry();
    }
    else
    {
      // Create a generic glue branch entry.
      return getBranchMonitorEntry(entryDN);
    }
  }
 
 
 
  /**
   * Generates and returns a monitor entry based on the contents of the provided
   * monitor provider.
   *
   * @param entryDN
   *          The DN to use for the entry.
   * @param monitorProvider
   *          The monitor provider to use to obtain the information for the
   *          entry.
   * @return The monitor entry generated from the information in the provided
   *         monitor provider.
   */
  private Entry getMonitorEntry(final DN entryDN,
      final MonitorProvider<?> monitorProvider)
  {
    final HashMap<ObjectClass, String> monitorClasses =
        new LinkedHashMap<ObjectClass, String>(
        3);
    monitorClasses.putAll(monitorObjectClasses);
 
    final ObjectClass monitorOC = monitorProvider.getMonitorObjectClass();
    monitorClasses.put(monitorOC, monitorOC.getPrimaryName());
 
    final List<Attribute> monitorAttrs = monitorProvider.getMonitorData();
    final HashMap<AttributeType, List<Attribute>> attrMap =
        new LinkedHashMap<AttributeType, List<Attribute>>(
          monitorAttrs.size() + 1);
 
    // Make sure to include the RDN attribute.
    final RDN entryRDN = entryDN.rdn();
    final AttributeType rdnType = entryRDN.getAttributeType(0);
    final AttributeValue rdnValue = entryRDN.getAttributeValue(0);
 
    final Attribute rdnAttr = Attributes.create(rdnType, rdnValue);
    final ArrayList<Attribute> rdnList = new ArrayList<Attribute>(1);
    rdnList.add(rdnAttr);
    attrMap.put(rdnType, rdnList);
 
    // Take the rest of the information from the monitor data.
    for (final Attribute a : monitorAttrs)
    {
      final AttributeType type = a.getAttributeType();
 
      List<Attribute> attrs = attrMap.get(type);
      if (attrs == null)
      {
        attrs = new ArrayList<Attribute>();
        attrs.add(a);
        attrMap.put(type, attrs);
      }
      else
      {
        attrs.add(a);
      }
    }
 
    final Entry e = new Entry(entryDN, monitorClasses, attrMap,
        new HashMap<AttributeType, List<Attribute>>(0));
    e.processVirtualAttributes();
    return e;
  }
 
 
 
  /**
   * Indicates whether the provided attribute is one that is used in the
   * configuration of this backend.
   *
   * @param attribute
   *          The attribute for which to make the determination.
   * @return <CODE>true</CODE> if the provided attribute is one that is used in
   *         the configuration of this backend, <CODE>false</CODE> if not.
   */
  private boolean isMonitorConfigAttribute(final Attribute attribute)
  {
    final AttributeType attrType = attribute.getAttributeType();
    if (attrType.hasName(ATTR_COMMON_NAME)
        || attrType.hasName(ATTR_BACKEND_ENABLED.toLowerCase())
        || attrType.hasName(ATTR_BACKEND_CLASS.toLowerCase())
        || attrType.hasName(ATTR_BACKEND_BASE_DN.toLowerCase())
        || attrType.hasName(ATTR_BACKEND_ID.toLowerCase())
        || attrType.hasName(ATTR_BACKEND_WRITABILITY_MODE.toLowerCase()))
    {
      return true;
    }
 
    return false;
  }
 
}