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

jvergara
09.28.2009 06ec8c88556b02782c7b91a233de91eaf4a1439d
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
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
/*
 * 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
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE
 * or https://OpenDS.dev.java.net/OpenDS.LICENSE.
 * 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
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE.  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-2009 Sun Microsystems, Inc.
 */
 
package org.opends.guitools.controlpanel.datamodel;
 
import java.io.File;
import java.net.InetAddress;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.logging.Level;
import java.util.logging.Logger;
 
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
 
import org.opends.admin.ads.util.ApplicationTrustManager;
import org.opends.admin.ads.util.ConnectionUtils;
import org.opends.guitools.controlpanel.browser.IconPool;
import org.opends.guitools.controlpanel.browser.LDAPConnectionPool;
import org.opends.guitools.controlpanel.event.BackendPopulatedEvent;
import org.opends.guitools.controlpanel.event.BackendPopulatedListener;
import org.opends.guitools.controlpanel.event.BackupCreatedEvent;
import org.opends.guitools.controlpanel.event.BackupCreatedListener;
import org.opends.guitools.controlpanel.event.ConfigChangeListener;
import org.opends.guitools.controlpanel.event.ConfigurationChangeEvent;
import org.opends.guitools.controlpanel.event.IndexModifiedEvent;
import org.opends.guitools.controlpanel.event.IndexModifiedListener;
import org.opends.guitools.controlpanel.task.Task;
import org.opends.guitools.controlpanel.util.ConfigFromDirContext;
import org.opends.guitools.controlpanel.util.ConfigFromFile;
import org.opends.guitools.controlpanel.util.ConfigReader;
import org.opends.guitools.controlpanel.util.Utilities;
import org.opends.quicksetup.util.UIKeyStore;
import org.opends.quicksetup.util.Utils;
import org.opends.server.tools.ConfigureWindowsService;
 
/**
 * This is the classes that is shared among all the different places in the
 * Control Panel.  It contains information about the server status and
 * configuration and some objects that are shared everywhere.
 *
 */
public class ControlPanelInfo
{
  private long poolingPeriod = 20000;
 
  private ServerDescriptor serverDesc;
  private Set<Task> tasks = new HashSet<Task>();
  private InitialLdapContext ctx;
  private InitialLdapContext userDataCtx;
  private final LDAPConnectionPool connectionPool = new LDAPConnectionPool();
  // Used by the browsers
  private final IconPool iconPool = new IconPool(); // Used by the browsers
  private Thread poolingThread;
  private boolean stopPooling;
  private boolean pooling;
  private ApplicationTrustManager trustManager;
  private ConnectionProtocolPolicy connectionPolicy =
    ConnectionProtocolPolicy.USE_MOST_SECURE_AVAILABLE;
  private String ldapURL;
  private String startTLSURL;
  private String ldapsURL;
  private String adminConnectorURL;
  private String localAdminConnectorURL;
  private String lastWorkingBindDN;
  private String lastWorkingBindPwd;
  private String lastRemoteHostName;
  private String lastRemoteAdministrationURL;
 
  private static boolean mustDeregisterConfig;
 
  private boolean isLocal = true;
 
  private Set<AbstractIndexDescriptor> modifiedIndexes =
    new HashSet<AbstractIndexDescriptor>();
 
  private LinkedHashSet<ConfigChangeListener> configListeners =
    new LinkedHashSet<ConfigChangeListener>();
 
 
  private LinkedHashSet<BackupCreatedListener> backupListeners =
    new LinkedHashSet<BackupCreatedListener>();
 
  private LinkedHashSet<BackendPopulatedListener> backendPopulatedListeners =
    new LinkedHashSet<BackendPopulatedListener>();
 
  private LinkedHashSet<IndexModifiedListener> indexListeners =
    new LinkedHashSet<IndexModifiedListener>();
 
  private static final Logger LOG =
    Logger.getLogger(ControlPanelInfo.class.getName());
 
  private static ControlPanelInfo instance;
 
  /**
   * Default constructor.
   *
   */
  protected ControlPanelInfo()
  {
  }
 
  /**
   * Returns a singleton for this instance.
   * @return the control panel info.
   */
  public static ControlPanelInfo getInstance()
  {
    if (instance == null)
    {
      instance = new ControlPanelInfo();
      try
      {
        instance.setTrustManager(
            new ApplicationTrustManager(UIKeyStore.getInstance()));
      }
      catch (Throwable t)
      {
        LOG.log(Level.WARNING, "Error retrieving UI key store: "+t, t);
        instance.setTrustManager(new ApplicationTrustManager(null));
      }
    }
    return instance;
  }
 
