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

Jean-Noel Rouvignac
17.52.2014 18320d54c115617483a0912b496cdcc3ecd78b19
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
/*
 * 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 2008-2010 Sun Microsystems, Inc.
 *      Portions Copyright 2012-2014 ForgeRock AS
 */
 
package org.opends.guitools.controlpanel.browser;
 
import java.util.ArrayList;
import java.util.Set;
 
import javax.naming.InterruptedNamingException;
import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.SizeLimitExceededException;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapName;
import javax.swing.SwingUtilities;
import javax.swing.tree.TreeNode;
 
import org.forgerock.opendj.ldap.SearchScope;
import org.opends.admin.ads.util.ConnectionUtils;
import org.opends.guitools.controlpanel.ui.nodes.BasicNode;
import org.opends.messages.AdminToolMessages;
import org.opends.server.schema.SchemaConstants;
import org.opends.server.types.DN;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.LDAPURL;
import org.opends.server.types.OpenDsException;
import org.opends.server.types.RDN;
 
import static org.opends.messages.AdminToolMessages.*;
 
/**
 * The class that is in charge of doing the LDAP searches required to update a
 * node: search the local entry, detect if it has children, retrieve the
 * attributes required to render the node, etc.
 */
public class NodeRefresher extends AbstractNodeTask {
 
  /**
   * The enumeration containing all the states the refresher can have.
   *
   */
  public enum State
  {
    /**
     * The refresher is queued, but not started.
     */
    QUEUED,
    /**
     * The refresher is reading the local entry.
     */
    READING_LOCAL_ENTRY,
    /**
     * The refresher is solving a referral.
     */
    SOLVING_REFERRAL,
    /**
     * The refresher is detecting whether the entry has children or not.
     */
    DETECTING_CHILDREN,
    /**
     * The refresher is searching for the children of the entry.
     */
    SEARCHING_CHILDREN,
    /**
     * The refresher is finished.
     */
    FINISHED,
    /**
     * The refresher is cancelled.
     */
    CANCELLED,
    /**
     * The refresher has been interrupted.
     */
    INTERRUPTED,
    /**
     * The refresher has failed.
     */
    FAILED
  }
 
  BrowserController controller;
  State state;
  boolean recursive;
 
  SearchResult localEntry;
  SearchResult remoteEntry;
  LDAPURL   remoteUrl;
  boolean isLeafNode;
  ArrayList<SearchResult> childEntries = new ArrayList<SearchResult>();
  boolean differential;
  Exception exception;
  Object exceptionArg;
 
 
  /**
   * The constructor of the refresher object.
   * @param node the node on the tree to be updated.
   * @param ctlr the BrowserController.
   * @param localEntry the local entry corresponding to the node.
   * @param recursive whether this task is recursive or not (children must be
   * searched).
   */
  public NodeRefresher(BasicNode node, BrowserController ctlr,
      SearchResult localEntry, boolean recursive) {
    super(node);
    controller = ctlr;
    state = State.QUEUED;
    this.recursive = recursive;
 
    this.localEntry = localEntry;
  }
 
 
  /**
   * Returns the local entry the refresher is handling.
   * @return the local entry the refresher is handling.
   */
  public SearchResult getLocalEntry() {
    return localEntry;
  }
 
 
  /**
   * Returns the remote entry for the node.  It will be <CODE>null</CODE> if
   * the entry is not a referral.
   * @return the remote entry for the node.
   */
  public SearchResult getRemoteEntry() {
    return remoteEntry;
  }
 
  /**
   * Returns the URL of the remote entry.  It will be <CODE>null</CODE> if
   * the entry is not a referral.
   * @return the URL of the remote entry.
   */
  public LDAPURL getRemoteUrl() {
    return remoteUrl;
  }
 
 
  /**
   * Tells whether the node is a leaf or not.
   * @return <CODE>true</CODE> if the node is a leaf and <CODE>false</CODE>
   * otherwise.
   */
  public boolean isLeafNode() {
    return isLeafNode;
  }
 
 
  /**
   * Returns the child entries of the node.
   * @return the child entries of the node.
   */
  public ArrayList<SearchResult> getChildEntries() {
    return childEntries;
  }
 
  /**
   * Returns whether this refresher object is working on differential mode or
   * not.
   * @return <CODE>true</CODE> if the refresher is working on differential
   * mode and <CODE>false</CODE> otherwise.
   */
  public boolean isDifferential() {
    return differential;
  }
 
  /**
   * Returns the exception that occurred during the processing.  It returns
   * <CODE>null</CODE> if no exception occurred.
   * @return the exception that occurred during the processing.
   */
  public Exception getException() {
    return exception;
  }
 
 
  /**
   * Returns the argument of the exception that occurred during the processing.
   * It returns <CODE>null</CODE> if no exception occurred or if the exception
   * has no arguments.
   * @return the argument exception that occurred during the processing.
   */
  public Object getExceptionArg() {
    return exceptionArg;
  }
 
 
  /**
   * Returns the displayed entry in the browser.  This depends on the
   * visualization options in the BrowserController.
   * @return the remote entry if the entry is a referral and the
   * BrowserController is following referrals and the local entry otherwise.
   */
  public SearchResult getDisplayedEntry() {
    SearchResult result;
    if (controller.getFollowReferrals() && (remoteEntry != null)) {
      result = remoteEntry;
    }
    else {
      result = localEntry;
    }
    return result;
  }
 
  /**
   * Returns the LDAP URL of the displayed entry in the browser.  This depends
   * on the visualization options in the BrowserController.
   * @return the remote entry LDAP URL if the entry is a referral and the
   * BrowserController is following referrals and the local entry LDAP URL
   * otherwise.
   */
  public LDAPURL getDisplayedUrl() {
    LDAPURL result;
    if (controller.getFollowReferrals() && (remoteUrl != null)) {
      result = remoteUrl;
    }
    else {
      result = controller.findUrlForLocalEntry(getNode());
    }
    return result;
  }
 
  /**
   * Returns whether the refresh is over or not.
   * @return <CODE>true</CODE> if the refresh is over and <CODE>false</CODE>
   * otherwise.
   */
  public boolean isInFinalState() {
    return (
      (state == State.FINISHED) ||
        (state == State.CANCELLED) ||
        (state == State.FAILED) ||
        (state == State.INTERRUPTED)
    );
  }
 
  /**
   * The method that actually does the refresh.
   */
  @Override
  public void run() {
    final BasicNode node = getNode();
 
    try {
      boolean checkExpand = false;
      if (localEntry == null) {
        changeStateTo(State.READING_LOCAL_ENTRY);
        runReadLocalEntry();
      }
      if (!isInFinalState()) {
        if (controller.getFollowReferrals() && isReferralEntry(localEntry)) {
          changeStateTo(State.SOLVING_REFERRAL);
          runSolveReferral();
        }
        if (node.isLeaf()) {
          changeStateTo(State.DETECTING_CHILDREN);
          runDetectChildren();
        }
        if (controller.nodeIsExpanded(node) && recursive) {
          changeStateTo(State.SEARCHING_CHILDREN);
          runSearchChildren();
          /* If the node is not expanded, we have to refresh its children
            when we expand it */
        } else if (recursive  && (!node.isLeaf() || !isLeafNode)) {
          node.setRefreshNeededOnExpansion(true);
          checkExpand = true;
        }
        changeStateTo(State.FINISHED);
        if (checkExpand && mustAutomaticallyExpand(node))
        {
          SwingUtilities.invokeLater(new Runnable()
          {
            @Override
            public void run()
            {
              controller.expandNode(node);
            }
          });
        }
      }
    }
    catch (NamingException ne)
    {
      exception = ne;
      exceptionArg = null;
    }
    catch(SearchAbandonException x) {
      exception = x.getException();
      exceptionArg = x.getArg();
      try {
        changeStateTo(x.getState());
      }
      catch(SearchAbandonException xx) {
        // We've done all what we can...
      }
    }
  }
 
  /**
   * Tells whether a custom filter is being used (specified by the user in the
   * browser dialog) or not.
   * @return <CODE>true</CODE> if a custom filter is being used and
   * <CODE>false</CODE> otherwise.
   */
  private boolean useCustomFilter()
  {
    boolean result=false;
    if (controller.getFilter()!=null)
      result =
        !controller.getFilter().equals(BrowserController.ALL_OBJECTS_FILTER);
    return result;
  }
 