  /**
   * Returns the last ServerDescriptor that has been retrieved.
   * @return the last ServerDescriptor that has been retrieved.
   */
  public ServerDescriptor getServerDescriptor()
  {
    return serverDesc;
  }
 
  /**
   * Returns the list of tasks.
   * @return the list of tasks.
   */
  public Set<Task> getTasks()
  {
    return Collections.unmodifiableSet(tasks);
  }
 
  /**
   * Registers a task.  The Control Panel creates a task everytime an operation
   * is made and they are stored here.
   * @param task the task to be registered.
   */
  public void registerTask(Task task)
  {
    tasks.add(task);
  }
 
  /**
   * Tells whether an index must be reindexed or not.
   * @param index the index.
   * @return <CODE>true</CODE> if the index must be reindexed and
   * <CODE>false</CODE> otherwise.
   */
  public boolean mustReindex(AbstractIndexDescriptor index)
  {
    boolean mustReindex = false;
    for (AbstractIndexDescriptor i : modifiedIndexes)
    {
      if (i.getName().equals(index.getName()) &&
          i.getBackend().getBackendID().equals(
              index.getBackend().getBackendID()))
      {
        mustReindex = true;
        break;
      }
    }
    return mustReindex;
  }
 
  /**
   * Registers an index as modified.  This is used by the panels to be able
   * to inform the user that a rebuild of the index is required.
   * @param index the index.
   */
  public void registerModifiedIndex(AbstractIndexDescriptor index)
  {
    modifiedIndexes.add(index);
    indexModified(index);
  }
 
  /**
   * Unregisters a modified index.
   * @param index the index.
   * @return <CODE>true</CODE> if the index is found in the list of modified
   * indexes and <CODE>false</CODE> otherwise.
   */
  public boolean unregisterModifiedIndex(AbstractIndexDescriptor index)
  {
    // We might have stored indexes whose configuration has changed, just remove
    // them if they have the same name, are of the same type and are defined in
    // the same backend.
    Set<AbstractIndexDescriptor> toRemove =
      new HashSet<AbstractIndexDescriptor>();
    for (AbstractIndexDescriptor i : modifiedIndexes)
    {
      if (i.getName().equalsIgnoreCase(index.getName()) &&
          i.getBackend().getBackendID().equalsIgnoreCase(
              index.getBackend().getBackendID()) &&
          i.getClass().equals((index.getClass())))
      {
        toRemove.add(i);
      }
    }
    if (!toRemove.isEmpty())
    {
      boolean returnValue = modifiedIndexes.removeAll(toRemove);
      indexModified(toRemove.iterator().next());
      return returnValue;
    }
    else
    {
      return false;
    }
  }
 
  /**
   * Unregisters all the modified indexes on a given backend.
   * @param backendName the name of the backend.
   */
  public void unregisterModifiedIndexesInBackend(String backendName)
  {
    HashSet<AbstractIndexDescriptor> toDelete =
      new HashSet<AbstractIndexDescriptor>();
    for (AbstractIndexDescriptor index : modifiedIndexes)
    {
      // Compare only the Backend ID, since the backend object attached to
      // the registered index might have changed (for instance the number of
      // entries).  Relying on the backend ID to identify the backend is
      // safe.
      if (index.getBackend().getBackendID().equalsIgnoreCase(backendName))
      {
        toDelete.add(index);
      }
    }
    modifiedIndexes.removeAll(toDelete);
    for (BackendDescriptor backend : getServerDescriptor().getBackends())
    {
      if (backend.getBackendID().equals(backendName))
      {
        IndexModifiedEvent ev = new IndexModifiedEvent(backend);
        for (IndexModifiedListener listener : indexListeners)
        {
          listener.backendIndexesModified(ev);
        }
        break;
      }
    }
  }
 
  /**
   * Returns a collection with all the modified indexes.
   * @return a collection with all the modified indexes.
   */
  public Collection<AbstractIndexDescriptor> getModifiedIndexes()
  {
    return Collections.unmodifiableCollection(modifiedIndexes);
  }
 
  /**
   * Sets the dir context to be used by the ControlPanelInfo to retrieve
   * monitoring and configuration information.
   * @param ctx the connection.
   */
  public void setDirContext(InitialLdapContext ctx)
  {
    this.ctx = ctx;
    if (ctx != null)
    {
      lastWorkingBindDN = ConnectionUtils.getBindDN(ctx);
      lastWorkingBindPwd = ConnectionUtils.getBindPassword(ctx);
      lastRemoteHostName = ConnectionUtils.getHostName(ctx);
      lastRemoteAdministrationURL = ConnectionUtils.getLdapUrl(ctx);
    }
  }
 
  /**
   * Returns the dir context to be used by the ControlPanelInfo to retrieve
   * monitoring and configuration information.
   * @return the dir context to be used by the ControlPanelInfo to retrieve
   * monitoring and configuration information.
   */
  public InitialLdapContext getDirContext()
  {
    return ctx;
  }
 
  /**
   * Sets the dir context to be used by the ControlPanelInfo to retrieve
   * user data.
   * @param ctx the connection.
   * @throws NamingException if there is a problem updating the connection pool.
   */
  public void setUserDataDirContext(InitialLdapContext ctx)
  throws NamingException
  {
    if (userDataCtx != null)
    {
      if (connectionPool.isConnectionRegistered(userDataCtx))
      {
        try
        {
          connectionPool.unregisterConnection(userDataCtx);
        }
        catch (Throwable t)
        {
        }
      }
    }
    this.userDataCtx = ctx;
    if (ctx != null)
    {
      InitialLdapContext cloneLdc =
        ConnectionUtils.cloneInitialLdapContext(userDataCtx,
            ConnectionUtils.getDefaultLDAPTimeout(),
            getTrustManager(), null);
      connectionPool.registerConnection(cloneLdc);
    }
  }
 
  /**
   * Returns the dir context to be used by the ControlPanelInfo to retrieve
   * user data.
   * @return the dir context to be used by the ControlPanelInfo to retrieve
   * user data.
   */
  public InitialLdapContext getUserDataDirContext()
  {
    return userDataCtx;
  }
 
  /**
   * Informs that a backup has been created.  The method will notify to all
   * the backup listeners that a backup has been created.
   * @param newBackup the new created backup.
   */
  public void backupCreated(BackupDescriptor newBackup)
  {
    BackupCreatedEvent ev = new BackupCreatedEvent(newBackup);
    for (BackupCreatedListener listener : backupListeners)
    {
      listener.backupCreated(ev);
    }
  }
 
  /**
   * Informs that a set of backends have been populated.  The method will notify
   * to all the backend populated listeners.
   * @param backends the populated backends.
   */
  public void backendPopulated(Set<BackendDescriptor> backends)
  {
    BackendPopulatedEvent ev = new BackendPopulatedEvent(backends);
    for (BackendPopulatedListener listener : backendPopulatedListeners)
    {
      listener.backendPopulated(ev);
    }
  }
 
  /**
   * Informs that an index has been modified.  The method will notify to all
   * the index listeners that an index has been modified.
   * @param modifiedIndex the modified index.
   */
  public void indexModified(AbstractIndexDescriptor modifiedIndex)
  {
    IndexModifiedEvent ev = new IndexModifiedEvent(modifiedIndex);
    for (IndexModifiedListener listener : indexListeners)
    {
      listener.indexModified(ev);
    }
  }
 
  /**
   * Returns an empty new server descriptor instance.
   * @return an empty new server descriptor instance.
   */
  protected ServerDescriptor createNewServerDescriptorInstance()
  {
    return new ServerDescriptor();
  }
 
  /**
   * Returns a reader that will read the configuration from a file.
   * @return a reader that will read the configuration from a file.
   */
  protected ConfigFromFile createNewConfigFromFileReader()
  {
    return new ConfigFromFile();
  }
 
  /**
   * Returns a reader that will read the configuration from a dir context.
   * @return a reader that will read the configuration from a dir context.
   */
  protected ConfigFromDirContext createNewConfigFromDirContextReader()
  {
    ConfigFromDirContext configFromDirContext = new ConfigFromDirContext();
    configFromDirContext.setIsLocal(isLocal());
    return configFromDirContext;
  }
 