  /**
   * Performs the search in the case the user specified a custom filter.
   * @param node the parent node we perform the search from.
   * @param ctx the connection to be used.
   * @throws NamingException if a problem occurred.
   */
  private void searchForCustomFilter(BasicNode node, InitialLdapContext ctx)
  throws NamingException
  {
    SearchControls ctls = controller.getBasicSearchControls();
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setReturningAttributes(new String[] { SchemaConstants.NO_ATTRIBUTES });
    ctls.setCountLimit(1);
    NamingEnumeration<SearchResult> s = ctx.search(new LdapName(node.getDN()),
              controller.getFilter(),
              ctls);
    try
    {
      if (!s.hasMore())
      {
        throw new NameNotFoundException("Entry "+node.getDN()+
            " does not verify filter "+controller.getFilter());
      }
      while (s.hasMore())
      {
        s.next();
      }
    }
    catch (SizeLimitExceededException slme)
    {
      // We are just searching for an entry, but if there is more than one
      // this exception will be thrown.  We call sr.hasMore after the
      // first entry has been retrieved to avoid sending a systematic
      // abandon when closing the s NamingEnumeration.
      // See CR 6976906.
    }
    finally
    {
      s.close();
    }
  }
 
  /**
   * Performs the search in the case the user specified a custom filter.
   * @param dn the parent DN we perform the search from.
   * @param ctx the connection to be used.
   * @throws NamingException if a problem occurred.
   */
  private void searchForCustomFilter(String dn, InitialLdapContext ctx)
  throws NamingException
  {
    SearchControls ctls = controller.getBasicSearchControls();
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setReturningAttributes(new String[]{});
    ctls.setCountLimit(1);
    NamingEnumeration<SearchResult> s = ctx.search(new LdapName(dn),
              controller.getFilter(),
              ctls);
    try
    {
      if (!s.hasMore())
      {
        throw new NameNotFoundException("Entry "+dn+
            " does not verify filter "+controller.getFilter());
      }
      while (s.hasMore())
      {
        s.next();
      }
    }
    catch (SizeLimitExceededException slme)
    {
      // We are just searching for an entry, but if there is more than one
      // this exception will be thrown.  We call sr.hasMore after the
      // first entry has been retrieved to avoid sending a systematic
      // abandon when closing the s NamingEnumeration.
      // See CR 6976906.
    }
    finally
    {
      s.close();
    }
  }
 
  /**
   * Read the local entry associated to the current node.
   */
  private void runReadLocalEntry() throws SearchAbandonException {
    BasicNode node = getNode();
    InitialLdapContext ctx = null;
    try {
      ctx = controller.findConnectionForLocalEntry(node);
 
      if (ctx != null) {
        if (useCustomFilter())
        {
          // Check that the entry verifies the filter
          searchForCustomFilter(node, ctx);
        }
 
        SearchControls ctls = controller.getBasicSearchControls();
        ctls.setReturningAttributes(controller.getAttrsForRedSearch());
        ctls.setSearchScope(SearchControls.OBJECT_SCOPE);
 
        NamingEnumeration<SearchResult> s =
                ctx.search(new LdapName(node.getDN()),
                controller.getObjectSearchFilter(),
                ctls);
        try
        {
          while (s.hasMore())
          {
            localEntry = s.next();
            localEntry.setName(node.getDN());
 
          }
        }
        finally
        {
          s.close();
        }
        if (localEntry == null) {
          /* Not enough rights to read the entry or the entry simply does not
           exist */
          throw new NameNotFoundException("Can't find entry: "+node.getDN());
        }
        throwAbandonIfNeeded(null);
      } else {
          changeStateTo(State.FINISHED);
      }
    }
    catch(NamingException x) {
        throwAbandonIfNeeded(x);
    }
    finally {
      if (ctx != null) {
        controller.releaseLDAPConnection(ctx);
      }
    }
  }
 
  /**
   * Solve the referral associated to the current node.
   * This routine assumes that node.getReferral() is non null
   * and that BrowserController.getFollowReferrals() == true.
   * It also protect the browser against looping referrals by
   * limiting the number of hops.
   * @throws SearchAbandonException if the hop count limit for referrals has
   * been exceeded.
   * @throws NamingException if an error occurred searching the entry.
   */
  private void runSolveReferral()
  throws SearchAbandonException, NamingException {
    int hopCount = 0;
    String[] referral = getNode().getReferral();
    while ((referral != null) && (hopCount < 10)) {
      readRemoteEntry(referral);
      referral = BrowserController.getReferral(remoteEntry);
      hopCount++;
    }
    if (referral != null) { // -> hopCount has reached the max
      throwAbandonIfNeeded(new ReferralLimitExceededException(
          AdminToolMessages.ERR_REFERRAL_LIMIT_EXCEEDED.get(hopCount)));
    }
  }
 
  /**
   * Searches for the remote entry.
   * @param referral the referral list to be used to search the remote entry.
   * @throws SearchAbandonException if an error occurs.
   */
  private void readRemoteEntry(String[] referral)
  throws SearchAbandonException {
    LDAPConnectionPool connectionPool = controller.getConnectionPool();
    LDAPURL url = null;
    SearchResult entry = null;
    String remoteDn = null;
    Exception lastException = null;
    Object lastExceptionArg = null;
 
    int i = 0;
    while ((i < referral.length) && (entry == null)) {
      InitialLdapContext ctx = null;
      try {
        url = LDAPURL.decode(referral[i], false);
        if (url.getHost() == null)
        {
          // Use the local server connection.
          ctx = controller.getUserDataConnection();
          url.setHost(ConnectionUtils.getHostName(ctx));
          url.setPort(ConnectionUtils.getPort(ctx));
          url.setScheme(ConnectionUtils.isSSL(ctx)?"ldaps":"ldap");
        }
        ctx = connectionPool.getConnection(url);
        remoteDn = url.getRawBaseDN();
        if ((remoteDn == null) ||
          remoteDn.equals("")) {
          /* The referral has not a target DN specified: we
             have to use the DN of the entry that contains the
             referral... */
          if (remoteEntry != null) {
            remoteDn = remoteEntry.getName();
          } else {
            remoteDn = localEntry.getName();
          }
          /* We have to recreate the url including the target DN
             we are using */
          url = new LDAPURL(url.getScheme(), url.getHost(), url.getPort(),
              remoteDn, url.getAttributes(), url.getScope(), url.getRawFilter(),
                 url.getExtensions());
        }
        if (useCustomFilter() && url.getScope() == SearchScope.BASE_OBJECT)
        {
          // Check that the entry verifies the filter
          searchForCustomFilter(remoteDn, ctx);
        }
 
        int scope = getJNDIScope(url);
        String filter = getJNDIFilter(url);
 
        SearchControls ctls = controller.getBasicSearchControls();
        ctls.setReturningAttributes(controller.getAttrsForBlackSearch());
        ctls.setSearchScope(scope);
        ctls.setCountLimit(1);
        NamingEnumeration<SearchResult> sr = ctx.search(remoteDn,
            filter,
            ctls);
        try
        {
          boolean found = false;
          while (sr.hasMore())
          {
            entry = sr.next();
            String name;
            if (entry.getName().length() == 0)
            {
              name = remoteDn;
            }
            else
            {
              name = unquoteRelativeName(entry.getName())+","+remoteDn;
            }
            entry.setName(name);
            found = true;
          }
          if (!found)
          {
            throw new NameNotFoundException();
          }
        }
        catch (SizeLimitExceededException sle)
        {
          // We are just searching for an entry, but if there is more than one
          // this exception will be thrown.  We call sr.hasMore after the
          // first entry has been retrieved to avoid sending a systematic
          // abandon when closing the sr NamingEnumeration.
          // See CR 6976906.
        }
        finally
        {
          sr.close();
        }
        throwAbandonIfNeeded(null);
      }
      catch (InterruptedNamingException x) {
        throwAbandonIfNeeded(x);
      }
      catch (NamingException x) {
        lastException = x;
        lastExceptionArg = referral[i];
      }
      catch (DirectoryException de) {
        lastException = de;
        lastExceptionArg = referral[i];
      }
      finally {
        if (ctx != null) {
          connectionPool.releaseConnection(ctx);
        }
      }
      i = i + 1;
    }
    if (entry == null) {
      throw new SearchAbandonException(
          State.FAILED, lastException, lastExceptionArg);
    }
    else
    {
      if (url.getScope() != SearchScope.BASE_OBJECT)
      {
        // The URL is to be transformed: the code assumes that the URL points
        // to the remote entry.
        url = new LDAPURL(url.getScheme(), url.getHost(),
            url.getPort(), entry.getName(), url.getAttributes(),
            SearchScope.BASE_OBJECT, null, url.getExtensions());
      }
      checkLoopInReferral(url, referral[i-1]);
      remoteUrl = url;
      remoteEntry = entry;
    }
  }
 