  /**
   * Updates the contents of the server descriptor with the provider reader.
   * @param reader the configuration reader.
   * @param desc the server descriptor.
   */
  protected void updateServerDescriptor(ConfigReader reader,
      ServerDescriptor desc)
  {
    desc.setExceptions(reader.getExceptions());
    desc.setAdministrativeUsers(reader.getAdministrativeUsers());
    desc.setBackends(reader.getBackends());
    desc.setConnectionHandlers(reader.getConnectionHandlers());
    desc.setAdminConnector(reader.getAdminConnector());
    desc.setSchema(reader.getSchema());
    desc.setSchemaEnabled(reader.isSchemaEnabled());
  }
  private int i=0;
  /**
   * Regenerates the last found ServerDescriptor object.
   *
   */
  public synchronized void regenerateDescriptor()
  {
    boolean isLocal = isLocal();
 
    ServerDescriptor desc = createNewServerDescriptorInstance();
    desc.setIsLocal(isLocal);
    InitialLdapContext ctx = getDirContext();
    if (isLocal)
    {
      desc.setOpenDSVersion(
        org.opends.server.util.DynamicConstants.FULL_VERSION_STRING);
      desc.setInstallPath(Utilities.getServerRootDirectory());
      desc.setInstancePath(Utilities.getInstanceRootDirectory(
          Utilities.getServerRootDirectory().getAbsolutePath()));
      boolean windowsServiceEnabled = false;
      if (Utilities.isWindows())
      {
        int result = ConfigureWindowsService.serviceState(null, null);
        windowsServiceEnabled =
          result == ConfigureWindowsService.SERVICE_STATE_ENABLED;
      }
      desc.setWindowsServiceEnabled(windowsServiceEnabled);
    }
    else
    {
      if (lastRemoteHostName != null)
      {
        desc.setHostname(lastRemoteHostName);
      }
    }
    ConfigReader reader;
 
    ServerDescriptor.ServerStatus status = null;
    for (Task task : getTasks())
    {
      if ((task.getType() == Task.Type.START_SERVER) &&
          (task.getState() == Task.State.RUNNING) &&
          isRunningOnServer(desc, task))
      {
        status = ServerDescriptor.ServerStatus.STARTING;
      }
      else if ((task.getType() == Task.Type.STOP_SERVER) &&
          (task.getState() == Task.State.RUNNING) &&
          isRunningOnServer(desc, task))
      {
        status = ServerDescriptor.ServerStatus.STOPPING;
      }
    }
    if (status != null)
    {
      desc.setStatus(status);
      if (status == ServerDescriptor.ServerStatus.STOPPING)
      {
        if (ctx != null)
        {
          try
          {
            ctx.close();
          }
          catch (Throwable t)
          {
          }
          this.ctx = null;
        }
        if (userDataCtx != null)
        {
          if (connectionPool.isConnectionRegistered(userDataCtx))
          {
            try
            {
              connectionPool.unregisterConnection(userDataCtx);
            }
            catch (Throwable t)
            {
            }
          }
          try
          {
            userDataCtx.close();
          }
          catch (Throwable t)
          {
          }
          userDataCtx = null;
        }
      }
      if (isLocal)
      {
        reader = createNewConfigFromFileReader();
        ((ConfigFromFile)reader).readConfiguration();
      }
      else
      {
        reader = null;
      }
      desc.setAuthenticated(false);
    }
    else if (!isLocal ||
        Utilities.isServerRunning(
        Utilities.getInstanceRootDirectory(
            desc.getInstallPath().getAbsolutePath())))
    {
      desc.setStatus(ServerDescriptor.ServerStatus.STARTED);
 
      if ((ctx == null) && (lastWorkingBindDN != null))
      {
        // Try with previous credentials.
        try
        {
          if (isLocal)
          {
            ctx = Utilities.getAdminDirContext(this, lastWorkingBindDN,
              lastWorkingBindPwd);
          }
          else if (lastRemoteAdministrationURL != null)
          {
            ctx = Utils.createLdapsContext(lastRemoteAdministrationURL,
                lastWorkingBindDN,
                lastWorkingBindPwd,
                Utils.getDefaultLDAPTimeout(), null,
                getTrustManager());
          }
        }
        catch (ConfigReadException cre)
        {
//        Ignore: we will ask the user for credentials.
        }
        catch (NamingException ne)
        {
          // Ignore: we will ask the user for credentials.
        }
        if (ctx != null)
        {
          this.ctx = ctx;
        }
      }
 
      if (isLocal && (ctx == null))
      {
        reader = createNewConfigFromFileReader();
        ((ConfigFromFile)reader).readConfiguration();
      }
      else
      {
        if (!isLocal && (ctx == null))
        {
          desc.setStatus(ServerDescriptor.ServerStatus.NOT_CONNECTED_TO_REMOTE);
          reader = null;
        }
        else
        {
          reader = createNewConfigFromDirContextReader();
          ((ConfigFromDirContext)reader).readConfiguration(ctx);
          if (reader.getExceptions().size() > 0)
          {
            // Check the connection
            boolean connectionWorks = false;
            int nMaxErrors = 5;
            for (int i=0; i< nMaxErrors && !connectionWorks; i++)
            {
              try
              {
                Utilities.pingDirContext(ctx);
                connectionWorks = true;
              }
              catch (NamingException ne)
              {
                try
                {
                  Thread.sleep(400);
                }
                catch (Throwable t)
                {
                }
              }
            }
            if (!connectionWorks)
            {
              if (isLocal)
              {
                // Try with offline info
                reader = createNewConfigFromFileReader();
                ((ConfigFromFile)reader).readConfiguration();
              }
              else
              {
                desc.setStatus(
                    ServerDescriptor.ServerStatus.NOT_CONNECTED_TO_REMOTE);
                reader = null;
              }
              try
              {
                ctx.close();
              }
              catch (Throwable t)
              {
              }
              this.ctx = null;
              if (connectionPool.isConnectionRegistered(userDataCtx))
              {
                try
                {
                  connectionPool.unregisterConnection(userDataCtx);
                }
                catch (Throwable t)
                {
                }
              }
              try
              {
                userDataCtx.close();
              }
              catch (Throwable t)
              {
              }
              userDataCtx = null;
            }
          }
        }
      }
      if (reader != null)
      {
        desc.setAuthenticated(reader instanceof ConfigFromDirContext);
        desc.setJavaVersion(reader.getJavaVersion());
        desc.setOpenConnections(reader.getOpenConnections());
        if (reader instanceof ConfigFromDirContext)
        {
          ConfigFromDirContext rCtx = (ConfigFromDirContext)reader;
          desc.setRootMonitor(rCtx.getRootMonitor());
          desc.setEntryCachesMonitor(rCtx.getEntryCaches());
          desc.setJvmMemoryUsageMonitor(rCtx.getJvmMemoryUsage());
          desc.setSystemInformationMonitor(rCtx.getSystemInformation());
          desc.setWorkQueueMonitor(rCtx.getWorkQueue());
          desc.setOpenDSVersion((String)Utilities.getFirstMonitoringValue(
              rCtx.getVersionMonitor(), "fullVersion"));
          String installPath = (String)Utilities.getFirstMonitoringValue(
              rCtx.getSystemInformation(), "installPath");
          if (installPath != null)
          {
            desc.setInstallPath(new File(installPath));
          }
          String instancePath = (String)Utilities.getFirstMonitoringValue(
              rCtx.getSystemInformation(), "instancePath");
          if (instancePath != null)
          {
            desc.setInstancePath(new File(instancePath));
          }
        }
      }
    }
    else
    {
      desc.setStatus(ServerDescriptor.ServerStatus.STOPPED);
      desc.setAuthenticated(false);
      reader = createNewConfigFromFileReader();
      ((ConfigFromFile)reader).readConfiguration();
    }
    if (reader != null)
    {
      updateServerDescriptor(reader, desc);
    }
 
    if ((serverDesc == null) || !serverDesc.equals(desc))
    {
      serverDesc = desc;
      ldapURL = getURL(serverDesc, ConnectionHandlerDescriptor.Protocol.LDAP);
      ldapsURL = getURL(serverDesc, ConnectionHandlerDescriptor.Protocol.LDAPS);
      adminConnectorURL = getAdminConnectorURL(serverDesc);
      if (serverDesc.isLocal())
      {
        localAdminConnectorURL = adminConnectorURL;
      }
      startTLSURL = getURL(serverDesc,
          ConnectionHandlerDescriptor.Protocol.LDAP_STARTTLS);
      ConfigurationChangeEvent ev = new ConfigurationChangeEvent(this, desc);
      for (ConfigChangeListener listener : configListeners)
      {
        listener.configurationChanged(ev);
      }
    }
  }
 
  /**
   * Adds a configuration change listener.
   * @param listener the listener.
   */
  public void addConfigChangeListener(ConfigChangeListener listener)
  {
    configListeners.add(listener);
  }
 
  /**
   * Removes a configuration change listener.
   * @param listener the listener.
   * @return <CODE>true</CODE> if the listener is found and <CODE>false</CODE>
   * otherwise.
   */
  public boolean removeConfigChangeListener(ConfigChangeListener listener)
  {
    return configListeners.remove(listener);
  }
 
  /**
   * Adds a backup creation listener.
   * @param listener the listener.
   */
  public void addBackupCreatedListener(BackupCreatedListener listener)
  {
    backupListeners.add(listener);
  }
 
  /**
   * Removes a backup creation listener.
   * @param listener the listener.
   * @return <CODE>true</CODE> if the listener is found and <CODE>false</CODE>
   * otherwise.
   */
  public boolean removeBackupCreatedListener(BackupCreatedListener listener)
  {
    return backupListeners.remove(listener);
  }
 
  /**
   * Adds a backend populated listener.
   * @param listener the listener.
   */
  public void addBackendPopulatedListener(BackendPopulatedListener listener)
  {
    backendPopulatedListeners.add(listener);
  }
 
  /**
   * Removes a backend populated listener.
   * @param listener the listener.
   * @return <CODE>true</CODE> if the listener is found and <CODE>false</CODE>
   * otherwise.
   */
  public boolean removeBackendPopulatedListener(
      BackendPopulatedListener listener)
  {
    return backendPopulatedListeners.remove(listener);
  }
 