  /**
   * Tells whether the provided node must be automatically expanded or not.
   * This is used when the user provides a custom filter, in this case we
   * expand automatically the tree.
   * @param node the node to analyze.
   * @return <CODE>true</CODE> if the node must be expanded and
   * <CODE>false</CODE> otherwise.
   */
  private boolean mustAutomaticallyExpand(BasicNode node)
  {
    boolean mustAutomaticallyExpand = false;
    if (controller.isAutomaticExpand())
    {
      // Limit the number of expansion levels to 3
      int nLevels = 0;
      TreeNode parent = node;
      while (parent != null)
      {
        nLevels ++;
        parent = parent.getParent();
      }
      mustAutomaticallyExpand = nLevels <= 4;
    }
    return mustAutomaticallyExpand;
  }
 
  /**
   * Detects whether the entries has children or not.
   * @throws SearchAbandonException if the search was abandoned.
   * @throws NamingException if an error during the search occurred.
   */
  private void runDetectChildren()
  throws SearchAbandonException, NamingException {
    if (controller.isShowContainerOnly() || !isNumSubOrdinatesUsable()) {
      runDetectChildrenManually();
    }
    else {
      SearchResult entry = getDisplayedEntry();
      isLeafNode = !BrowserController.getHasSubOrdinates(entry);
    }
  }
 
 
  /**
   * Detects whether the entry has children by performing a search using the
   * entry as base DN.
   * @throws SearchAbandonException if there is an error.
   */
  private void runDetectChildrenManually() throws SearchAbandonException {
    BasicNode parentNode = getNode();
    InitialLdapContext ctx = null;
    NamingEnumeration<SearchResult> searchResults = null;
 
    try {
      // We set the search constraints so that only one entry is returned.
      // It's enough to know if the entry has children or not.
      SearchControls ctls = controller.getBasicSearchControls();
      ctls.setCountLimit(1);
      ctls.setReturningAttributes(
          new String[] { SchemaConstants.NO_ATTRIBUTES });
      if (useCustomFilter())
      {
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
      }
      else
      {
        ctls.setSearchScope(SearchControls.OBJECT_SCOPE);
      }
      // Send an LDAP search
      ctx = controller.findConnectionForDisplayedEntry(parentNode);
      searchResults = ctx.search(
          new LdapName(controller.findBaseDNForChildEntries(parentNode)),
          controller.getChildSearchFilter(),
          ctls);
 
      throwAbandonIfNeeded(null);
      isLeafNode = true;
      // Check if parentNode has children
      while (searchResults.hasMoreElements()) {
        isLeafNode = false;
      }
    }
    catch (SizeLimitExceededException e)
    {
      // We are just searching for an entry, but if there is more than one
      // this exception will be thrown.  We call sr.hasMore after the
      // first entry has been retrieved to avoid sending a systematic
      // abandon when closing the searchResults NamingEnumeration.
      // See CR 6976906.
    }
    catch (NamingException x) {
      throwAbandonIfNeeded(x);
    }
    finally {
      if (ctx != null) {
        controller.releaseLDAPConnection(ctx);
      }
      if (searchResults != null)
      {
        try
        {
          searchResults.close();
        }
        catch (NamingException x)
        {
          throwAbandonIfNeeded(x);
        }
      }
    }
  }
 
 
  // NUMSUBORDINATE HACK
  // numsubordinates is not usable if the displayed entry
  // is listed in in the hacker.
  // Note: *usable* means *usable for detecting children presence*.
  private boolean isNumSubOrdinatesUsable() throws NamingException {
    boolean result;
    SearchResult entry = getDisplayedEntry();
    boolean hasSubOrdinates = BrowserController.getHasSubOrdinates(entry);
    if (!hasSubOrdinates) { // We must check
      LDAPURL url = getDisplayedUrl();
      if (controller.getNumSubordinateHacker().contains(url)) {
        // The numSubOrdinate we have is unreliable.
        result = false;
//        System.out.println("numSubOrdinates of " + url +
//                           " is not reliable");
      }
      else {
        result = true;
      }
    }
    else { // Other values are usable
      result = true;
    }
    return result;
  }
 
 
 
  /**
   * Searchs for the children.
   * @throws SearchAbandonException if an error occurs.
   */
  private void runSearchChildren() throws SearchAbandonException {
    InitialLdapContext ctx = null;
    BasicNode parentNode = getNode();
    parentNode.setSizeLimitReached(false);
 
    try {
      // Send an LDAP search
      SearchControls ctls = controller.getBasicSearchControls();
      if (useCustomFilter())
      {
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
      }
      else
      {
        ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
      }
      ctls.setReturningAttributes(controller.getAttrsForRedSearch());
      ctx = controller.findConnectionForDisplayedEntry(parentNode);
      String parentDn = controller.findBaseDNForChildEntries(parentNode);
      int parentComponents;
      try
      {
        DN dn = DN.valueOf(parentDn);
        parentComponents = dn.size();
      }
      catch (Throwable t)
      {
        throw new RuntimeException("Error decoding dn: "+parentDn+" . "+t,
            t);
      }
      NamingEnumeration<SearchResult> entries = ctx.search(
            new LdapName(parentDn),
                controller.getChildSearchFilter(),
                ctls);
 
      try
      {
        while (entries.hasMore())
        {
          SearchResult r = entries.next();
          String name;
          if (r.getName().length() == 0)
          {
            continue;
          }
          else
          {
            name = unquoteRelativeName(r.getName())+","+parentDn;
          }
          boolean add = false;
          if (useCustomFilter())
          {
            // Check that is an immediate child: use a faster method by just
            // comparing the number of components.
            DN dn = null;
            try
            {
              dn = DN.valueOf(name);
              add = dn.size() == parentComponents + 1;
            }
            catch (Throwable t)
            {
              throw new RuntimeException("Error decoding dns: "+t, t);
            }
 
            if (!add)
            {
              // Is not a direct child.  Check if the parent has been added,
              // if it is the case, do not add the parent.  If is not the case,
              // search for the parent and add it.
              RDN[] rdns = new RDN[parentComponents + 1];
              int diff = dn.size() - rdns.length;
              for (int i=0; i < rdns.length; i++)
              {
                rdns[i] = dn.getRDN(i + diff);
              }
              final DN parentToAddDN = new DN(rdns);
              boolean mustAddParent = true;
              for (SearchResult addedEntry : childEntries)
              {
                try
                {
                  DN addedDN = DN.valueOf(addedEntry.getName());
                  if (addedDN.equals(parentToAddDN))
                  {
                    mustAddParent = false;
                    break;
                  }
                }
                catch (Throwable t)
                {
                  throw new RuntimeException("Error decoding dn: "+
                      addedEntry.getName()+" . "+t, t);
                }
              }
              if (mustAddParent)
              {
                final boolean resultValue[] = {true};
                // Check the children added to the tree
                try
                {
                  SwingUtilities.invokeAndWait(new Runnable()
                  {
                    @Override
                    public void run()
                    {
                      for (int i=0; i<getNode().getChildCount(); i++)
                      {
                        BasicNode node = (BasicNode)getNode().getChildAt(i);
                        try
                        {
                          DN dn = DN.valueOf(node.getDN());
                          if (dn.equals(parentToAddDN))
                          {
                            resultValue[0] = false;
                            break;
                          }
                        }
                        catch (Throwable t)
                        {
                          throw new RuntimeException("Error decoding dn: "+
                              node.getDN()+" . "+t, t);
                        }
                      }
                    }
                  });
                }
                catch (Throwable t)
                {
                  // Ignore
                }
                mustAddParent = resultValue[0];
              }
              if (mustAddParent)
              {
                SearchResult parentResult = searchManuallyEntry(ctx,
                    parentToAddDN.toString());
                childEntries.add(parentResult);
              }
            }
          }
          else
          {
            add = true;
          }
          if (add)
          {
            r.setName(name);
            childEntries.add(r);
            // Time to time we update the display
            if (childEntries.size() >= 20) {
              changeStateTo(State.SEARCHING_CHILDREN);
              childEntries.clear();
            }
          }
          throwAbandonIfNeeded(null);
        }
      }
      finally
      {
        entries.close();
      }
    }
    catch (SizeLimitExceededException slee)
    {
      parentNode.setSizeLimitReached(true);
    }
    catch (NamingException x) {
      throwAbandonIfNeeded(x);
    }
    finally {
      if (ctx != null)
      {
        controller.releaseLDAPConnection(ctx);
      }
    }
  }
 