  /**
   * Adds an index modification listener.
   * @param listener the listener.
   */
  public void addIndexModifiedListener(IndexModifiedListener listener)
  {
    indexListeners.add(listener);
  }
 
  /**
   * Removes an index modification listener.
   * @param listener the listener.
   * @return <CODE>true</CODE> if the listener is found and <CODE>false</CODE>
   * otherwise.
   */
  public boolean removeIndexModifiedListener(IndexModifiedListener listener)
  {
    return indexListeners.remove(listener);
  }
 
  /**
   * Starts pooling the server configuration.  The period of the pooling is
   * specified as a parameter.  This method is asynchronous and it will start
   * the pooling in another thread.
   */
  public synchronized void startPooling()
  {
    if (poolingThread != null)
    {
      return;
    }
    pooling = true;
    stopPooling = false;
 
    poolingThread = new Thread(new Runnable()
    {
      public void run()
      {
        try
        {
          while (!stopPooling)
          {
            regenerateDescriptor();
            Thread.sleep(poolingPeriod);
          }
 
        }
        catch (Throwable t)
        {
        }
        pooling = false;
      }
    });
    poolingThread.start();
  }
 
  /**
   * Stops pooling the server.  This method is synchronous, it does not return
   * until the pooling is actually stopped.
   *
   */
  public synchronized void stopPooling()
  {
    stopPooling = true;
    while ((poolingThread != null) && pooling)
    {
      try
      {
        poolingThread.interrupt();
        Thread.sleep(100);
      }
      catch (Throwable t)
      {
        // do nothing;
      }
    }
    poolingThread = null;
    pooling = false;
  }
 
  /**
   * Returns the trust manager to be used by this ControlPanelInfo (and in
   * general by the control panel).
   * @return the trust manager to be used by this ControlPanelInfo.
   */
  public ApplicationTrustManager getTrustManager()
  {
    return trustManager;
  }
 
  /**
   * Sets the trust manager to be used by this ControlPanelInfo (and in
   * general by the control panel).
   * @param trustManager the trust manager to be used by this ControlPanelInfo.
   */
  public void setTrustManager(ApplicationTrustManager trustManager)
  {
    this.trustManager = trustManager;
    connectionPool.setTrustManager(trustManager);
  }
 
  /**
   * Returns the connection policy to be used by this ControlPanelInfo (and in
   * general by the control panel).
   * @return the connection policy to be used by this ControlPanelInfo.
   */
  public ConnectionProtocolPolicy getConnectionPolicy()
  {
    return connectionPolicy;
  }
 
  /**
   * Sets the connection policy to be used by this ControlPanelInfo (and in
   * general by the control panel).
   * @param connectionPolicy the connection policy to be used by this
   * ControlPanelInfo.
   */
  public void setConnectionPolicy(ConnectionProtocolPolicy connectionPolicy)
  {
    this.connectionPolicy = connectionPolicy;
  }
 
  /**
   * Gets the LDAPS URL based in what is read in the configuration. It
   * returns <CODE>null</CODE> if no LDAPS URL was found.
   * @return the LDAPS URL to be used to connect to the server.
   */
  public String getLDAPSURL()
  {
    return ldapsURL;
  }
 
  /**
   * Gets the Administration Connector URL based in what is read in the
   * configuration. It returns <CODE>null</CODE> if no Administration
   * Connector URL was found.
   * @return the Administration Connector URL to be used to connect
   * to the server.
   */
  public String getAdminConnectorURL()
  {
    if (isLocal)
    {
      // If the user set isLocal to true, we want to return the
      // localAdminConnectorURL (in particular if regenerateDescriptor has not
      // been called).
      return localAdminConnectorURL;
    }
    else
    {
      return adminConnectorURL;
    }
  }
 
  /**
   * Gets the Administration Connector URL based in what is read in the local
   * configuration. It returns <CODE>null</CODE> if no Administration
   * Connector URL was found.
   * @return the Administration Connector URL to be used to connect
   * to the local server.
   */
  public String getLocalAdminConnectorURL()
  {
    return localAdminConnectorURL;
  }
 
  /**
   * Gets the LDAP URL based in what is read in the configuration. It
   * returns <CODE>null</CODE> if no LDAP URL was found.
   * @return the LDAP URL to be used to connect to the server.
   */
  public String getLDAPURL()
  {
    return ldapURL;
  }
 