  /**
   * Returns the entry for the given dn.
   * The code assumes that the request controls are set in the connection.
   * @param ctx the connection to be used.
   * @param dn the DN of the entry to be searched.
   * @throws NamingException if an error occurs.
   */
  private SearchResult searchManuallyEntry(InitialLdapContext ctx, String dn)
  throws NamingException
  {
    SearchResult sr = null;
//  Send an LDAP search
    SearchControls ctls = controller.getBasicSearchControls();
    ctls.setSearchScope(SearchControls.OBJECT_SCOPE);
    ctls.setReturningAttributes(controller.getAttrsForRedSearch());
    NamingEnumeration<SearchResult> entries = ctx.search(
          new LdapName(dn),
              controller.getObjectSearchFilter(),
              ctls);
 
    try
    {
      while (entries.hasMore())
      {
        sr = entries.next();
        sr.setName(dn);
      }
    }
    finally
    {
      entries.close();
    }
    return sr;
  }
 
 
  /**
   * Utilities
   */
 
 
  /**
   * Change the state of the task and inform the BrowserController.
   * @param newState the new state for the refresher.
   */
  private void changeStateTo(State newState) throws SearchAbandonException {
    State oldState = state;
    state = newState;
    try {
      controller.invokeRefreshTaskDidProgress(this, oldState, newState);
    }
    catch(InterruptedException x) {
      throwAbandonIfNeeded(x);
    }
  }
 
 
  /**
   * Transform an exception into a TaskAbandonException.
   * If no exception is passed, the routine checks if the task has
   * been canceled and throws an TaskAbandonException accordingly.
   * @param x the exception.
   * @throws SearchAbandonException if the task/refresher must be abandoned.
   */
  private void throwAbandonIfNeeded(Exception x) throws SearchAbandonException {
    SearchAbandonException tax = null;
    if (x != null) {
      if ((x instanceof InterruptedException) ||
          (x instanceof InterruptedNamingException)) {
        tax = new SearchAbandonException(State.INTERRUPTED, x, null);
      }
      else {
        tax = new SearchAbandonException(State.FAILED, x, null);
      }
    }
    else if (isCanceled()) {
      tax = new SearchAbandonException(State.CANCELLED, null, null);
    }
    if (tax != null) {
      throw tax;
    }
  }
 
  /**
   * Removes the quotes surrounding the provided name.  JNDI can return relative
   * names with this format.
   * @param name the relative name to be treated.
   * @return an String representing the provided relative name without
   * surrounding quotes.
   */
  private String unquoteRelativeName(String name)
  {
    if ((name.length() > 0) && (name.charAt(0) == '"'))
    {
      if (name.charAt(name.length() - 1) == '"')
      {
        return name.substring(1, name.length() - 1);
      }
      else
      {
        return name.substring(1);
      }
    }
    else
    {
      return name;
    }
  }
 