  /**
   * Gets the Start TLS URL based in what is read in the configuration. It
   * returns <CODE>null</CODE> if no Start TLS URL is found.
   * @return the Start TLS URL to be used to connect to the server.
   */
  public String getStartTLSURL()
  {
    return startTLSURL;
  }
 
  /**
   * Returns the LDAP URL to be used to connect to a given ServerDescriptor
   * using a certain protocol. It returns <CODE>null</CODE> if URL for the
   * protocol is not found.
   * @param server the server descriptor.
   * @param protocol the protocol to be used.
   * @return the LDAP URL to be used to connect to a given ServerDescriptor
   * using a certain protocol.
   */
  private static String getURL(ServerDescriptor server,
      ConnectionHandlerDescriptor.Protocol protocol)
  {
    String url = null;
 
    String sProtocol = null;
    switch (protocol)
    {
    case LDAP:
      sProtocol = "ldap";
      break;
    case LDAPS:
      sProtocol = "ldaps";
      break;
    case LDAP_STARTTLS:
      sProtocol = "ldap";
      break;
    case JMX:
      sProtocol = "jmx";
      break;
    case JMXS:
      sProtocol = "jmxs";
      break;
    }
 
    for (ConnectionHandlerDescriptor desc : server.getConnectionHandlers())
    {
      if ((desc.getState() == ConnectionHandlerDescriptor.State.ENABLED) &&
          (desc.getProtocol() == protocol))
      {
        int port = desc.getPort();
        SortedSet<InetAddress> addresses = desc.getAddresses();
        if (addresses.size() == 0)
        {
          if (port > 0)
          {
            url = sProtocol +"://localhost:"+port;
          }
        }
        else
        {
          if (port > 0)
          {
            InetAddress address = addresses.first();
            url = sProtocol +"://"+
            ConnectionUtils.getHostNameForLdapUrl(address.getHostAddress())+":"+
            port;
          }
        }
      }
    }
    return url;
  }
 
  /**
   * Returns the Administration Connector URL.
   * It returns <CODE>null</CODE> if URL for the
   * protocol is not found.
   * @param server the server descriptor.
   * @return the Administration Connector URL.
   */
  private static String getAdminConnectorURL(ServerDescriptor server) {
    String url = null;
 
    ConnectionHandlerDescriptor desc = server.getAdminConnector();
    if (desc != null)
    {
      int port = desc.getPort();
      SortedSet<InetAddress> addresses = desc.getAddresses();
      if (addresses.size() == 0) {
        if (port > 0) {
          url = "ldaps://localhost:" + port;
        }
      } else {
        if (port > 0) {
          InetAddress address = addresses.first();
          url = "ldaps://" +
          ConnectionUtils.getHostNameForLdapUrl(address.getHostAddress()) + ":"
          + port;
        }
      }
    }
    else
    {
      url = null;
    }
    return url;
  }
 
  /**
   * Tells whether we must connect to the server using Start TLS.
   * @return <CODE>true</CODE> if we must connect to the server using Start TLS
   * and <CODE>false</CODE> otherwise.
   */
  public boolean connectUsingStartTLS()
  {
    boolean connectUsingStartTLS = false;
    if (getStartTLSURL() != null)
    {
      connectUsingStartTLS = getStartTLSURL().equals(getURLToConnect());
    }
    return connectUsingStartTLS;
  }
 
  /**
   * Tells whether we must connect to the server using LDAPS.
   * @return <CODE>true</CODE> if we must connect to the server using LDAPS
   * and <CODE>false</CODE> otherwise.
   */
  public boolean connectUsingLDAPS()
  {
    boolean connectUsingLDAPS = false;
    if (getLDAPSURL() != null)
    {
      connectUsingLDAPS = getLDAPSURL().equals(getURLToConnect());
    }
    return connectUsingLDAPS;
  }
 
  /**
   * Returns the URL that must be used to connect to the server based on the
   * available enabled connection handlers in the server and the connection
   * policy.
   * @return the URL that must be used to connect to the server.
   */
  public String getURLToConnect()
  {
    String url;
    switch (getConnectionPolicy())
    {
    case USE_STARTTLS:
      url = getStartTLSURL();
      break;
    case USE_LDAP:
      url = getLDAPURL();
      break;
    case USE_LDAPS:
      url = getLDAPSURL();
      break;
    case USE_ADMIN:
      url = getAdminConnectorURL();
      break;
    case USE_MOST_SECURE_AVAILABLE:
      url = getLDAPSURL();
      if (url == null)
      {
        url = getStartTLSURL();
      }
      if (url == null)
      {
        url = getLDAPURL();
      }
      break;
    case USE_LESS_SECURE_AVAILABLE:
      url = getLDAPURL();
      if (url == null)
      {
        url = getStartTLSURL();
      }
      if (url == null)
      {
        url = getLDAPSURL();
      }
      break;
    default:
      throw new IllegalStateException("Unknown policy: "+getConnectionPolicy());
    }
    return url;
  }
 
  /**
   * Returns <CODE>true</CODE> if the configuration must be deregistered and
   * <CODE>false</CODE> otherwise.
   * This is required when we use the ConfigFileHandler to update the
   * configuration, in these cases cn=config must the deregistered from the
   * ConfigFileHandler and after that register again.
   * @return <CODE>true</CODE> if the configuration must be deregistered and
   * <CODE>false</CODE> otherwise.
   */
  public boolean mustDeregisterConfig()
  {
    return mustDeregisterConfig;
  }
 
  /**
   * Sets whether the configuration must be deregistered or not.
   * @param mustDeregisterConfig whether the configuration must be deregistered
   * or not.
   */
  public void setMustDeregisterConfig(boolean mustDeregisterConfig)
  {
    ControlPanelInfo.mustDeregisterConfig = mustDeregisterConfig;
  }
 
  /**
   * Sets whether the server is local or not.
   * @param isLocal whether the server is local or not.
   */
  public void setIsLocal(boolean isLocal)
  {
    this.isLocal = isLocal;
  }
 
  /**
   * Returns <CODE>true</CODE> if we are trying to manage the local host and
   * <CODE>false</CODE> otherwise.
   * @return <CODE>true</CODE> if we are trying to manage the local host and
   * <CODE>false</CODE> otherwise.
   */
  public boolean isLocal()
  {
    return isLocal;
  }
 
  /**
   * Returns the connection pool to be used by the LDAP entry browsers.
   * @return the connection pool to be used by the LDAP entry browsers.
   */
  public LDAPConnectionPool getConnectionPool()
  {
    return connectionPool;
  }
 
  /**
   * Returns the icon pool to be used by the LDAP entry browsers.
   * @return the icon pool to be used by the LDAP entry browsers.
   */
  public IconPool getIconPool()
  {
    return iconPool;
  }
 
  /**
   * Returns the pooling period in miliseconds.
   * @return the pooling period in miliseconds.
   */
  public long getPoolingPeriod()
  {
    return poolingPeriod;
  }
 
  /**
   * Sets the pooling period in miliseconds.
   * @param poolingPeriod the pooling time in miliseconds.
   */
  public void setPoolingPeriod(long poolingPeriod)
  {
    this.poolingPeriod = poolingPeriod;
  }
 
  /**
   * Returns whether the provided task is running on the provided server or not.
   * The code takes into account that the server object might not be fully
   * initialized (but at least it contains the host name and the instance
   * path if it is local).
   * @param server the server.
   * @param task the task to be analyzed.
   * @return <CODE>true</CODE> if the provided task is running on the provided
   * server and <CODE>false</CODE> otherwise.
   */
  private boolean isRunningOnServer(ServerDescriptor server, Task task)
  {
    boolean isRunningOnServer;
    if (!server.isLocal() || !task.getServer().isLocal())
    {
      if (!server.isLocal())
      {
        // At this point we only have connection information about the new
        // server.  Use the dir context which corresponds to the server to
        // compare things.
        String host1 = server.getHostname();
        String host2 = task.getServer().getHostname();
        if (host1 == null)
        {
          isRunningOnServer = host2 == null;
        }
        else
        {
          isRunningOnServer = host1.equalsIgnoreCase(host2);
        }
        if (isRunningOnServer)
        {
          // Compare administration port;
          int adminPort1 = -1;
          int adminPort2 = -1;
          if (server.getAdminConnector() != null)
          {
            adminPort1 = server.getAdminConnector().getPort();
          }
 
          if (getDirContext() != null)
          {
            adminPort2 = ConnectionUtils.getPort(getDirContext());
          }
          isRunningOnServer = adminPort1 == adminPort2;
        }
      }
      else
      {
        // Compare host names and paths
        File f1 = server.getInstancePath();
        File f2 = task.getServer().getInstancePath();
 
        String host1 = server.getHostname();
        String host2 = task.getServer().getHostname();
        if (host1 == null)
        {
          isRunningOnServer = host2 == null;
        }
        else
        {
          isRunningOnServer = host1.equalsIgnoreCase(host2);
        }
        if (isRunningOnServer)
        {
          if (f1 == null)
          {
            isRunningOnServer = f2 == null;
          }
          else
          {
            isRunningOnServer = f1.equals(f2);
          }
        }
      }
    }
    else
    {
      isRunningOnServer = true;
    }
    return isRunningOnServer;
  }
}