  /**
   * DEBUG : Dump the state of the task.
   */
  void dump() {
    System.out.println("=============");
    System.out.println("         node: " + getNode().getDN());
    System.out.println("    recursive: " + recursive);
    System.out.println(" differential: " + differential);
 
    System.out.println("        state: " + state);
    System.out.println("   localEntry: " + localEntry);
    System.out.println("  remoteEntry: " + remoteEntry);
    System.out.println("    remoteUrl: " + remoteUrl);
    System.out.println("   isLeafNode: " + isLeafNode);
    System.out.println("    exception: " + exception);
    System.out.println(" exceptionArg: " + exceptionArg);
    System.out.println("=============");
  }
 
 
  /**
   * Checks that the entry's objectClass contains 'referral' and that the
   * attribute 'ref' is present.
   * @param entry the search result.
   * @return <CODE>true</CODE> if the entry's objectClass contains 'referral'
   * and the attribute 'ref' is present and <CODE>false</CODE> otherwise.
   * @throws NamingException if an error occurs.
   */
  static boolean isReferralEntry(SearchResult entry) throws NamingException {
    boolean result = false;
    Set<String> ocValues = ConnectionUtils.getValues(entry, "objectClass");
    if (ocValues != null) {
      for (String value : ocValues)
      {
        boolean isReferral = value.equalsIgnoreCase("referral");
 
        if (isReferral) {
          result = (ConnectionUtils.getFirstValue(entry, "ref") != null);
          break;
        }
      }
    }
    return result;
  }
 
  /**
   * Returns the scope to be used in a JNDI request based on the information
   * of an LDAP URL.
   * @param url the LDAP URL.
   * @return the scope to be used in a JNDI request.
   */
  private int getJNDIScope(LDAPURL url)
  {
    int scope;
    if (url.getScope() != null)
    {
      switch (url.getScope().asEnum())
      {
      case BASE_OBJECT:
        scope = SearchControls.OBJECT_SCOPE;
        break;
      case WHOLE_SUBTREE:
        scope = SearchControls.SUBTREE_SCOPE;
        break;
      case SUBORDINATES:
        scope = SearchControls.ONELEVEL_SCOPE;
        break;
      case SINGLE_LEVEL:
        scope = SearchControls.ONELEVEL_SCOPE;
        break;
      default:
        scope = SearchControls.OBJECT_SCOPE;
      }
    }
    else
    {
      scope = SearchControls.OBJECT_SCOPE;
    }
    return scope;
  }
 
  /**
   * Returns the filter to be used in a JNDI request based on the information
   * of an LDAP URL.
   * @param url the LDAP URL.
   * @return the filter.
   */
  private String getJNDIFilter(LDAPURL url)
  {
    String filter = url.getRawFilter();
    if (filter == null)
    {
      filter = controller.getObjectSearchFilter();
    }
    return filter;
  }
 
  /**
   * Check that there is no loop in terms of DIT (the check basically identifies
   * whether we are pointing to an entry above in the same server).
   * @param url the URL to the remote entry.  It is assumed that the base DN
   * of the URL points to the remote entry.
   * @param referral the referral used to retrieve the remote entry.
   * @throws SearchAbandonException if there is a loop issue (the remoteEntry
   * is actually an entry in the same server as the local entry but above in the
   * DIT).
   */
  private void checkLoopInReferral(LDAPURL url,
      String referral) throws SearchAbandonException
  {
    boolean checkSucceeded = true;
    try
    {
      DN dn1 = DN.valueOf(getNode().getDN());
      DN dn2 = url.getBaseDN();
      if (dn2.isAncestorOf(dn1))
      {
        String host = url.getHost();
        int port = url.getPort();
        String adminHost = ConnectionUtils.getHostName(
            controller.getConfigurationConnection());
        int adminPort =
          ConnectionUtils.getPort(controller.getConfigurationConnection());
        checkSucceeded = (port != adminPort) ||
        !adminHost.equalsIgnoreCase(host);
 
        if (checkSucceeded)
        {
          String hostUserData = ConnectionUtils.getHostName(
              controller.getUserDataConnection());
          int portUserData =
            ConnectionUtils.getPort(controller.getUserDataConnection());
          checkSucceeded = (port != portUserData) ||
          !hostUserData.equalsIgnoreCase(host);
        }
      }
    }
    catch (OpenDsException odse)
    {
      // Ignore
    }
    if (!checkSucceeded)
    {
      throw new SearchAbandonException(
          State.FAILED, new ReferralLimitExceededException(
              ERR_CTRL_PANEL_REFERRAL_LOOP.get(url.getRawBaseDN())), referral);
    }
  }
}